blob: cccab539f89b4d35d1b13711484775adbc07d40a [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
Victor Stinnerce5faf62011-10-05 00:42:43 +020049#ifdef Py_DEBUG
50# define DONT_MAKE_RESULT_READY
51#endif
52
Guido van Rossumd57fd912000-03-10 22:53:23 +000053/* Limit for the Unicode object free list */
54
Christian Heimes2202f872008-02-06 14:31:34 +000055#define PyUnicode_MAXFREELIST 1024
Guido van Rossumd57fd912000-03-10 22:53:23 +000056
57/* Limit for the Unicode object free list stay alive optimization.
58
59 The implementation will keep allocated Unicode memory intact for
60 all objects on the free list having a size less than this
Tim Petersced69f82003-09-16 20:30:58 +000061 limit. This reduces malloc() overhead for small Unicode objects.
Guido van Rossumd57fd912000-03-10 22:53:23 +000062
Christian Heimes2202f872008-02-06 14:31:34 +000063 At worst this will result in PyUnicode_MAXFREELIST *
Guido van Rossumfd4b9572000-04-10 13:51:10 +000064 (sizeof(PyUnicodeObject) + KEEPALIVE_SIZE_LIMIT +
Guido van Rossumd57fd912000-03-10 22:53:23 +000065 malloc()-overhead) bytes of unused garbage.
66
67 Setting the limit to 0 effectively turns the feature off.
68
Guido van Rossumfd4b9572000-04-10 13:51:10 +000069 Note: This is an experimental feature ! If you get core dumps when
70 using Unicode objects, turn this feature off.
Guido van Rossumd57fd912000-03-10 22:53:23 +000071
72*/
73
Guido van Rossumfd4b9572000-04-10 13:51:10 +000074#define KEEPALIVE_SIZE_LIMIT 9
Guido van Rossumd57fd912000-03-10 22:53:23 +000075
76/* Endianness switches; defaults to little endian */
77
78#ifdef WORDS_BIGENDIAN
79# define BYTEORDER_IS_BIG_ENDIAN
80#else
81# define BYTEORDER_IS_LITTLE_ENDIAN
82#endif
83
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000084/* --- Globals ------------------------------------------------------------
85
86 The globals are initialized by the _PyUnicode_Init() API and should
87 not be used before calling that API.
88
89*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000090
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000091
92#ifdef __cplusplus
93extern "C" {
94#endif
95
Victor Stinner910337b2011-10-03 03:20:16 +020096#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020097# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020098#else
99# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
100#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +0200101
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200102#define _PyUnicode_UTF8(op) \
103 (((PyCompactUnicodeObject*)(op))->utf8)
104#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200105 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200106 assert(PyUnicode_IS_READY(op)), \
107 PyUnicode_IS_COMPACT_ASCII(op) ? \
108 ((char*)((PyASCIIObject*)(op) + 1)) : \
109 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +0200110#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200111 (((PyCompactUnicodeObject*)(op))->utf8_length)
112#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200113 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200114 assert(PyUnicode_IS_READY(op)), \
115 PyUnicode_IS_COMPACT_ASCII(op) ? \
116 ((PyASCIIObject*)(op))->length : \
117 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +0200118#define _PyUnicode_WSTR(op) \
119 (((PyASCIIObject*)(op))->wstr)
120#define _PyUnicode_WSTR_LENGTH(op) \
121 (((PyCompactUnicodeObject*)(op))->wstr_length)
122#define _PyUnicode_LENGTH(op) \
123 (((PyASCIIObject *)(op))->length)
124#define _PyUnicode_STATE(op) \
125 (((PyASCIIObject *)(op))->state)
126#define _PyUnicode_HASH(op) \
127 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200128#define _PyUnicode_KIND(op) \
129 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200130 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200131#define _PyUnicode_GET_LENGTH(op) \
132 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200133 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200134#define _PyUnicode_DATA_ANY(op) \
135 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200136
Victor Stinner910337b2011-10-03 03:20:16 +0200137#undef PyUnicode_READY
138#define PyUnicode_READY(op) \
139 (assert(_PyUnicode_CHECK(op)), \
140 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200141 0 : \
142 _PyUnicode_Ready((PyObject *)(op))))
Victor Stinner910337b2011-10-03 03:20:16 +0200143
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200144#define _PyUnicode_READY_REPLACE(p_obj) \
145 (assert(_PyUnicode_CHECK(*p_obj)), \
146 (PyUnicode_IS_READY(*p_obj) ? \
147 0 : _PyUnicode_ReadyReplace((PyObject **)(p_obj))))
148
Victor Stinnerc379ead2011-10-03 12:52:27 +0200149#define _PyUnicode_SHARE_UTF8(op) \
150 (assert(_PyUnicode_CHECK(op)), \
151 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
152 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
153#define _PyUnicode_SHARE_WSTR(op) \
154 (assert(_PyUnicode_CHECK(op)), \
155 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
156
Victor Stinner829c0ad2011-10-03 01:08:02 +0200157/* true if the Unicode object has an allocated UTF-8 memory block
158 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200159#define _PyUnicode_HAS_UTF8_MEMORY(op) \
160 (assert(_PyUnicode_CHECK(op)), \
161 (!PyUnicode_IS_COMPACT_ASCII(op) \
162 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200163 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
164
Victor Stinner03490912011-10-03 23:45:12 +0200165/* true if the Unicode object has an allocated wstr memory block
166 (not shared with other data) */
167#define _PyUnicode_HAS_WSTR_MEMORY(op) \
168 (assert(_PyUnicode_CHECK(op)), \
169 (_PyUnicode_WSTR(op) && \
170 (!PyUnicode_IS_READY(op) || \
171 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
172
Victor Stinner910337b2011-10-03 03:20:16 +0200173/* Generic helper macro to convert characters of different types.
174 from_type and to_type have to be valid type names, begin and end
175 are pointers to the source characters which should be of type
176 "from_type *". to is a pointer of type "to_type *" and points to the
177 buffer where the result characters are written to. */
178#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
179 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200180 to_type *_to = (to_type *) to; \
181 const from_type *_iter = (begin); \
182 const from_type *_end = (end); \
183 Py_ssize_t n = (_end) - (_iter); \
184 const from_type *_unrolled_end = \
185 _iter + (n & ~ (Py_ssize_t) 3); \
186 while (_iter < (_unrolled_end)) { \
187 _to[0] = (to_type) _iter[0]; \
188 _to[1] = (to_type) _iter[1]; \
189 _to[2] = (to_type) _iter[2]; \
190 _to[3] = (to_type) _iter[3]; \
191 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200192 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200193 while (_iter < (_end)) \
194 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200195 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200196
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200197/* The Unicode string has been modified: reset the hash */
198#define _PyUnicode_DIRTY(op) do { _PyUnicode_HASH(op) = -1; } while (0)
199
Walter Dörwald16807132007-05-25 13:52:07 +0000200/* This dictionary holds all interned unicode strings. Note that references
201 to strings in this dictionary are *not* counted in the string's ob_refcnt.
202 When the interned string reaches a refcnt of 0 the string deallocation
203 function will delete the reference from this dictionary.
204
205 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000206 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000207*/
208static PyObject *interned;
209
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000210/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200211static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000212
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200213/* List of static strings. */
214static _Py_Identifier *static_strings;
215
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000216/* Single character Unicode strings in the Latin-1 range are being
217 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200218static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000219
Christian Heimes190d79e2008-01-30 11:58:22 +0000220/* Fast detection of the most frequent whitespace characters */
221const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000222 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000223/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000224/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000225/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000226/* case 0x000C: * FORM FEED */
227/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000228 0, 1, 1, 1, 1, 1, 0, 0,
229 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000230/* case 0x001C: * FILE SEPARATOR */
231/* case 0x001D: * GROUP SEPARATOR */
232/* case 0x001E: * RECORD SEPARATOR */
233/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000234 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000235/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000236 1, 0, 0, 0, 0, 0, 0, 0,
237 0, 0, 0, 0, 0, 0, 0, 0,
238 0, 0, 0, 0, 0, 0, 0, 0,
239 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000240
Benjamin Peterson14339b62009-01-31 16:36:08 +0000241 0, 0, 0, 0, 0, 0, 0, 0,
242 0, 0, 0, 0, 0, 0, 0, 0,
243 0, 0, 0, 0, 0, 0, 0, 0,
244 0, 0, 0, 0, 0, 0, 0, 0,
245 0, 0, 0, 0, 0, 0, 0, 0,
246 0, 0, 0, 0, 0, 0, 0, 0,
247 0, 0, 0, 0, 0, 0, 0, 0,
248 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000249};
250
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200251/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200252static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200253static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200254static void copy_characters(
255 PyObject *to, Py_ssize_t to_start,
256 PyObject *from, Py_ssize_t from_start,
257 Py_ssize_t how_many);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200258#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200259static int unicode_is_singleton(PyObject *unicode);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200260#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200261
Alexander Belopolsky40018472011-02-26 01:02:56 +0000262static PyObject *
263unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000264 PyObject **errorHandler,const char *encoding, const char *reason,
265 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
266 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
267
Alexander Belopolsky40018472011-02-26 01:02:56 +0000268static void
269raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300270 const char *encoding,
271 const Py_UNICODE *unicode, Py_ssize_t size,
272 Py_ssize_t startpos, Py_ssize_t endpos,
273 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000274
Christian Heimes190d79e2008-01-30 11:58:22 +0000275/* Same for linebreaks */
276static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000277 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000278/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000279/* 0x000B, * LINE TABULATION */
280/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000281/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000282 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000283 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000284/* 0x001C, * FILE SEPARATOR */
285/* 0x001D, * GROUP SEPARATOR */
286/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000287 0, 0, 0, 0, 1, 1, 1, 0,
288 0, 0, 0, 0, 0, 0, 0, 0,
289 0, 0, 0, 0, 0, 0, 0, 0,
290 0, 0, 0, 0, 0, 0, 0, 0,
291 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000292
Benjamin Peterson14339b62009-01-31 16:36:08 +0000293 0, 0, 0, 0, 0, 0, 0, 0,
294 0, 0, 0, 0, 0, 0, 0, 0,
295 0, 0, 0, 0, 0, 0, 0, 0,
296 0, 0, 0, 0, 0, 0, 0, 0,
297 0, 0, 0, 0, 0, 0, 0, 0,
298 0, 0, 0, 0, 0, 0, 0, 0,
299 0, 0, 0, 0, 0, 0, 0, 0,
300 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000301};
302
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300303/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
304 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000305Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000306PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000307{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000308#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000309 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000310#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000311 /* This is actually an illegal character, so it should
312 not be passed to unichr. */
313 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000314#endif
315}
316
Victor Stinner910337b2011-10-03 03:20:16 +0200317#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200318int
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200319/* FIXME: use PyObject* type for op */
320_PyUnicode_CheckConsistency(void *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200321{
322 PyASCIIObject *ascii;
323 unsigned int kind;
324
325 assert(PyUnicode_Check(op));
326
327 ascii = (PyASCIIObject *)op;
328 kind = ascii->state.kind;
329
Victor Stinnera3b334d2011-10-03 13:53:37 +0200330 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200331 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200332 assert(ascii->state.ready == 1);
333 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200334 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200335 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200336 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200337
Victor Stinnera41463c2011-10-04 01:05:08 +0200338 if (ascii->state.compact == 1) {
339 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200340 assert(kind == PyUnicode_1BYTE_KIND
341 || kind == PyUnicode_2BYTE_KIND
342 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200343 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200344 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200345 assert (compact->utf8 != data);
346 } else {
347 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
348
349 data = unicode->data.any;
350 if (kind == PyUnicode_WCHAR_KIND) {
351 assert(ascii->state.compact == 0);
352 assert(ascii->state.ascii == 0);
353 assert(ascii->state.ready == 0);
354 assert(ascii->wstr != NULL);
355 assert(data == NULL);
356 assert(compact->utf8 == NULL);
357 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
358 }
359 else {
360 assert(kind == PyUnicode_1BYTE_KIND
361 || kind == PyUnicode_2BYTE_KIND
362 || kind == PyUnicode_4BYTE_KIND);
363 assert(ascii->state.compact == 0);
364 assert(ascii->state.ready == 1);
365 assert(data != NULL);
366 if (ascii->state.ascii) {
367 assert (compact->utf8 == data);
368 assert (compact->utf8_length == ascii->length);
369 }
370 else
371 assert (compact->utf8 != data);
372 }
373 }
374 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200375 if (
376#if SIZEOF_WCHAR_T == 2
377 kind == PyUnicode_2BYTE_KIND
378#else
379 kind == PyUnicode_4BYTE_KIND
380#endif
381 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200382 {
383 assert(ascii->wstr == data);
384 assert(compact->wstr_length == ascii->length);
385 } else
386 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200387 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200388
389 if (compact->utf8 == NULL)
390 assert(compact->utf8_length == 0);
391 if (ascii->wstr == NULL)
392 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200393 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200394 /* check that the best kind is used */
395 if (check_content && kind != PyUnicode_WCHAR_KIND)
396 {
397 Py_ssize_t i;
398 Py_UCS4 maxchar = 0;
399 void *data = PyUnicode_DATA(ascii);
400 for (i=0; i < ascii->length; i++)
401 {
402 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
403 if (ch > maxchar)
404 maxchar = ch;
405 }
406 if (kind == PyUnicode_1BYTE_KIND) {
407 if (ascii->state.ascii == 0)
408 assert(maxchar >= 128);
409 else
410 assert(maxchar < 128);
411 }
412 else if (kind == PyUnicode_2BYTE_KIND)
413 assert(maxchar >= 0x100);
414 else
415 assert(maxchar >= 0x10000);
416 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200417 if (check_content && !unicode_is_singleton((PyObject*)ascii))
418 assert(ascii->hash == -1);
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400419 return 1;
420}
Victor Stinner910337b2011-10-03 03:20:16 +0200421#endif
422
Thomas Wouters477c8d52006-05-27 19:21:47 +0000423/* --- Bloom Filters ----------------------------------------------------- */
424
425/* stuff to implement simple "bloom filters" for Unicode characters.
426 to keep things simple, we use a single bitmask, using the least 5
427 bits from each unicode characters as the bit index. */
428
429/* the linebreak mask is set up by Unicode_Init below */
430
Antoine Pitrouf068f942010-01-13 14:19:12 +0000431#if LONG_BIT >= 128
432#define BLOOM_WIDTH 128
433#elif LONG_BIT >= 64
434#define BLOOM_WIDTH 64
435#elif LONG_BIT >= 32
436#define BLOOM_WIDTH 32
437#else
438#error "LONG_BIT is smaller than 32"
439#endif
440
Thomas Wouters477c8d52006-05-27 19:21:47 +0000441#define BLOOM_MASK unsigned long
442
443static BLOOM_MASK bloom_linebreak;
444
Antoine Pitrouf068f942010-01-13 14:19:12 +0000445#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
446#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000447
Benjamin Peterson29060642009-01-31 22:14:21 +0000448#define BLOOM_LINEBREAK(ch) \
449 ((ch) < 128U ? ascii_linebreak[(ch)] : \
450 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000451
Alexander Belopolsky40018472011-02-26 01:02:56 +0000452Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200453make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000454{
455 /* calculate simple bloom-style bitmask for a given unicode string */
456
Antoine Pitrouf068f942010-01-13 14:19:12 +0000457 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000458 Py_ssize_t i;
459
460 mask = 0;
461 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200462 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000463
464 return mask;
465}
466
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200467#define BLOOM_MEMBER(mask, chr, str) \
468 (BLOOM(mask, chr) \
469 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000470
Guido van Rossumd57fd912000-03-10 22:53:23 +0000471/* --- Unicode Object ----------------------------------------------------- */
472
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200473static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200474fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200475
476Py_LOCAL_INLINE(char *) findchar(void *s, int kind,
477 Py_ssize_t size, Py_UCS4 ch,
478 int direction)
479{
480 /* like wcschr, but doesn't stop at NULL characters */
481 Py_ssize_t i;
482 if (direction == 1) {
483 for(i = 0; i < size; i++)
484 if (PyUnicode_READ(kind, s, i) == ch)
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200485 return (char*)s + kind * i;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200486 }
487 else {
488 for(i = size-1; i >= 0; i--)
489 if (PyUnicode_READ(kind, s, i) == ch)
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200490 return (char*)s + kind * i;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200491 }
492 return NULL;
493}
494
Victor Stinnerfe226c02011-10-03 03:52:20 +0200495static PyObject*
496resize_compact(PyObject *unicode, Py_ssize_t length)
497{
498 Py_ssize_t char_size;
499 Py_ssize_t struct_size;
500 Py_ssize_t new_size;
501 int share_wstr;
502
503 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200504 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200505 if (PyUnicode_IS_COMPACT_ASCII(unicode))
506 struct_size = sizeof(PyASCIIObject);
507 else
508 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200509 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200510
511 _Py_DEC_REFTOTAL;
512 _Py_ForgetReference(unicode);
513
514 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
515 PyErr_NoMemory();
516 return NULL;
517 }
518 new_size = (struct_size + (length + 1) * char_size);
519
520 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
521 if (unicode == NULL) {
522 PyObject_Del(unicode);
523 PyErr_NoMemory();
524 return NULL;
525 }
526 _Py_NewReference(unicode);
527 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200528 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200529 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200530 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
531 _PyUnicode_WSTR_LENGTH(unicode) = length;
532 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200533 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
534 length, 0);
535 return unicode;
536}
537
Alexander Belopolsky40018472011-02-26 01:02:56 +0000538static int
Victor Stinner95663112011-10-04 01:03:50 +0200539resize_inplace(PyUnicodeObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000540{
Victor Stinner95663112011-10-04 01:03:50 +0200541 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200542 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200543 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000544
Victor Stinner95663112011-10-04 01:03:50 +0200545 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200546
547 if (PyUnicode_IS_READY(unicode)) {
548 Py_ssize_t char_size;
549 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200550 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200551 void *data;
552
553 data = _PyUnicode_DATA_ANY(unicode);
554 assert(data != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200555 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200556 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
557 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200558 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
559 {
560 PyObject_DEL(_PyUnicode_UTF8(unicode));
561 _PyUnicode_UTF8(unicode) = NULL;
562 _PyUnicode_UTF8_LENGTH(unicode) = 0;
563 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200564
565 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
566 PyErr_NoMemory();
567 return -1;
568 }
569 new_size = (length + 1) * char_size;
570
571 data = (PyObject *)PyObject_REALLOC(data, new_size);
572 if (data == NULL) {
573 PyErr_NoMemory();
574 return -1;
575 }
576 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200577 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200578 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200579 _PyUnicode_WSTR_LENGTH(unicode) = length;
580 }
581 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200582 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200583 _PyUnicode_UTF8_LENGTH(unicode) = length;
584 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200585 _PyUnicode_LENGTH(unicode) = length;
586 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200587 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200588 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200589 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200590 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200591 }
Victor Stinner95663112011-10-04 01:03:50 +0200592 assert(_PyUnicode_WSTR(unicode) != NULL);
593
594 /* check for integer overflow */
595 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
596 PyErr_NoMemory();
597 return -1;
598 }
599 wstr = _PyUnicode_WSTR(unicode);
600 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
601 if (!wstr) {
602 PyErr_NoMemory();
603 return -1;
604 }
605 _PyUnicode_WSTR(unicode) = wstr;
606 _PyUnicode_WSTR(unicode)[length] = 0;
607 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200608 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000609 return 0;
610}
611
Victor Stinnerfe226c02011-10-03 03:52:20 +0200612static PyObject*
613resize_copy(PyObject *unicode, Py_ssize_t length)
614{
615 Py_ssize_t copy_length;
616 if (PyUnicode_IS_COMPACT(unicode)) {
617 PyObject *copy;
618 assert(PyUnicode_IS_READY(unicode));
619
620 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
621 if (copy == NULL)
622 return NULL;
623
624 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200625 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200626 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200627 }
628 else {
Victor Stinner2fd82272011-10-03 04:06:05 +0200629 PyUnicodeObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200630 assert(_PyUnicode_WSTR(unicode) != NULL);
631 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner2fd82272011-10-03 04:06:05 +0200632 w = _PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200633 if (w == NULL)
634 return NULL;
635 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
636 copy_length = Py_MIN(copy_length, length);
637 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
638 copy_length);
639 return (PyObject*)w;
640 }
641}
642
Guido van Rossumd57fd912000-03-10 22:53:23 +0000643/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000644 Ux0000 terminated; some code (e.g. new_identifier)
645 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000646
647 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000648 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000649
650*/
651
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200652#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200653static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200654#endif
655
Alexander Belopolsky40018472011-02-26 01:02:56 +0000656static PyUnicodeObject *
657_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000658{
659 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200660 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000661
Thomas Wouters477c8d52006-05-27 19:21:47 +0000662 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000663 if (length == 0 && unicode_empty != NULL) {
664 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200665 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000666 }
667
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000668 /* Ensure we won't overflow the size. */
669 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
670 return (PyUnicodeObject *)PyErr_NoMemory();
671 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200672 if (length < 0) {
673 PyErr_SetString(PyExc_SystemError,
674 "Negative size passed to _PyUnicode_New");
675 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000676 }
677
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200678#ifdef Py_DEBUG
679 ++unicode_old_new_calls;
680#endif
681
682 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
683 if (unicode == NULL)
684 return NULL;
685 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
686 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
687 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000688 PyErr_NoMemory();
689 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000690 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200691
Jeremy Hyltond8082792003-09-16 19:41:39 +0000692 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000693 * the caller fails before initializing str -- unicode_resize()
694 * reads str[0], and the Keep-Alive optimization can keep memory
695 * allocated for str alive across a call to unicode_dealloc(unicode).
696 * We don't want unicode_resize to read uninitialized memory in
697 * that case.
698 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200699 _PyUnicode_WSTR(unicode)[0] = 0;
700 _PyUnicode_WSTR(unicode)[length] = 0;
701 _PyUnicode_WSTR_LENGTH(unicode) = length;
702 _PyUnicode_HASH(unicode) = -1;
703 _PyUnicode_STATE(unicode).interned = 0;
704 _PyUnicode_STATE(unicode).kind = 0;
705 _PyUnicode_STATE(unicode).compact = 0;
706 _PyUnicode_STATE(unicode).ready = 0;
707 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200708 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200709 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200710 _PyUnicode_UTF8(unicode) = NULL;
711 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000712 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000713
Benjamin Peterson29060642009-01-31 22:14:21 +0000714 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000715 /* XXX UNREF/NEWREF interface should be more symmetrical */
716 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000717 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000718 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000719 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000720}
721
Victor Stinnerf42dc442011-10-02 23:33:16 +0200722static const char*
723unicode_kind_name(PyObject *unicode)
724{
Victor Stinner42dfd712011-10-03 14:41:45 +0200725 /* don't check consistency: unicode_kind_name() is called from
726 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200727 if (!PyUnicode_IS_COMPACT(unicode))
728 {
729 if (!PyUnicode_IS_READY(unicode))
730 return "wstr";
731 switch(PyUnicode_KIND(unicode))
732 {
733 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200734 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200735 return "legacy ascii";
736 else
737 return "legacy latin1";
738 case PyUnicode_2BYTE_KIND:
739 return "legacy UCS2";
740 case PyUnicode_4BYTE_KIND:
741 return "legacy UCS4";
742 default:
743 return "<legacy invalid kind>";
744 }
745 }
746 assert(PyUnicode_IS_READY(unicode));
747 switch(PyUnicode_KIND(unicode))
748 {
749 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200750 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200751 return "ascii";
752 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200753 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200754 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200755 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200756 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200757 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200758 default:
759 return "<invalid compact kind>";
760 }
761}
762
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200763#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200764static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200765
766/* Functions wrapping macros for use in debugger */
767char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200768 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200769}
770
771void *_PyUnicode_compact_data(void *unicode) {
772 return _PyUnicode_COMPACT_DATA(unicode);
773}
774void *_PyUnicode_data(void *unicode){
775 printf("obj %p\n", unicode);
776 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
777 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
778 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
779 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
780 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
781 return PyUnicode_DATA(unicode);
782}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200783
784void
785_PyUnicode_Dump(PyObject *op)
786{
787 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200788 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
789 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
790 void *data;
791 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
792 if (ascii->state.compact)
793 data = (compact + 1);
794 else
795 data = unicode->data.any;
796 if (ascii->wstr == data)
797 printf("shared ");
798 printf("wstr=%p", ascii->wstr);
Victor Stinnera3b334d2011-10-03 13:53:37 +0200799 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200800 printf(" (%zu), ", compact->wstr_length);
801 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
802 printf("shared ");
803 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200804 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200805 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200806}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200807#endif
808
809PyObject *
810PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
811{
812 PyObject *obj;
813 PyCompactUnicodeObject *unicode;
814 void *data;
815 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200816 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200817 Py_ssize_t char_size;
818 Py_ssize_t struct_size;
819
820 /* Optimization for empty strings */
821 if (size == 0 && unicode_empty != NULL) {
822 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200823 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200824 }
825
826#ifdef Py_DEBUG
827 ++unicode_new_new_calls;
828#endif
829
Victor Stinner9e9d6892011-10-04 01:02:02 +0200830 is_ascii = 0;
831 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200832 struct_size = sizeof(PyCompactUnicodeObject);
833 if (maxchar < 128) {
834 kind_state = PyUnicode_1BYTE_KIND;
835 char_size = 1;
836 is_ascii = 1;
837 struct_size = sizeof(PyASCIIObject);
838 }
839 else if (maxchar < 256) {
840 kind_state = PyUnicode_1BYTE_KIND;
841 char_size = 1;
842 }
843 else if (maxchar < 65536) {
844 kind_state = PyUnicode_2BYTE_KIND;
845 char_size = 2;
846 if (sizeof(wchar_t) == 2)
847 is_sharing = 1;
848 }
849 else {
850 kind_state = PyUnicode_4BYTE_KIND;
851 char_size = 4;
852 if (sizeof(wchar_t) == 4)
853 is_sharing = 1;
854 }
855
856 /* Ensure we won't overflow the size. */
857 if (size < 0) {
858 PyErr_SetString(PyExc_SystemError,
859 "Negative size passed to PyUnicode_New");
860 return NULL;
861 }
862 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
863 return PyErr_NoMemory();
864
865 /* Duplicated allocation code from _PyObject_New() instead of a call to
866 * PyObject_New() so we are able to allocate space for the object and
867 * it's data buffer.
868 */
869 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
870 if (obj == NULL)
871 return PyErr_NoMemory();
872 obj = PyObject_INIT(obj, &PyUnicode_Type);
873 if (obj == NULL)
874 return NULL;
875
876 unicode = (PyCompactUnicodeObject *)obj;
877 if (is_ascii)
878 data = ((PyASCIIObject*)obj) + 1;
879 else
880 data = unicode + 1;
881 _PyUnicode_LENGTH(unicode) = size;
882 _PyUnicode_HASH(unicode) = -1;
883 _PyUnicode_STATE(unicode).interned = 0;
884 _PyUnicode_STATE(unicode).kind = kind_state;
885 _PyUnicode_STATE(unicode).compact = 1;
886 _PyUnicode_STATE(unicode).ready = 1;
887 _PyUnicode_STATE(unicode).ascii = is_ascii;
888 if (is_ascii) {
889 ((char*)data)[size] = 0;
890 _PyUnicode_WSTR(unicode) = NULL;
891 }
892 else if (kind_state == PyUnicode_1BYTE_KIND) {
893 ((char*)data)[size] = 0;
894 _PyUnicode_WSTR(unicode) = NULL;
895 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200896 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200897 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200898 }
899 else {
900 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200901 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200902 if (kind_state == PyUnicode_2BYTE_KIND)
903 ((Py_UCS2*)data)[size] = 0;
904 else /* kind_state == PyUnicode_4BYTE_KIND */
905 ((Py_UCS4*)data)[size] = 0;
906 if (is_sharing) {
907 _PyUnicode_WSTR_LENGTH(unicode) = size;
908 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
909 }
910 else {
911 _PyUnicode_WSTR_LENGTH(unicode) = 0;
912 _PyUnicode_WSTR(unicode) = NULL;
913 }
914 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200915 assert(_PyUnicode_CheckConsistency(unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200916 return obj;
917}
918
919#if SIZEOF_WCHAR_T == 2
920/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
921 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +0200922 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200923
924 This function assumes that unicode can hold one more code point than wstr
925 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +0200926static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200927unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
928 PyUnicodeObject *unicode)
929{
930 const wchar_t *iter;
931 Py_UCS4 *ucs4_out;
932
Victor Stinner910337b2011-10-03 03:20:16 +0200933 assert(unicode != NULL);
934 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200935 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
936 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
937
938 for (iter = begin; iter < end; ) {
939 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
940 _PyUnicode_GET_LENGTH(unicode)));
941 if (*iter >= 0xD800 && *iter <= 0xDBFF
942 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
943 {
944 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
945 iter += 2;
946 }
947 else {
948 *ucs4_out++ = *iter;
949 iter++;
950 }
951 }
952 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
953 _PyUnicode_GET_LENGTH(unicode)));
954
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200955}
956#endif
957
Victor Stinnercd9950f2011-10-02 00:34:53 +0200958static int
959_PyUnicode_Dirty(PyObject *unicode)
960{
Victor Stinner910337b2011-10-03 03:20:16 +0200961 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +0200962 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +0200963 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +0200964 "Cannot modify a string having more than 1 reference");
965 return -1;
966 }
967 _PyUnicode_DIRTY(unicode);
968 return 0;
969}
970
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200971static int
972_copy_characters(PyObject *to, Py_ssize_t to_start,
973 PyObject *from, Py_ssize_t from_start,
974 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200975{
Victor Stinnera0702ab2011-09-29 14:14:38 +0200976 unsigned int from_kind, to_kind;
977 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200978 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200979
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200980 assert(PyUnicode_Check(from));
981 assert(PyUnicode_Check(to));
982 assert(PyUnicode_IS_READY(from));
983 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200984
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200985 assert(PyUnicode_GET_LENGTH(from) >= how_many);
986 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
987 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200988
Victor Stinnerf5ca1a22011-09-28 23:54:59 +0200989 if (how_many == 0)
990 return 0;
991
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200992 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +0200993 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200994 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +0200995 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200996
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200997#ifdef Py_DEBUG
998 if (!check_maxchar
999 && (from_kind > to_kind
1000 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001001 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001002 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1003 Py_UCS4 ch;
1004 Py_ssize_t i;
1005 for (i=0; i < how_many; i++) {
1006 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1007 assert(ch <= to_maxchar);
1008 }
1009 }
1010#endif
1011 fast = (from_kind == to_kind);
1012 if (check_maxchar
1013 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1014 {
1015 /* deny latin1 => ascii */
1016 fast = 0;
1017 }
1018
1019 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001020 Py_MEMCPY((char*)to_data + to_kind * to_start,
1021 (char*)from_data + from_kind * from_start,
1022 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001023 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001024 else if (from_kind == PyUnicode_1BYTE_KIND
1025 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001026 {
1027 _PyUnicode_CONVERT_BYTES(
1028 Py_UCS1, Py_UCS2,
1029 PyUnicode_1BYTE_DATA(from) + from_start,
1030 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1031 PyUnicode_2BYTE_DATA(to) + to_start
1032 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001033 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001034 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001035 && to_kind == PyUnicode_4BYTE_KIND)
1036 {
1037 _PyUnicode_CONVERT_BYTES(
1038 Py_UCS1, Py_UCS4,
1039 PyUnicode_1BYTE_DATA(from) + from_start,
1040 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1041 PyUnicode_4BYTE_DATA(to) + to_start
1042 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001043 }
1044 else if (from_kind == PyUnicode_2BYTE_KIND
1045 && to_kind == PyUnicode_4BYTE_KIND)
1046 {
1047 _PyUnicode_CONVERT_BYTES(
1048 Py_UCS2, Py_UCS4,
1049 PyUnicode_2BYTE_DATA(from) + from_start,
1050 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1051 PyUnicode_4BYTE_DATA(to) + to_start
1052 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001053 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001054 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001055 /* check if max_char(from substring) <= max_char(to) */
1056 if (from_kind > to_kind
1057 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001058 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001059 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001060 /* slow path to check for character overflow */
1061 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001062 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001063 Py_ssize_t i;
1064
Victor Stinner56c161a2011-10-06 02:47:11 +02001065#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001066 for (i=0; i < how_many; i++) {
1067 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001068 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001069 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1070 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001071#else
1072 if (!check_maxchar) {
1073 for (i=0; i < how_many; i++) {
1074 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1075 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1076 }
1077 }
1078 else {
1079 for (i=0; i < how_many; i++) {
1080 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1081 if (ch > to_maxchar)
1082 return 1;
1083 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1084 }
1085 }
1086#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001087 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001088 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001089 assert(0 && "inconsistent state");
1090 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001091 }
1092 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001093 return 0;
1094}
1095
1096static void
1097copy_characters(PyObject *to, Py_ssize_t to_start,
1098 PyObject *from, Py_ssize_t from_start,
1099 Py_ssize_t how_many)
1100{
1101 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1102}
1103
1104Py_ssize_t
1105PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1106 PyObject *from, Py_ssize_t from_start,
1107 Py_ssize_t how_many)
1108{
1109 int err;
1110
1111 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1112 PyErr_BadInternalCall();
1113 return -1;
1114 }
1115
1116 if (PyUnicode_READY(from))
1117 return -1;
1118 if (PyUnicode_READY(to))
1119 return -1;
1120
1121 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1122 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1123 PyErr_Format(PyExc_SystemError,
1124 "Cannot write %zi characters at %zi "
1125 "in a string of %zi characters",
1126 how_many, to_start, PyUnicode_GET_LENGTH(to));
1127 return -1;
1128 }
1129
1130 if (how_many == 0)
1131 return 0;
1132
1133 if (_PyUnicode_Dirty(to))
1134 return -1;
1135
1136 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1137 if (err) {
1138 PyErr_Format(PyExc_SystemError,
1139 "Cannot copy %s characters "
1140 "into a string of %s characters",
1141 unicode_kind_name(from),
1142 unicode_kind_name(to));
1143 return -1;
1144 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001145 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001146}
1147
Victor Stinner17222162011-09-28 22:15:37 +02001148/* Find the maximum code point and count the number of surrogate pairs so a
1149 correct string length can be computed before converting a string to UCS4.
1150 This function counts single surrogates as a character and not as a pair.
1151
1152 Return 0 on success, or -1 on error. */
1153static int
1154find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1155 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001156{
1157 const wchar_t *iter;
1158
Victor Stinnerc53be962011-10-02 21:33:54 +02001159 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001160 *num_surrogates = 0;
1161 *maxchar = 0;
1162
1163 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001164 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001165 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001166#if SIZEOF_WCHAR_T != 2
1167 if (*maxchar >= 0x10000)
1168 return 0;
1169#endif
1170 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001171#if SIZEOF_WCHAR_T == 2
1172 if (*iter >= 0xD800 && *iter <= 0xDBFF
1173 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1174 {
1175 Py_UCS4 surrogate_val;
1176 surrogate_val = (((iter[0] & 0x3FF)<<10)
1177 | (iter[1] & 0x3FF)) + 0x10000;
1178 ++(*num_surrogates);
1179 if (surrogate_val > *maxchar)
1180 *maxchar = surrogate_val;
1181 iter += 2;
1182 }
1183 else
1184 iter++;
1185#else
1186 iter++;
1187#endif
1188 }
1189 return 0;
1190}
1191
1192#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001193static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001194#endif
1195
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001196static int
1197unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001198{
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001199 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001200 wchar_t *end;
1201 Py_UCS4 maxchar = 0;
1202 Py_ssize_t num_surrogates;
1203#if SIZEOF_WCHAR_T == 2
1204 Py_ssize_t length_wo_surrogates;
1205#endif
1206
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001207 assert(p_obj != NULL);
1208 unicode = (PyUnicodeObject *)*p_obj;
1209
Georg Brandl7597add2011-10-05 16:36:47 +02001210 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001211 strings were created using _PyObject_New() and where no canonical
1212 representation (the str field) has been set yet aka strings
1213 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001214 assert(_PyUnicode_CHECK(unicode));
1215 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001216 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001217 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001218 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001219 /* Actually, it should neither be interned nor be anything else: */
1220 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001221
1222#ifdef Py_DEBUG
1223 ++unicode_ready_calls;
1224#endif
1225
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001226#ifdef Py_DEBUG
1227 assert(!replace || Py_REFCNT(unicode) == 1);
1228#else
1229 if (replace && Py_REFCNT(unicode) != 1)
1230 replace = 0;
1231#endif
1232 if (replace) {
1233 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1234 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1235 /* Optimization for empty strings */
1236 if (len == 0) {
1237 Py_INCREF(unicode_empty);
1238 Py_DECREF(*p_obj);
1239 *p_obj = unicode_empty;
1240 return 0;
1241 }
1242 if (len == 1 && wstr[0] < 256) {
1243 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1244 if (latin1_char == NULL)
1245 return -1;
1246 Py_DECREF(*p_obj);
1247 *p_obj = latin1_char;
1248 return 0;
1249 }
1250 }
1251
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001252 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001253 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001254 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001255 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001256
1257 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001258 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1259 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001260 PyErr_NoMemory();
1261 return -1;
1262 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001263 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001264 _PyUnicode_WSTR(unicode), end,
1265 PyUnicode_1BYTE_DATA(unicode));
1266 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1267 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1268 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1269 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001270 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001271 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001272 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001273 }
1274 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001275 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001276 _PyUnicode_UTF8(unicode) = NULL;
1277 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001278 }
1279 PyObject_FREE(_PyUnicode_WSTR(unicode));
1280 _PyUnicode_WSTR(unicode) = NULL;
1281 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1282 }
1283 /* In this case we might have to convert down from 4-byte native
1284 wchar_t to 2-byte unicode. */
1285 else if (maxchar < 65536) {
1286 assert(num_surrogates == 0 &&
1287 "FindMaxCharAndNumSurrogatePairs() messed up");
1288
Victor Stinner506f5922011-09-28 22:34:18 +02001289#if SIZEOF_WCHAR_T == 2
1290 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001291 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001292 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1293 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1294 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001295 _PyUnicode_UTF8(unicode) = NULL;
1296 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001297#else
1298 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001299 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001300 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001301 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001302 PyErr_NoMemory();
1303 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001304 }
Victor Stinner506f5922011-09-28 22:34:18 +02001305 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1306 _PyUnicode_WSTR(unicode), end,
1307 PyUnicode_2BYTE_DATA(unicode));
1308 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1309 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1310 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001311 _PyUnicode_UTF8(unicode) = NULL;
1312 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001313 PyObject_FREE(_PyUnicode_WSTR(unicode));
1314 _PyUnicode_WSTR(unicode) = NULL;
1315 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1316#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001317 }
1318 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1319 else {
1320#if SIZEOF_WCHAR_T == 2
1321 /* in case the native representation is 2-bytes, we need to allocate a
1322 new normalized 4-byte version. */
1323 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001324 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1325 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001326 PyErr_NoMemory();
1327 return -1;
1328 }
1329 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1330 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001331 _PyUnicode_UTF8(unicode) = NULL;
1332 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001333 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1334 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001335 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001336 PyObject_FREE(_PyUnicode_WSTR(unicode));
1337 _PyUnicode_WSTR(unicode) = NULL;
1338 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1339#else
1340 assert(num_surrogates == 0);
1341
Victor Stinnerc3c74152011-10-02 20:39:55 +02001342 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001343 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001344 _PyUnicode_UTF8(unicode) = NULL;
1345 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001346 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1347#endif
1348 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1349 }
1350 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001351 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001352 return 0;
1353}
1354
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001355int
1356_PyUnicode_ReadyReplace(PyObject **op)
1357{
1358 return unicode_ready(op, 1);
1359}
1360
1361int
1362_PyUnicode_Ready(PyObject *op)
1363{
1364 return unicode_ready(&op, 0);
1365}
1366
Alexander Belopolsky40018472011-02-26 01:02:56 +00001367static void
1368unicode_dealloc(register PyUnicodeObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001369{
Walter Dörwald16807132007-05-25 13:52:07 +00001370 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001371 case SSTATE_NOT_INTERNED:
1372 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001373
Benjamin Peterson29060642009-01-31 22:14:21 +00001374 case SSTATE_INTERNED_MORTAL:
1375 /* revive dead object temporarily for DelItem */
1376 Py_REFCNT(unicode) = 3;
1377 if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
1378 Py_FatalError(
1379 "deletion of interned string failed");
1380 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001381
Benjamin Peterson29060642009-01-31 22:14:21 +00001382 case SSTATE_INTERNED_IMMORTAL:
1383 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001384
Benjamin Peterson29060642009-01-31 22:14:21 +00001385 default:
1386 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001387 }
1388
Victor Stinner03490912011-10-03 23:45:12 +02001389 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001390 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001391 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001392 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001393
1394 if (PyUnicode_IS_COMPACT(unicode)) {
1395 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001396 }
1397 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001398 if (_PyUnicode_DATA_ANY(unicode))
1399 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Benjamin Peterson29060642009-01-31 22:14:21 +00001400 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001401 }
1402}
1403
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001404#ifdef Py_DEBUG
1405static int
1406unicode_is_singleton(PyObject *unicode)
1407{
1408 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1409 if (unicode == unicode_empty)
1410 return 1;
1411 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1412 {
1413 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1414 if (ch < 256 && unicode_latin1[ch] == unicode)
1415 return 1;
1416 }
1417 return 0;
1418}
1419#endif
1420
Alexander Belopolsky40018472011-02-26 01:02:56 +00001421static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001422unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001423{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001424 if (Py_REFCNT(unicode) != 1)
1425 return 0;
1426 if (PyUnicode_CHECK_INTERNED(unicode))
1427 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001428#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001429 /* singleton refcount is greater than 1 */
1430 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001431#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001432 return 1;
1433}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001434
Victor Stinnerfe226c02011-10-03 03:52:20 +02001435static int
1436unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1437{
1438 PyObject *unicode;
1439 Py_ssize_t old_length;
1440
1441 assert(p_unicode != NULL);
1442 unicode = *p_unicode;
1443
1444 assert(unicode != NULL);
1445 assert(PyUnicode_Check(unicode));
1446 assert(0 <= length);
1447
Victor Stinner910337b2011-10-03 03:20:16 +02001448 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001449 old_length = PyUnicode_WSTR_LENGTH(unicode);
1450 else
1451 old_length = PyUnicode_GET_LENGTH(unicode);
1452 if (old_length == length)
1453 return 0;
1454
Victor Stinnerfe226c02011-10-03 03:52:20 +02001455 if (!unicode_resizable(unicode)) {
1456 PyObject *copy = resize_copy(unicode, length);
1457 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001458 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001459 Py_DECREF(*p_unicode);
1460 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001461 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001462 }
1463
Victor Stinnerfe226c02011-10-03 03:52:20 +02001464 if (PyUnicode_IS_COMPACT(unicode)) {
1465 *p_unicode = resize_compact(unicode, length);
1466 if (*p_unicode == NULL)
1467 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001468 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001469 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001470 }
1471 return resize_inplace((PyUnicodeObject*)unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001472}
1473
Alexander Belopolsky40018472011-02-26 01:02:56 +00001474int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001475PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001476{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001477 PyObject *unicode;
1478 if (p_unicode == NULL) {
1479 PyErr_BadInternalCall();
1480 return -1;
1481 }
1482 unicode = *p_unicode;
1483 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0
1484 || _PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND)
1485 {
1486 PyErr_BadInternalCall();
1487 return -1;
1488 }
1489 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001490}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001491
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001492static PyObject*
1493get_latin1_char(unsigned char ch)
1494{
Victor Stinnera464fc12011-10-02 20:39:30 +02001495 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001496 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001497 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001498 if (!unicode)
1499 return NULL;
1500 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001501 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001502 unicode_latin1[ch] = unicode;
1503 }
1504 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001505 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001506}
1507
Alexander Belopolsky40018472011-02-26 01:02:56 +00001508PyObject *
1509PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001510{
1511 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001512 Py_UCS4 maxchar = 0;
1513 Py_ssize_t num_surrogates;
1514
1515 if (u == NULL)
1516 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001517
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001518 /* If the Unicode data is known at construction time, we can apply
1519 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001520
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001521 /* Optimization for empty strings */
1522 if (size == 0 && unicode_empty != NULL) {
1523 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001524 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001525 }
Tim Petersced69f82003-09-16 20:30:58 +00001526
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001527 /* Single character Unicode objects in the Latin-1 range are
1528 shared when using this constructor */
1529 if (size == 1 && *u < 256)
1530 return get_latin1_char((unsigned char)*u);
1531
1532 /* If not empty and not single character, copy the Unicode data
1533 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001534 if (find_maxchar_surrogates(u, u + size,
1535 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001536 return NULL;
1537
1538 unicode = (PyUnicodeObject *) PyUnicode_New(size - num_surrogates,
1539 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001540 if (!unicode)
1541 return NULL;
1542
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001543 switch (PyUnicode_KIND(unicode)) {
1544 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001545 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001546 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1547 break;
1548 case PyUnicode_2BYTE_KIND:
1549#if Py_UNICODE_SIZE == 2
1550 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1551#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001552 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001553 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1554#endif
1555 break;
1556 case PyUnicode_4BYTE_KIND:
1557#if SIZEOF_WCHAR_T == 2
1558 /* This is the only case which has to process surrogates, thus
1559 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001560 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001561#else
1562 assert(num_surrogates == 0);
1563 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1564#endif
1565 break;
1566 default:
1567 assert(0 && "Impossible state");
1568 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001569
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001570 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001571 return (PyObject *)unicode;
1572}
1573
Alexander Belopolsky40018472011-02-26 01:02:56 +00001574PyObject *
1575PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001576{
1577 PyUnicodeObject *unicode;
Christian Heimes33fe8092008-04-13 13:53:33 +00001578
Benjamin Peterson14339b62009-01-31 16:36:08 +00001579 if (size < 0) {
1580 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001581 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001582 return NULL;
1583 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001584
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001585 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001586 some optimizations which share commonly used objects.
1587 Also, this means the input must be UTF-8, so fall back to the
1588 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001589 if (u != NULL) {
1590
Benjamin Peterson29060642009-01-31 22:14:21 +00001591 /* Optimization for empty strings */
1592 if (size == 0 && unicode_empty != NULL) {
1593 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001594 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001595 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001596
1597 /* Single characters are shared when using this constructor.
1598 Restrict to ASCII, since the input must be UTF-8. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001599 if (size == 1 && Py_CHARMASK(*u) < 128)
1600 return get_latin1_char(Py_CHARMASK(*u));
Martin v. Löwis9c121062007-08-05 20:26:11 +00001601
1602 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001603 }
1604
Walter Dörwald55507312007-05-18 13:12:10 +00001605 unicode = _PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001606 if (!unicode)
1607 return NULL;
1608
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001609 return (PyObject *)unicode;
1610}
1611
Alexander Belopolsky40018472011-02-26 01:02:56 +00001612PyObject *
1613PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001614{
1615 size_t size = strlen(u);
1616 if (size > PY_SSIZE_T_MAX) {
1617 PyErr_SetString(PyExc_OverflowError, "input too long");
1618 return NULL;
1619 }
1620
1621 return PyUnicode_FromStringAndSize(u, size);
1622}
1623
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001624PyObject *
1625_PyUnicode_FromId(_Py_Identifier *id)
1626{
1627 if (!id->object) {
1628 id->object = PyUnicode_FromString(id->string);
1629 if (!id->object)
1630 return NULL;
1631 PyUnicode_InternInPlace(&id->object);
1632 assert(!id->next);
1633 id->next = static_strings;
1634 static_strings = id;
1635 }
1636 Py_INCREF(id->object);
1637 return id->object;
1638}
1639
1640void
1641_PyUnicode_ClearStaticStrings()
1642{
1643 _Py_Identifier *i;
1644 for (i = static_strings; i; i = i->next) {
1645 Py_DECREF(i->object);
1646 i->object = NULL;
1647 i->next = NULL;
1648 }
1649}
1650
Victor Stinnere57b1c02011-09-28 22:20:48 +02001651static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001652unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001653{
Victor Stinner0617b6e2011-10-05 23:26:01 +02001654 PyObject *res;
1655#ifdef Py_DEBUG
1656 const unsigned char *p;
1657 const unsigned char *end = s + size;
1658 for (p=s; p < end; p++) {
1659 assert(*p < 128);
1660 }
1661#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001662 if (size == 1)
1663 return get_latin1_char(s[0]);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001664 res = PyUnicode_New(size, 127);
Victor Stinner702c7342011-10-05 13:50:52 +02001665 if (!res)
1666 return NULL;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001667 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
Victor Stinner702c7342011-10-05 13:50:52 +02001668 return res;
1669}
1670
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001671static Py_UCS4
1672kind_maxchar_limit(unsigned int kind)
1673{
1674 switch(kind) {
1675 case PyUnicode_1BYTE_KIND:
1676 return 0x80;
1677 case PyUnicode_2BYTE_KIND:
1678 return 0x100;
1679 case PyUnicode_4BYTE_KIND:
1680 return 0x10000;
1681 default:
1682 assert(0 && "invalid kind");
1683 return 0x10ffff;
1684 }
1685}
1686
Victor Stinner702c7342011-10-05 13:50:52 +02001687static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001688_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001689{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001690 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001691 unsigned char max_char = 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001692 Py_ssize_t i;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001693
1694 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001695 if (size == 1)
1696 return get_latin1_char(u[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001697 for (i = 0; i < size; i++) {
1698 if (u[i] & 0x80) {
Victor Stinnerb9275c12011-10-05 14:01:42 +02001699 max_char = 255;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001700 break;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001701 }
1702 }
Victor Stinnerb9275c12011-10-05 14:01:42 +02001703 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001704 if (!res)
1705 return NULL;
1706 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001707 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001708 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001709}
1710
Victor Stinnere57b1c02011-09-28 22:20:48 +02001711static PyObject*
1712_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001713{
1714 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001715 Py_UCS2 max_char = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001716 Py_ssize_t i;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001717
1718 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001719 if (size == 1 && u[0] < 256)
1720 return get_latin1_char(u[0]);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001721 for (i = 0; i < size; i++) {
1722 if (u[i] > max_char) {
1723 max_char = u[i];
1724 if (max_char >= 256)
1725 break;
1726 }
1727 }
1728 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001729 if (!res)
1730 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001731 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001732 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
1733 else
1734 for (i = 0; i < size; i++)
1735 PyUnicode_1BYTE_DATA(res)[i] = (Py_UCS1)u[i];
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001736 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001737 return res;
1738}
1739
Victor Stinnere57b1c02011-09-28 22:20:48 +02001740static PyObject*
1741_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001742{
1743 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001744 Py_UCS4 max_char = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001745 Py_ssize_t i;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001746
1747 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001748 if (size == 1 && u[0] < 256)
1749 return get_latin1_char(u[0]);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001750 for (i = 0; i < size; i++) {
1751 if (u[i] > max_char) {
1752 max_char = u[i];
1753 if (max_char >= 0x10000)
1754 break;
1755 }
1756 }
1757 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001758 if (!res)
1759 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001760 if (max_char >= 0x10000)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001761 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
1762 else {
1763 int kind = PyUnicode_KIND(res);
1764 void *data = PyUnicode_DATA(res);
1765 for (i = 0; i < size; i++)
1766 PyUnicode_WRITE(kind, data, i, u[i]);
1767 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001768 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001769 return res;
1770}
1771
1772PyObject*
1773PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1774{
1775 switch(kind) {
1776 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001777 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001778 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001779 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001780 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001781 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001782 default:
1783 assert(0 && "invalid kind");
1784 PyErr_SetString(PyExc_SystemError, "invalid kind");
1785 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001786 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001787}
1788
Victor Stinner25a4b292011-10-06 12:31:55 +02001789/* Ensure that a string uses the most efficient storage, if it is not the
1790 case: create a new string with of the right kind. Write NULL into *p_unicode
1791 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001792static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001793unicode_adjust_maxchar(PyObject **p_unicode)
1794{
1795 PyObject *unicode, *copy;
1796 Py_UCS4 max_char;
1797 Py_ssize_t i, len;
1798 unsigned int kind;
1799
1800 assert(p_unicode != NULL);
1801 unicode = *p_unicode;
1802 assert(PyUnicode_IS_READY(unicode));
1803 if (PyUnicode_IS_ASCII(unicode))
1804 return;
1805
1806 len = PyUnicode_GET_LENGTH(unicode);
1807 kind = PyUnicode_KIND(unicode);
1808 if (kind == PyUnicode_1BYTE_KIND) {
1809 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
1810 for (i = 0; i < len; i++) {
1811 if (u[i] & 0x80)
1812 return;
1813 }
1814 max_char = 127;
1815 }
1816 else if (kind == PyUnicode_2BYTE_KIND) {
1817 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
1818 max_char = 0;
1819 for (i = 0; i < len; i++) {
1820 if (u[i] > max_char) {
1821 max_char = u[i];
1822 if (max_char >= 256)
1823 return;
1824 }
1825 }
1826 }
1827 else {
Antoine Pitrou15a66cf2011-10-06 15:25:32 +02001828 const Py_UCS4 *u;
Victor Stinner25a4b292011-10-06 12:31:55 +02001829 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitrou15a66cf2011-10-06 15:25:32 +02001830 u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001831 max_char = 0;
1832 for (i = 0; i < len; i++) {
1833 if (u[i] > max_char) {
1834 max_char = u[i];
1835 if (max_char >= 0x10000)
1836 return;
1837 }
1838 }
1839 }
Victor Stinner200f2132011-10-06 13:27:56 +02001840 assert(max_char < PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinner25a4b292011-10-06 12:31:55 +02001841 copy = PyUnicode_New(len, max_char);
1842 copy_characters(copy, 0, unicode, 0, len);
1843 Py_DECREF(unicode);
1844 *p_unicode = copy;
1845}
1846
Victor Stinner034f6cf2011-09-30 02:26:44 +02001847PyObject*
1848PyUnicode_Copy(PyObject *unicode)
1849{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001850 Py_ssize_t size;
1851 PyObject *copy;
1852 void *data;
1853
Victor Stinner034f6cf2011-09-30 02:26:44 +02001854 if (!PyUnicode_Check(unicode)) {
1855 PyErr_BadInternalCall();
1856 return NULL;
1857 }
1858 if (PyUnicode_READY(unicode))
1859 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001860
1861 size = PyUnicode_GET_LENGTH(unicode);
1862 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1863 if (!copy)
1864 return NULL;
1865 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1866
1867 data = PyUnicode_DATA(unicode);
1868 switch (PyUnicode_KIND(unicode))
1869 {
1870 case PyUnicode_1BYTE_KIND:
1871 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1872 break;
1873 case PyUnicode_2BYTE_KIND:
1874 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1875 break;
1876 case PyUnicode_4BYTE_KIND:
1877 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1878 break;
1879 default:
1880 assert(0);
1881 break;
1882 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001883 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001884 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001885}
1886
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001887
Victor Stinnerbc603d12011-10-02 01:00:40 +02001888/* Widen Unicode objects to larger buffers. Don't write terminating null
1889 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001890
1891void*
1892_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1893{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001894 Py_ssize_t len;
1895 void *result;
1896 unsigned int skind;
1897
1898 if (PyUnicode_READY(s))
1899 return NULL;
1900
1901 len = PyUnicode_GET_LENGTH(s);
1902 skind = PyUnicode_KIND(s);
1903 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001904 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001905 return NULL;
1906 }
1907 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001908 case PyUnicode_2BYTE_KIND:
1909 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1910 if (!result)
1911 return PyErr_NoMemory();
1912 assert(skind == PyUnicode_1BYTE_KIND);
1913 _PyUnicode_CONVERT_BYTES(
1914 Py_UCS1, Py_UCS2,
1915 PyUnicode_1BYTE_DATA(s),
1916 PyUnicode_1BYTE_DATA(s) + len,
1917 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001918 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001919 case PyUnicode_4BYTE_KIND:
1920 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1921 if (!result)
1922 return PyErr_NoMemory();
1923 if (skind == PyUnicode_2BYTE_KIND) {
1924 _PyUnicode_CONVERT_BYTES(
1925 Py_UCS2, Py_UCS4,
1926 PyUnicode_2BYTE_DATA(s),
1927 PyUnicode_2BYTE_DATA(s) + len,
1928 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001929 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001930 else {
1931 assert(skind == PyUnicode_1BYTE_KIND);
1932 _PyUnicode_CONVERT_BYTES(
1933 Py_UCS1, Py_UCS4,
1934 PyUnicode_1BYTE_DATA(s),
1935 PyUnicode_1BYTE_DATA(s) + len,
1936 result);
1937 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001938 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001939 default:
1940 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001941 }
Victor Stinner01698042011-10-04 00:04:26 +02001942 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001943 return NULL;
1944}
1945
1946static Py_UCS4*
1947as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1948 int copy_null)
1949{
1950 int kind;
1951 void *data;
1952 Py_ssize_t len, targetlen;
1953 if (PyUnicode_READY(string) == -1)
1954 return NULL;
1955 kind = PyUnicode_KIND(string);
1956 data = PyUnicode_DATA(string);
1957 len = PyUnicode_GET_LENGTH(string);
1958 targetlen = len;
1959 if (copy_null)
1960 targetlen++;
1961 if (!target) {
1962 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
1963 PyErr_NoMemory();
1964 return NULL;
1965 }
1966 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
1967 if (!target) {
1968 PyErr_NoMemory();
1969 return NULL;
1970 }
1971 }
1972 else {
1973 if (targetsize < targetlen) {
1974 PyErr_Format(PyExc_SystemError,
1975 "string is longer than the buffer");
1976 if (copy_null && 0 < targetsize)
1977 target[0] = 0;
1978 return NULL;
1979 }
1980 }
1981 if (kind != PyUnicode_4BYTE_KIND) {
1982 Py_ssize_t i;
1983 for (i = 0; i < len; i++)
1984 target[i] = PyUnicode_READ(kind, data, i);
1985 }
1986 else
1987 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
1988 if (copy_null)
1989 target[len] = 0;
1990 return target;
1991}
1992
1993Py_UCS4*
1994PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1995 int copy_null)
1996{
1997 if (target == NULL || targetsize < 1) {
1998 PyErr_BadInternalCall();
1999 return NULL;
2000 }
2001 return as_ucs4(string, target, targetsize, copy_null);
2002}
2003
2004Py_UCS4*
2005PyUnicode_AsUCS4Copy(PyObject *string)
2006{
2007 return as_ucs4(string, NULL, 0, 1);
2008}
2009
2010#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002011
Alexander Belopolsky40018472011-02-26 01:02:56 +00002012PyObject *
2013PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002014{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002015 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00002016 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002017 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00002018 PyErr_BadInternalCall();
2019 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002020 }
2021
Martin v. Löwis790465f2008-04-05 20:41:37 +00002022 if (size == -1) {
2023 size = wcslen(w);
2024 }
2025
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002026 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002027}
2028
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002029#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002030
Walter Dörwald346737f2007-05-31 10:44:43 +00002031static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002032makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2033 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002034{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002035 *fmt++ = '%';
2036 if (width) {
2037 if (zeropad)
2038 *fmt++ = '0';
2039 fmt += sprintf(fmt, "%d", width);
2040 }
2041 if (precision)
2042 fmt += sprintf(fmt, ".%d", precision);
2043 if (longflag)
2044 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002045 else if (longlongflag) {
2046 /* longlongflag should only ever be nonzero on machines with
2047 HAVE_LONG_LONG defined */
2048#ifdef HAVE_LONG_LONG
2049 char *f = PY_FORMAT_LONG_LONG;
2050 while (*f)
2051 *fmt++ = *f++;
2052#else
2053 /* we shouldn't ever get here */
2054 assert(0);
2055 *fmt++ = 'l';
2056#endif
2057 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002058 else if (size_tflag) {
2059 char *f = PY_FORMAT_SIZE_T;
2060 while (*f)
2061 *fmt++ = *f++;
2062 }
2063 *fmt++ = c;
2064 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002065}
2066
Victor Stinner96865452011-03-01 23:44:09 +00002067/* helper for PyUnicode_FromFormatV() */
2068
2069static const char*
2070parse_format_flags(const char *f,
2071 int *p_width, int *p_precision,
2072 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2073{
2074 int width, precision, longflag, longlongflag, size_tflag;
2075
2076 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2077 f++;
2078 width = 0;
2079 while (Py_ISDIGIT((unsigned)*f))
2080 width = (width*10) + *f++ - '0';
2081 precision = 0;
2082 if (*f == '.') {
2083 f++;
2084 while (Py_ISDIGIT((unsigned)*f))
2085 precision = (precision*10) + *f++ - '0';
2086 if (*f == '%') {
2087 /* "%.3%s" => f points to "3" */
2088 f--;
2089 }
2090 }
2091 if (*f == '\0') {
2092 /* bogus format "%.1" => go backward, f points to "1" */
2093 f--;
2094 }
2095 if (p_width != NULL)
2096 *p_width = width;
2097 if (p_precision != NULL)
2098 *p_precision = precision;
2099
2100 /* Handle %ld, %lu, %lld and %llu. */
2101 longflag = 0;
2102 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002103 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002104
2105 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002106 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002107 longflag = 1;
2108 ++f;
2109 }
2110#ifdef HAVE_LONG_LONG
2111 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002112 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002113 longlongflag = 1;
2114 f += 2;
2115 }
2116#endif
2117 }
2118 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002119 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002120 size_tflag = 1;
2121 ++f;
2122 }
2123 if (p_longflag != NULL)
2124 *p_longflag = longflag;
2125 if (p_longlongflag != NULL)
2126 *p_longlongflag = longlongflag;
2127 if (p_size_tflag != NULL)
2128 *p_size_tflag = size_tflag;
2129 return f;
2130}
2131
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002132/* maximum number of characters required for output of %ld. 21 characters
2133 allows for 64-bit integers (in decimal) and an optional sign. */
2134#define MAX_LONG_CHARS 21
2135/* maximum number of characters required for output of %lld.
2136 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2137 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2138#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2139
Walter Dörwaldd2034312007-05-18 16:29:38 +00002140PyObject *
2141PyUnicode_FromFormatV(const char *format, va_list vargs)
2142{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002143 va_list count;
2144 Py_ssize_t callcount = 0;
2145 PyObject **callresults = NULL;
2146 PyObject **callresult = NULL;
2147 Py_ssize_t n = 0;
2148 int width = 0;
2149 int precision = 0;
2150 int zeropad;
2151 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002152 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002153 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002154 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002155 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2156 Py_UCS4 argmaxchar;
2157 Py_ssize_t numbersize = 0;
2158 char *numberresults = NULL;
2159 char *numberresult = NULL;
2160 Py_ssize_t i;
2161 int kind;
2162 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002163
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002164 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002165 /* step 1: count the number of %S/%R/%A/%s format specifications
2166 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2167 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002168 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002169 * also estimate a upper bound for all the number formats in the string,
2170 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002171 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002172 for (f = format; *f; f++) {
2173 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002174 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002175 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2176 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2177 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2178 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002179
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002180 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002181#ifdef HAVE_LONG_LONG
2182 if (longlongflag) {
2183 if (width < MAX_LONG_LONG_CHARS)
2184 width = MAX_LONG_LONG_CHARS;
2185 }
2186 else
2187#endif
2188 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2189 including sign. Decimal takes the most space. This
2190 isn't enough for octal. If a width is specified we
2191 need more (which we allocate later). */
2192 if (width < MAX_LONG_CHARS)
2193 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002194
2195 /* account for the size + '\0' to separate numbers
2196 inside of the numberresults buffer */
2197 numbersize += (width + 1);
2198 }
2199 }
2200 else if ((unsigned char)*f > 127) {
2201 PyErr_Format(PyExc_ValueError,
2202 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2203 "string, got a non-ASCII byte: 0x%02x",
2204 (unsigned char)*f);
2205 return NULL;
2206 }
2207 }
2208 /* step 2: allocate memory for the results of
2209 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2210 if (callcount) {
2211 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2212 if (!callresults) {
2213 PyErr_NoMemory();
2214 return NULL;
2215 }
2216 callresult = callresults;
2217 }
2218 /* step 2.5: allocate memory for the results of formating numbers */
2219 if (numbersize) {
2220 numberresults = PyObject_Malloc(numbersize);
2221 if (!numberresults) {
2222 PyErr_NoMemory();
2223 goto fail;
2224 }
2225 numberresult = numberresults;
2226 }
2227
2228 /* step 3: format numbers and figure out how large a buffer we need */
2229 for (f = format; *f; f++) {
2230 if (*f == '%') {
2231 const char* p;
2232 int longflag;
2233 int longlongflag;
2234 int size_tflag;
2235 int numprinted;
2236
2237 p = f;
2238 zeropad = (f[1] == '0');
2239 f = parse_format_flags(f, &width, &precision,
2240 &longflag, &longlongflag, &size_tflag);
2241 switch (*f) {
2242 case 'c':
2243 {
2244 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002245 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002246 n++;
2247 break;
2248 }
2249 case '%':
2250 n++;
2251 break;
2252 case 'i':
2253 case 'd':
2254 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2255 width, precision, *f);
2256 if (longflag)
2257 numprinted = sprintf(numberresult, fmt,
2258 va_arg(count, long));
2259#ifdef HAVE_LONG_LONG
2260 else if (longlongflag)
2261 numprinted = sprintf(numberresult, fmt,
2262 va_arg(count, PY_LONG_LONG));
2263#endif
2264 else if (size_tflag)
2265 numprinted = sprintf(numberresult, fmt,
2266 va_arg(count, Py_ssize_t));
2267 else
2268 numprinted = sprintf(numberresult, fmt,
2269 va_arg(count, int));
2270 n += numprinted;
2271 /* advance by +1 to skip over the '\0' */
2272 numberresult += (numprinted + 1);
2273 assert(*(numberresult - 1) == '\0');
2274 assert(*(numberresult - 2) != '\0');
2275 assert(numprinted >= 0);
2276 assert(numberresult <= numberresults + numbersize);
2277 break;
2278 case 'u':
2279 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2280 width, precision, 'u');
2281 if (longflag)
2282 numprinted = sprintf(numberresult, fmt,
2283 va_arg(count, unsigned long));
2284#ifdef HAVE_LONG_LONG
2285 else if (longlongflag)
2286 numprinted = sprintf(numberresult, fmt,
2287 va_arg(count, unsigned PY_LONG_LONG));
2288#endif
2289 else if (size_tflag)
2290 numprinted = sprintf(numberresult, fmt,
2291 va_arg(count, size_t));
2292 else
2293 numprinted = sprintf(numberresult, fmt,
2294 va_arg(count, unsigned int));
2295 n += numprinted;
2296 numberresult += (numprinted + 1);
2297 assert(*(numberresult - 1) == '\0');
2298 assert(*(numberresult - 2) != '\0');
2299 assert(numprinted >= 0);
2300 assert(numberresult <= numberresults + numbersize);
2301 break;
2302 case 'x':
2303 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2304 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2305 n += numprinted;
2306 numberresult += (numprinted + 1);
2307 assert(*(numberresult - 1) == '\0');
2308 assert(*(numberresult - 2) != '\0');
2309 assert(numprinted >= 0);
2310 assert(numberresult <= numberresults + numbersize);
2311 break;
2312 case 'p':
2313 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2314 /* %p is ill-defined: ensure leading 0x. */
2315 if (numberresult[1] == 'X')
2316 numberresult[1] = 'x';
2317 else if (numberresult[1] != 'x') {
2318 memmove(numberresult + 2, numberresult,
2319 strlen(numberresult) + 1);
2320 numberresult[0] = '0';
2321 numberresult[1] = 'x';
2322 numprinted += 2;
2323 }
2324 n += numprinted;
2325 numberresult += (numprinted + 1);
2326 assert(*(numberresult - 1) == '\0');
2327 assert(*(numberresult - 2) != '\0');
2328 assert(numprinted >= 0);
2329 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002330 break;
2331 case 's':
2332 {
2333 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002334 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002335 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2336 if (!str)
2337 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002338 /* since PyUnicode_DecodeUTF8 returns already flexible
2339 unicode objects, there is no need to call ready on them */
2340 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002341 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002342 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002343 /* Remember the str and switch to the next slot */
2344 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002345 break;
2346 }
2347 case 'U':
2348 {
2349 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002350 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002351 if (PyUnicode_READY(obj) == -1)
2352 goto fail;
2353 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002354 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002355 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002356 break;
2357 }
2358 case 'V':
2359 {
2360 PyObject *obj = va_arg(count, PyObject *);
2361 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002362 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002363 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002364 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002365 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002366 if (PyUnicode_READY(obj) == -1)
2367 goto fail;
2368 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002369 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002370 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002371 *callresult++ = NULL;
2372 }
2373 else {
2374 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2375 if (!str_obj)
2376 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002377 if (PyUnicode_READY(str_obj)) {
2378 Py_DECREF(str_obj);
2379 goto fail;
2380 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002381 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002382 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002383 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002384 *callresult++ = str_obj;
2385 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002386 break;
2387 }
2388 case 'S':
2389 {
2390 PyObject *obj = va_arg(count, PyObject *);
2391 PyObject *str;
2392 assert(obj);
2393 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002394 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002395 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002396 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002397 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002398 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002399 /* Remember the str and switch to the next slot */
2400 *callresult++ = str;
2401 break;
2402 }
2403 case 'R':
2404 {
2405 PyObject *obj = va_arg(count, PyObject *);
2406 PyObject *repr;
2407 assert(obj);
2408 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002409 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002410 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002411 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002412 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002413 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002414 /* Remember the repr and switch to the next slot */
2415 *callresult++ = repr;
2416 break;
2417 }
2418 case 'A':
2419 {
2420 PyObject *obj = va_arg(count, PyObject *);
2421 PyObject *ascii;
2422 assert(obj);
2423 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002424 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002425 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002426 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002427 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002428 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002429 /* Remember the repr and switch to the next slot */
2430 *callresult++ = ascii;
2431 break;
2432 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002433 default:
2434 /* if we stumble upon an unknown
2435 formatting code, copy the rest of
2436 the format string to the output
2437 string. (we cannot just skip the
2438 code, since there's no way to know
2439 what's in the argument list) */
2440 n += strlen(p);
2441 goto expand;
2442 }
2443 } else
2444 n++;
2445 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002446 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002447 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002448 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002449 we don't have to resize the string.
2450 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002451 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002452 if (!string)
2453 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002454 kind = PyUnicode_KIND(string);
2455 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002456 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002457 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002459 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002460 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002461 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002462
2463 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002464 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2465 /* checking for == because the last argument could be a empty
2466 string, which causes i to point to end, the assert at the end of
2467 the loop */
2468 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002469
Benjamin Peterson14339b62009-01-31 16:36:08 +00002470 switch (*f) {
2471 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002472 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002473 const int ordinal = va_arg(vargs, int);
2474 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002475 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002476 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002477 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002478 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002479 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002480 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002481 case 'p':
2482 /* unused, since we already have the result */
2483 if (*f == 'p')
2484 (void) va_arg(vargs, void *);
2485 else
2486 (void) va_arg(vargs, int);
2487 /* extract the result from numberresults and append. */
2488 for (; *numberresult; ++i, ++numberresult)
2489 PyUnicode_WRITE(kind, data, i, *numberresult);
2490 /* skip over the separating '\0' */
2491 assert(*numberresult == '\0');
2492 numberresult++;
2493 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002494 break;
2495 case 's':
2496 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002497 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002498 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002499 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002500 size = PyUnicode_GET_LENGTH(*callresult);
2501 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002502 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002503 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002504 /* We're done with the unicode()/repr() => forget it */
2505 Py_DECREF(*callresult);
2506 /* switch to next unicode()/repr() result */
2507 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002508 break;
2509 }
2510 case 'U':
2511 {
2512 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002513 Py_ssize_t size;
2514 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2515 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002516 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002517 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002518 break;
2519 }
2520 case 'V':
2521 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002522 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002523 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002524 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002525 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002526 size = PyUnicode_GET_LENGTH(obj);
2527 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002528 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002529 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002530 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002531 size = PyUnicode_GET_LENGTH(*callresult);
2532 assert(PyUnicode_KIND(*callresult) <=
2533 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002534 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002535 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002536 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002537 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002538 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002539 break;
2540 }
2541 case 'S':
2542 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002543 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002544 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002545 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002546 /* unused, since we already have the result */
2547 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002548 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002549 copy_characters(string, i, *callresult, 0, size);
2550 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002551 /* We're done with the unicode()/repr() => forget it */
2552 Py_DECREF(*callresult);
2553 /* switch to next unicode()/repr() result */
2554 ++callresult;
2555 break;
2556 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002557 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002558 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002559 break;
2560 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002561 for (; *p; ++p, ++i)
2562 PyUnicode_WRITE(kind, data, i, *p);
2563 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002564 goto end;
2565 }
Victor Stinner1205f272010-09-11 00:54:47 +00002566 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002567 else {
2568 assert(i < PyUnicode_GET_LENGTH(string));
2569 PyUnicode_WRITE(kind, data, i++, *f);
2570 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002571 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002572 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002573
Benjamin Peterson29060642009-01-31 22:14:21 +00002574 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002575 if (callresults)
2576 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002577 if (numberresults)
2578 PyObject_Free(numberresults);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002579 assert(_PyUnicode_CheckConsistency(string, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002580 return (PyObject *)string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002581 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002582 if (callresults) {
2583 PyObject **callresult2 = callresults;
2584 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002585 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002586 ++callresult2;
2587 }
2588 PyObject_Free(callresults);
2589 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002590 if (numberresults)
2591 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002592 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002593}
2594
Walter Dörwaldd2034312007-05-18 16:29:38 +00002595PyObject *
2596PyUnicode_FromFormat(const char *format, ...)
2597{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002598 PyObject* ret;
2599 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002600
2601#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002602 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002603#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002604 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002605#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002606 ret = PyUnicode_FromFormatV(format, vargs);
2607 va_end(vargs);
2608 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002609}
2610
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002611#ifdef HAVE_WCHAR_H
2612
Victor Stinner5593d8a2010-10-02 11:11:27 +00002613/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2614 convert a Unicode object to a wide character string.
2615
Victor Stinnerd88d9832011-09-06 02:00:05 +02002616 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002617 character) required to convert the unicode object. Ignore size argument.
2618
Victor Stinnerd88d9832011-09-06 02:00:05 +02002619 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002620 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002621 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002622static Py_ssize_t
Victor Stinner137c34c2010-09-29 10:25:54 +00002623unicode_aswidechar(PyUnicodeObject *unicode,
2624 wchar_t *w,
2625 Py_ssize_t size)
2626{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002627 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002628 const wchar_t *wstr;
2629
2630 wstr = PyUnicode_AsUnicodeAndSize((PyObject *)unicode, &res);
2631 if (wstr == NULL)
2632 return -1;
2633
Victor Stinner5593d8a2010-10-02 11:11:27 +00002634 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002635 if (size > res)
2636 size = res + 1;
2637 else
2638 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002639 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002640 return res;
2641 }
2642 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002643 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002644}
2645
2646Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002647PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002648 wchar_t *w,
2649 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002650{
2651 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002652 PyErr_BadInternalCall();
2653 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002654 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002655 return unicode_aswidechar((PyUnicodeObject*)unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002656}
2657
Victor Stinner137c34c2010-09-29 10:25:54 +00002658wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002659PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002660 Py_ssize_t *size)
2661{
2662 wchar_t* buffer;
2663 Py_ssize_t buflen;
2664
2665 if (unicode == NULL) {
2666 PyErr_BadInternalCall();
2667 return NULL;
2668 }
2669
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002670 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002671 if (buflen == -1)
2672 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002673 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002674 PyErr_NoMemory();
2675 return NULL;
2676 }
2677
Victor Stinner137c34c2010-09-29 10:25:54 +00002678 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2679 if (buffer == NULL) {
2680 PyErr_NoMemory();
2681 return NULL;
2682 }
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002683 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002684 if (buflen == -1)
2685 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002686 if (size != NULL)
2687 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002688 return buffer;
2689}
2690
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002691#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002692
Alexander Belopolsky40018472011-02-26 01:02:56 +00002693PyObject *
2694PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002695{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002696 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002697 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002698 PyErr_SetString(PyExc_ValueError,
2699 "chr() arg not in range(0x110000)");
2700 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002701 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002702
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002703 if (ordinal < 256)
2704 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002705
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002706 v = PyUnicode_New(1, ordinal);
2707 if (v == NULL)
2708 return NULL;
2709 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002710 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002711 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002712}
2713
Alexander Belopolsky40018472011-02-26 01:02:56 +00002714PyObject *
2715PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002716{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002717 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002718 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002719 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002720 if (PyUnicode_READY(obj))
2721 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002722 Py_INCREF(obj);
2723 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002724 }
2725 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002726 /* For a Unicode subtype that's not a Unicode object,
2727 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002728 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002729 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002730 PyErr_Format(PyExc_TypeError,
2731 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002732 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002733 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002734}
2735
Alexander Belopolsky40018472011-02-26 01:02:56 +00002736PyObject *
2737PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002738 const char *encoding,
2739 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002740{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002741 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002742 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002743
Guido van Rossumd57fd912000-03-10 22:53:23 +00002744 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002745 PyErr_BadInternalCall();
2746 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002747 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002748
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002749 /* Decoding bytes objects is the most common case and should be fast */
2750 if (PyBytes_Check(obj)) {
2751 if (PyBytes_GET_SIZE(obj) == 0) {
2752 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002753 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002754 }
2755 else {
2756 v = PyUnicode_Decode(
2757 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2758 encoding, errors);
2759 }
2760 return v;
2761 }
2762
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002763 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002764 PyErr_SetString(PyExc_TypeError,
2765 "decoding str is not supported");
2766 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002767 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002768
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002769 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2770 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2771 PyErr_Format(PyExc_TypeError,
2772 "coercing to str: need bytes, bytearray "
2773 "or buffer-like object, %.80s found",
2774 Py_TYPE(obj)->tp_name);
2775 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002776 }
Tim Petersced69f82003-09-16 20:30:58 +00002777
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002778 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002779 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002780 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002781 }
Tim Petersced69f82003-09-16 20:30:58 +00002782 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002783 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002784
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002785 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002786 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002787}
2788
Victor Stinner600d3be2010-06-10 12:00:55 +00002789/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002790 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2791 1 on success. */
2792static int
2793normalize_encoding(const char *encoding,
2794 char *lower,
2795 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002796{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002797 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002798 char *l;
2799 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002800
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002801 e = encoding;
2802 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002803 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002804 while (*e) {
2805 if (l == l_end)
2806 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002807 if (Py_ISUPPER(*e)) {
2808 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002809 }
2810 else if (*e == '_') {
2811 *l++ = '-';
2812 e++;
2813 }
2814 else {
2815 *l++ = *e++;
2816 }
2817 }
2818 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002819 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002820}
2821
Alexander Belopolsky40018472011-02-26 01:02:56 +00002822PyObject *
2823PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002824 Py_ssize_t size,
2825 const char *encoding,
2826 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002827{
2828 PyObject *buffer = NULL, *unicode;
2829 Py_buffer info;
2830 char lower[11]; /* Enough for any encoding shortcut */
2831
2832 if (encoding == NULL)
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002833 return PyUnicode_DecodeUTF8(s, size, errors);
Fred Drakee4315f52000-05-09 19:53:39 +00002834
2835 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002836 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002837 if ((strcmp(lower, "utf-8") == 0) ||
2838 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002839 return PyUnicode_DecodeUTF8(s, size, errors);
2840 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002841 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002842 (strcmp(lower, "iso-8859-1") == 0))
2843 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002844#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002845 else if (strcmp(lower, "mbcs") == 0)
2846 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002847#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002848 else if (strcmp(lower, "ascii") == 0)
2849 return PyUnicode_DecodeASCII(s, size, errors);
2850 else if (strcmp(lower, "utf-16") == 0)
2851 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2852 else if (strcmp(lower, "utf-32") == 0)
2853 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2854 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002855
2856 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002857 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002858 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002859 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002860 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002861 if (buffer == NULL)
2862 goto onError;
2863 unicode = PyCodec_Decode(buffer, encoding, errors);
2864 if (unicode == NULL)
2865 goto onError;
2866 if (!PyUnicode_Check(unicode)) {
2867 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002868 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002869 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002870 Py_DECREF(unicode);
2871 goto onError;
2872 }
2873 Py_DECREF(buffer);
Victor Stinner17efeed2011-10-04 20:05:46 +02002874#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002875 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002876 Py_DECREF(unicode);
2877 return NULL;
2878 }
Victor Stinner17efeed2011-10-04 20:05:46 +02002879#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002880 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00002881 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002882
Benjamin Peterson29060642009-01-31 22:14:21 +00002883 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002884 Py_XDECREF(buffer);
2885 return NULL;
2886}
2887
Alexander Belopolsky40018472011-02-26 01:02:56 +00002888PyObject *
2889PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002890 const char *encoding,
2891 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002892{
2893 PyObject *v;
2894
2895 if (!PyUnicode_Check(unicode)) {
2896 PyErr_BadArgument();
2897 goto onError;
2898 }
2899
2900 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002901 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002902
2903 /* Decode via the codec registry */
2904 v = PyCodec_Decode(unicode, encoding, errors);
2905 if (v == NULL)
2906 goto onError;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002907 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002908 return v;
2909
Benjamin Peterson29060642009-01-31 22:14:21 +00002910 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002911 return NULL;
2912}
2913
Alexander Belopolsky40018472011-02-26 01:02:56 +00002914PyObject *
2915PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002916 const char *encoding,
2917 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002918{
2919 PyObject *v;
2920
2921 if (!PyUnicode_Check(unicode)) {
2922 PyErr_BadArgument();
2923 goto onError;
2924 }
2925
2926 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002927 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002928
2929 /* Decode via the codec registry */
2930 v = PyCodec_Decode(unicode, encoding, errors);
2931 if (v == NULL)
2932 goto onError;
2933 if (!PyUnicode_Check(v)) {
2934 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002935 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002936 Py_TYPE(v)->tp_name);
2937 Py_DECREF(v);
2938 goto onError;
2939 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002940 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002941 return v;
2942
Benjamin Peterson29060642009-01-31 22:14:21 +00002943 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002944 return NULL;
2945}
2946
Alexander Belopolsky40018472011-02-26 01:02:56 +00002947PyObject *
2948PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002949 Py_ssize_t size,
2950 const char *encoding,
2951 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002952{
2953 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002954
Guido van Rossumd57fd912000-03-10 22:53:23 +00002955 unicode = PyUnicode_FromUnicode(s, size);
2956 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002957 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002958 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
2959 Py_DECREF(unicode);
2960 return v;
2961}
2962
Alexander Belopolsky40018472011-02-26 01:02:56 +00002963PyObject *
2964PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002965 const char *encoding,
2966 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002967{
2968 PyObject *v;
2969
2970 if (!PyUnicode_Check(unicode)) {
2971 PyErr_BadArgument();
2972 goto onError;
2973 }
2974
2975 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002976 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002977
2978 /* Encode via the codec registry */
2979 v = PyCodec_Encode(unicode, encoding, errors);
2980 if (v == NULL)
2981 goto onError;
2982 return v;
2983
Benjamin Peterson29060642009-01-31 22:14:21 +00002984 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002985 return NULL;
2986}
2987
Victor Stinnerad158722010-10-27 00:25:46 +00002988PyObject *
2989PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00002990{
Victor Stinner99b95382011-07-04 14:23:54 +02002991#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00002992 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
2993 PyUnicode_GET_SIZE(unicode),
2994 NULL);
2995#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002996 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00002997#else
Victor Stinner793b5312011-04-27 00:24:21 +02002998 PyInterpreterState *interp = PyThreadState_GET()->interp;
2999 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3000 cannot use it to encode and decode filenames before it is loaded. Load
3001 the Python codec requires to encode at least its own filename. Use the C
3002 version of the locale codec until the codec registry is initialized and
3003 the Python codec is loaded.
3004
3005 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3006 cannot only rely on it: check also interp->fscodec_initialized for
3007 subinterpreters. */
3008 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003009 return PyUnicode_AsEncodedString(unicode,
3010 Py_FileSystemDefaultEncoding,
3011 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003012 }
3013 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003014 /* locale encoding with surrogateescape */
3015 wchar_t *wchar;
3016 char *bytes;
3017 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003018 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003019
3020 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3021 if (wchar == NULL)
3022 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003023 bytes = _Py_wchar2char(wchar, &error_pos);
3024 if (bytes == NULL) {
3025 if (error_pos != (size_t)-1) {
3026 char *errmsg = strerror(errno);
3027 PyObject *exc = NULL;
3028 if (errmsg == NULL)
3029 errmsg = "Py_wchar2char() failed";
3030 raise_encode_exception(&exc,
3031 "filesystemencoding",
3032 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
3033 error_pos, error_pos+1,
3034 errmsg);
3035 Py_XDECREF(exc);
3036 }
3037 else
3038 PyErr_NoMemory();
3039 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003040 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003041 }
3042 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003043
3044 bytes_obj = PyBytes_FromString(bytes);
3045 PyMem_Free(bytes);
3046 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003047 }
Victor Stinnerad158722010-10-27 00:25:46 +00003048#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003049}
3050
Alexander Belopolsky40018472011-02-26 01:02:56 +00003051PyObject *
3052PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003053 const char *encoding,
3054 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003055{
3056 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003057 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003058
Guido van Rossumd57fd912000-03-10 22:53:23 +00003059 if (!PyUnicode_Check(unicode)) {
3060 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003061 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003062 }
Fred Drakee4315f52000-05-09 19:53:39 +00003063
Victor Stinner2f283c22011-03-02 01:21:46 +00003064 if (encoding == NULL) {
3065 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003066 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003067 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003068 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner2f283c22011-03-02 01:21:46 +00003069 }
Fred Drakee4315f52000-05-09 19:53:39 +00003070
3071 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003072 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003073 if ((strcmp(lower, "utf-8") == 0) ||
3074 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003075 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003076 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003077 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003078 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003079 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003080 }
Victor Stinner37296e82010-06-10 13:36:23 +00003081 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003082 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003083 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003084 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003085#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003086 else if (strcmp(lower, "mbcs") == 0)
3087 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3088 PyUnicode_GET_SIZE(unicode),
3089 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003090#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003091 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003092 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003093 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003094
3095 /* Encode via the codec registry */
3096 v = PyCodec_Encode(unicode, encoding, errors);
3097 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003098 return NULL;
3099
3100 /* The normal path */
3101 if (PyBytes_Check(v))
3102 return v;
3103
3104 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003105 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003106 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003107 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003108
3109 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3110 "encoder %s returned bytearray instead of bytes",
3111 encoding);
3112 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003113 Py_DECREF(v);
3114 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003115 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003116
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003117 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3118 Py_DECREF(v);
3119 return b;
3120 }
3121
3122 PyErr_Format(PyExc_TypeError,
3123 "encoder did not return a bytes object (type=%.400s)",
3124 Py_TYPE(v)->tp_name);
3125 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003126 return NULL;
3127}
3128
Alexander Belopolsky40018472011-02-26 01:02:56 +00003129PyObject *
3130PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003131 const char *encoding,
3132 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003133{
3134 PyObject *v;
3135
3136 if (!PyUnicode_Check(unicode)) {
3137 PyErr_BadArgument();
3138 goto onError;
3139 }
3140
3141 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003142 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003143
3144 /* Encode via the codec registry */
3145 v = PyCodec_Encode(unicode, encoding, errors);
3146 if (v == NULL)
3147 goto onError;
3148 if (!PyUnicode_Check(v)) {
3149 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003150 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003151 Py_TYPE(v)->tp_name);
3152 Py_DECREF(v);
3153 goto onError;
3154 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003155 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003156
Benjamin Peterson29060642009-01-31 22:14:21 +00003157 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003158 return NULL;
3159}
3160
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003161PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003162PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003163 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003164 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3165}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003166
Christian Heimes5894ba72007-11-04 11:43:14 +00003167PyObject*
3168PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3169{
Victor Stinner99b95382011-07-04 14:23:54 +02003170#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003171 return PyUnicode_DecodeMBCS(s, size, NULL);
3172#elif defined(__APPLE__)
3173 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3174#else
Victor Stinner793b5312011-04-27 00:24:21 +02003175 PyInterpreterState *interp = PyThreadState_GET()->interp;
3176 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3177 cannot use it to encode and decode filenames before it is loaded. Load
3178 the Python codec requires to encode at least its own filename. Use the C
3179 version of the locale codec until the codec registry is initialized and
3180 the Python codec is loaded.
3181
3182 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3183 cannot only rely on it: check also interp->fscodec_initialized for
3184 subinterpreters. */
3185 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003186 return PyUnicode_Decode(s, size,
3187 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003188 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003189 }
3190 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003191 /* locale encoding with surrogateescape */
3192 wchar_t *wchar;
3193 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003194 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003195
3196 if (s[size] != '\0' || size != strlen(s)) {
3197 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3198 return NULL;
3199 }
3200
Victor Stinner168e1172010-10-16 23:16:16 +00003201 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003202 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003203 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003204
Victor Stinner168e1172010-10-16 23:16:16 +00003205 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003206 PyMem_Free(wchar);
3207 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003208 }
Victor Stinnerad158722010-10-27 00:25:46 +00003209#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003210}
3211
Martin v. Löwis011e8422009-05-05 04:43:17 +00003212
3213int
3214PyUnicode_FSConverter(PyObject* arg, void* addr)
3215{
3216 PyObject *output = NULL;
3217 Py_ssize_t size;
3218 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003219 if (arg == NULL) {
3220 Py_DECREF(*(PyObject**)addr);
3221 return 1;
3222 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003223 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003224 output = arg;
3225 Py_INCREF(output);
3226 }
3227 else {
3228 arg = PyUnicode_FromObject(arg);
3229 if (!arg)
3230 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003231 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003232 Py_DECREF(arg);
3233 if (!output)
3234 return 0;
3235 if (!PyBytes_Check(output)) {
3236 Py_DECREF(output);
3237 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3238 return 0;
3239 }
3240 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003241 size = PyBytes_GET_SIZE(output);
3242 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003243 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003244 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003245 Py_DECREF(output);
3246 return 0;
3247 }
3248 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003249 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003250}
3251
3252
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003253int
3254PyUnicode_FSDecoder(PyObject* arg, void* addr)
3255{
3256 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003257 if (arg == NULL) {
3258 Py_DECREF(*(PyObject**)addr);
3259 return 1;
3260 }
3261 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003262 if (PyUnicode_READY(arg))
3263 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003264 output = arg;
3265 Py_INCREF(output);
3266 }
3267 else {
3268 arg = PyBytes_FromObject(arg);
3269 if (!arg)
3270 return 0;
3271 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3272 PyBytes_GET_SIZE(arg));
3273 Py_DECREF(arg);
3274 if (!output)
3275 return 0;
3276 if (!PyUnicode_Check(output)) {
3277 Py_DECREF(output);
3278 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3279 return 0;
3280 }
3281 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003282 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
3283 PyUnicode_GET_LENGTH(output), 0, 1)) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003284 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3285 Py_DECREF(output);
3286 return 0;
3287 }
3288 *(PyObject**)addr = output;
3289 return Py_CLEANUP_SUPPORTED;
3290}
3291
3292
Martin v. Löwis5b222132007-06-10 09:51:05 +00003293char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003294PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003295{
Christian Heimesf3863112007-11-22 07:46:41 +00003296 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003297 PyUnicodeObject *u = (PyUnicodeObject *)unicode;
3298
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003299 if (!PyUnicode_Check(unicode)) {
3300 PyErr_BadArgument();
3301 return NULL;
3302 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003303 if (PyUnicode_READY(u) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003304 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003305
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003306 if (PyUnicode_UTF8(unicode) == NULL) {
3307 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003308 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3309 if (bytes == NULL)
3310 return NULL;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003311 _PyUnicode_UTF8(u) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3312 if (_PyUnicode_UTF8(u) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003313 Py_DECREF(bytes);
3314 return NULL;
3315 }
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003316 _PyUnicode_UTF8_LENGTH(u) = PyBytes_GET_SIZE(bytes);
3317 Py_MEMCPY(_PyUnicode_UTF8(u), PyBytes_AS_STRING(bytes), _PyUnicode_UTF8_LENGTH(u) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003318 Py_DECREF(bytes);
3319 }
3320
3321 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003322 *psize = PyUnicode_UTF8_LENGTH(unicode);
3323 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003324}
3325
3326char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003327PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003328{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003329 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3330}
3331
3332#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003333static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003334#endif
3335
3336
3337Py_UNICODE *
3338PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3339{
3340 PyUnicodeObject *u;
3341 const unsigned char *one_byte;
3342#if SIZEOF_WCHAR_T == 4
3343 const Py_UCS2 *two_bytes;
3344#else
3345 const Py_UCS4 *four_bytes;
3346 const Py_UCS4 *ucs4_end;
3347 Py_ssize_t num_surrogates;
3348#endif
3349 wchar_t *w;
3350 wchar_t *wchar_end;
3351
3352 if (!PyUnicode_Check(unicode)) {
3353 PyErr_BadArgument();
3354 return NULL;
3355 }
3356 u = (PyUnicodeObject*)unicode;
3357 if (_PyUnicode_WSTR(u) == NULL) {
3358 /* Non-ASCII compact unicode object */
3359 assert(_PyUnicode_KIND(u) != 0);
3360 assert(PyUnicode_IS_READY(u));
3361
3362#ifdef Py_DEBUG
3363 ++unicode_as_unicode_calls;
3364#endif
3365
3366 if (PyUnicode_KIND(u) == PyUnicode_4BYTE_KIND) {
3367#if SIZEOF_WCHAR_T == 2
3368 four_bytes = PyUnicode_4BYTE_DATA(u);
3369 ucs4_end = four_bytes + _PyUnicode_LENGTH(u);
3370 num_surrogates = 0;
3371
3372 for (; four_bytes < ucs4_end; ++four_bytes) {
3373 if (*four_bytes > 0xFFFF)
3374 ++num_surrogates;
3375 }
3376
3377 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(
3378 sizeof(wchar_t) * (_PyUnicode_LENGTH(u) + 1 + num_surrogates));
3379 if (!_PyUnicode_WSTR(u)) {
3380 PyErr_NoMemory();
3381 return NULL;
3382 }
3383 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u) + num_surrogates;
3384
3385 w = _PyUnicode_WSTR(u);
3386 wchar_end = w + _PyUnicode_WSTR_LENGTH(u);
3387 four_bytes = PyUnicode_4BYTE_DATA(u);
3388 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3389 if (*four_bytes > 0xFFFF) {
3390 /* encode surrogate pair in this case */
3391 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3392 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3393 }
3394 else
3395 *w = *four_bytes;
3396
3397 if (w > wchar_end) {
3398 assert(0 && "Miscalculated string end");
3399 }
3400 }
3401 *w = 0;
3402#else
3403 /* sizeof(wchar_t) == 4 */
3404 Py_FatalError("Impossible unicode object state, wstr and str "
3405 "should share memory already.");
3406 return NULL;
3407#endif
3408 }
3409 else {
3410 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3411 (_PyUnicode_LENGTH(u) + 1));
3412 if (!_PyUnicode_WSTR(u)) {
3413 PyErr_NoMemory();
3414 return NULL;
3415 }
3416 if (!PyUnicode_IS_COMPACT_ASCII(u))
3417 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u);
3418 w = _PyUnicode_WSTR(u);
3419 wchar_end = w + _PyUnicode_LENGTH(u);
3420
3421 if (PyUnicode_KIND(u) == PyUnicode_1BYTE_KIND) {
3422 one_byte = PyUnicode_1BYTE_DATA(u);
3423 for (; w < wchar_end; ++one_byte, ++w)
3424 *w = *one_byte;
3425 /* null-terminate the wstr */
3426 *w = 0;
3427 }
3428 else if (PyUnicode_KIND(u) == PyUnicode_2BYTE_KIND) {
3429#if SIZEOF_WCHAR_T == 4
3430 two_bytes = PyUnicode_2BYTE_DATA(u);
3431 for (; w < wchar_end; ++two_bytes, ++w)
3432 *w = *two_bytes;
3433 /* null-terminate the wstr */
3434 *w = 0;
3435#else
3436 /* sizeof(wchar_t) == 2 */
3437 PyObject_FREE(_PyUnicode_WSTR(u));
3438 _PyUnicode_WSTR(u) = NULL;
3439 Py_FatalError("Impossible unicode object state, wstr "
3440 "and str should share memory already.");
3441 return NULL;
3442#endif
3443 }
3444 else {
3445 assert(0 && "This should never happen.");
3446 }
3447 }
3448 }
3449 if (size != NULL)
3450 *size = PyUnicode_WSTR_LENGTH(u);
3451 return _PyUnicode_WSTR(u);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003452}
3453
Alexander Belopolsky40018472011-02-26 01:02:56 +00003454Py_UNICODE *
3455PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003456{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003457 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003458}
3459
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003460
Alexander Belopolsky40018472011-02-26 01:02:56 +00003461Py_ssize_t
3462PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003463{
3464 if (!PyUnicode_Check(unicode)) {
3465 PyErr_BadArgument();
3466 goto onError;
3467 }
3468 return PyUnicode_GET_SIZE(unicode);
3469
Benjamin Peterson29060642009-01-31 22:14:21 +00003470 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003471 return -1;
3472}
3473
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003474Py_ssize_t
3475PyUnicode_GetLength(PyObject *unicode)
3476{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003477 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003478 PyErr_BadArgument();
3479 return -1;
3480 }
3481
3482 return PyUnicode_GET_LENGTH(unicode);
3483}
3484
3485Py_UCS4
3486PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3487{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003488 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3489 PyErr_BadArgument();
3490 return (Py_UCS4)-1;
3491 }
3492 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3493 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003494 return (Py_UCS4)-1;
3495 }
3496 return PyUnicode_READ_CHAR(unicode, index);
3497}
3498
3499int
3500PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3501{
3502 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003503 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003504 return -1;
3505 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003506 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3507 PyErr_SetString(PyExc_IndexError, "string index out of range");
3508 return -1;
3509 }
3510 if (_PyUnicode_Dirty(unicode))
3511 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003512 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3513 index, ch);
3514 return 0;
3515}
3516
Alexander Belopolsky40018472011-02-26 01:02:56 +00003517const char *
3518PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003519{
Victor Stinner42cb4622010-09-01 19:39:01 +00003520 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003521}
3522
Victor Stinner554f3f02010-06-16 23:33:54 +00003523/* create or adjust a UnicodeDecodeError */
3524static void
3525make_decode_exception(PyObject **exceptionObject,
3526 const char *encoding,
3527 const char *input, Py_ssize_t length,
3528 Py_ssize_t startpos, Py_ssize_t endpos,
3529 const char *reason)
3530{
3531 if (*exceptionObject == NULL) {
3532 *exceptionObject = PyUnicodeDecodeError_Create(
3533 encoding, input, length, startpos, endpos, reason);
3534 }
3535 else {
3536 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3537 goto onError;
3538 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3539 goto onError;
3540 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3541 goto onError;
3542 }
3543 return;
3544
3545onError:
3546 Py_DECREF(*exceptionObject);
3547 *exceptionObject = NULL;
3548}
3549
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003550/* error handling callback helper:
3551 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003552 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003553 and adjust various state variables.
3554 return 0 on success, -1 on error
3555*/
3556
Alexander Belopolsky40018472011-02-26 01:02:56 +00003557static int
3558unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003559 const char *encoding, const char *reason,
3560 const char **input, const char **inend, Py_ssize_t *startinpos,
3561 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3562 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003563{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003564 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003565
3566 PyObject *restuple = NULL;
3567 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003568 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003569 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003570 Py_ssize_t requiredsize;
3571 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003572 const Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003573 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003574 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003575 int res = -1;
3576
3577 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003578 *errorHandler = PyCodec_LookupError(errors);
3579 if (*errorHandler == NULL)
3580 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003581 }
3582
Victor Stinner554f3f02010-06-16 23:33:54 +00003583 make_decode_exception(exceptionObject,
3584 encoding,
3585 *input, *inend - *input,
3586 *startinpos, *endinpos,
3587 reason);
3588 if (*exceptionObject == NULL)
3589 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003590
3591 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3592 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003593 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003594 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003595 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003596 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003597 }
3598 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003599 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003600
3601 /* Copy back the bytes variables, which might have been modified by the
3602 callback */
3603 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3604 if (!inputobj)
3605 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003606 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003607 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003608 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003609 *input = PyBytes_AS_STRING(inputobj);
3610 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003611 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003612 /* we can DECREF safely, as the exception has another reference,
3613 so the object won't go away. */
3614 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003615
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003616 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003617 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003618 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003619 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3620 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003621 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003622
3623 /* need more space? (at least enough for what we
3624 have+the replacement+the rest of the string (starting
3625 at the new input position), so we won't have to check space
3626 when there are no errors in the rest of the string) */
3627 repptr = PyUnicode_AS_UNICODE(repunicode);
3628 repsize = PyUnicode_GET_SIZE(repunicode);
3629 requiredsize = *outpos + repsize + insize-newpos;
3630 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003631 if (requiredsize<2*outsize)
3632 requiredsize = 2*outsize;
Victor Stinnerfe226c02011-10-03 03:52:20 +02003633 if (PyUnicode_Resize((PyObject**)output, requiredsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003634 goto onError;
3635 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003636 }
3637 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003638 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003639 Py_UNICODE_COPY(*outptr, repptr, repsize);
3640 *outptr += repsize;
3641 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003642
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003643 /* we made it! */
3644 res = 0;
3645
Benjamin Peterson29060642009-01-31 22:14:21 +00003646 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003647 Py_XDECREF(restuple);
3648 return res;
3649}
3650
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003651/* --- UTF-7 Codec -------------------------------------------------------- */
3652
Antoine Pitrou244651a2009-05-04 18:56:13 +00003653/* See RFC2152 for details. We encode conservatively and decode liberally. */
3654
3655/* Three simple macros defining base-64. */
3656
3657/* Is c a base-64 character? */
3658
3659#define IS_BASE64(c) \
3660 (((c) >= 'A' && (c) <= 'Z') || \
3661 ((c) >= 'a' && (c) <= 'z') || \
3662 ((c) >= '0' && (c) <= '9') || \
3663 (c) == '+' || (c) == '/')
3664
3665/* given that c is a base-64 character, what is its base-64 value? */
3666
3667#define FROM_BASE64(c) \
3668 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3669 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3670 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3671 (c) == '+' ? 62 : 63)
3672
3673/* What is the base-64 character of the bottom 6 bits of n? */
3674
3675#define TO_BASE64(n) \
3676 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3677
3678/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3679 * decoded as itself. We are permissive on decoding; the only ASCII
3680 * byte not decoding to itself is the + which begins a base64
3681 * string. */
3682
3683#define DECODE_DIRECT(c) \
3684 ((c) <= 127 && (c) != '+')
3685
3686/* The UTF-7 encoder treats ASCII characters differently according to
3687 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3688 * the above). See RFC2152. This array identifies these different
3689 * sets:
3690 * 0 : "Set D"
3691 * alphanumeric and '(),-./:?
3692 * 1 : "Set O"
3693 * !"#$%&*;<=>@[]^_`{|}
3694 * 2 : "whitespace"
3695 * ht nl cr sp
3696 * 3 : special (must be base64 encoded)
3697 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3698 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003699
Tim Petersced69f82003-09-16 20:30:58 +00003700static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003701char utf7_category[128] = {
3702/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3703 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3704/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3705 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3706/* sp ! " # $ % & ' ( ) * + , - . / */
3707 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3708/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3709 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3710/* @ A B C D E F G H I J K L M N O */
3711 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3712/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3713 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3714/* ` a b c d e f g h i j k l m n o */
3715 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3716/* p q r s t u v w x y z { | } ~ del */
3717 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003718};
3719
Antoine Pitrou244651a2009-05-04 18:56:13 +00003720/* ENCODE_DIRECT: this character should be encoded as itself. The
3721 * answer depends on whether we are encoding set O as itself, and also
3722 * on whether we are encoding whitespace as itself. RFC2152 makes it
3723 * clear that the answers to these questions vary between
3724 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003725
Antoine Pitrou244651a2009-05-04 18:56:13 +00003726#define ENCODE_DIRECT(c, directO, directWS) \
3727 ((c) < 128 && (c) > 0 && \
3728 ((utf7_category[(c)] == 0) || \
3729 (directWS && (utf7_category[(c)] == 2)) || \
3730 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003731
Alexander Belopolsky40018472011-02-26 01:02:56 +00003732PyObject *
3733PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003734 Py_ssize_t size,
3735 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003736{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003737 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3738}
3739
Antoine Pitrou244651a2009-05-04 18:56:13 +00003740/* The decoder. The only state we preserve is our read position,
3741 * i.e. how many characters we have consumed. So if we end in the
3742 * middle of a shift sequence we have to back off the read position
3743 * and the output to the beginning of the sequence, otherwise we lose
3744 * all the shift state (seen bits, number of bits seen, high
3745 * surrogate). */
3746
Alexander Belopolsky40018472011-02-26 01:02:56 +00003747PyObject *
3748PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003749 Py_ssize_t size,
3750 const char *errors,
3751 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003752{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003753 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003754 Py_ssize_t startinpos;
3755 Py_ssize_t endinpos;
3756 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003757 const char *e;
3758 PyUnicodeObject *unicode;
3759 Py_UNICODE *p;
3760 const char *errmsg = "";
3761 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003762 Py_UNICODE *shiftOutStart;
3763 unsigned int base64bits = 0;
3764 unsigned long base64buffer = 0;
3765 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003766 PyObject *errorHandler = NULL;
3767 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003768
3769 unicode = _PyUnicode_New(size);
3770 if (!unicode)
3771 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003772 if (size == 0) {
3773 if (consumed)
3774 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003775 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003776 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003777
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003778 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitrou244651a2009-05-04 18:56:13 +00003779 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003780 e = s + size;
3781
3782 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003783 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003784 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003785 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003786
Antoine Pitrou244651a2009-05-04 18:56:13 +00003787 if (inShift) { /* in a base-64 section */
3788 if (IS_BASE64(ch)) { /* consume a base-64 character */
3789 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3790 base64bits += 6;
3791 s++;
3792 if (base64bits >= 16) {
3793 /* we have enough bits for a UTF-16 value */
3794 Py_UNICODE outCh = (Py_UNICODE)
3795 (base64buffer >> (base64bits-16));
3796 base64bits -= 16;
3797 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3798 if (surrogate) {
3799 /* expecting a second surrogate */
3800 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3801#ifdef Py_UNICODE_WIDE
3802 *p++ = (((surrogate & 0x3FF)<<10)
3803 | (outCh & 0x3FF)) + 0x10000;
3804#else
3805 *p++ = surrogate;
3806 *p++ = outCh;
3807#endif
3808 surrogate = 0;
3809 }
3810 else {
3811 surrogate = 0;
3812 errmsg = "second surrogate missing";
3813 goto utf7Error;
3814 }
3815 }
3816 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3817 /* first surrogate */
3818 surrogate = outCh;
3819 }
3820 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3821 errmsg = "unexpected second surrogate";
3822 goto utf7Error;
3823 }
3824 else {
3825 *p++ = outCh;
3826 }
3827 }
3828 }
3829 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003830 inShift = 0;
3831 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003832 if (surrogate) {
3833 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003834 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003835 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003836 if (base64bits > 0) { /* left-over bits */
3837 if (base64bits >= 6) {
3838 /* We've seen at least one base-64 character */
3839 errmsg = "partial character in shift sequence";
3840 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003841 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003842 else {
3843 /* Some bits remain; they should be zero */
3844 if (base64buffer != 0) {
3845 errmsg = "non-zero padding bits in shift sequence";
3846 goto utf7Error;
3847 }
3848 }
3849 }
3850 if (ch != '-') {
3851 /* '-' is absorbed; other terminating
3852 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003853 *p++ = ch;
3854 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003855 }
3856 }
3857 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003858 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003859 s++; /* consume '+' */
3860 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003861 s++;
3862 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00003863 }
3864 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003865 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003866 shiftOutStart = p;
3867 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003868 }
3869 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003870 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003871 *p++ = ch;
3872 s++;
3873 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003874 else {
3875 startinpos = s-starts;
3876 s++;
3877 errmsg = "unexpected special character";
3878 goto utf7Error;
3879 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003880 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003881utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003882 outpos = p-PyUnicode_AS_UNICODE(unicode);
3883 endinpos = s-starts;
3884 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003885 errors, &errorHandler,
3886 "utf7", errmsg,
3887 &starts, &e, &startinpos, &endinpos, &exc, &s,
3888 &unicode, &outpos, &p))
3889 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003890 }
3891
Antoine Pitrou244651a2009-05-04 18:56:13 +00003892 /* end of string */
3893
3894 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3895 /* if we're in an inconsistent state, that's an error */
3896 if (surrogate ||
3897 (base64bits >= 6) ||
3898 (base64bits > 0 && base64buffer != 0)) {
3899 outpos = p-PyUnicode_AS_UNICODE(unicode);
3900 endinpos = size;
3901 if (unicode_decode_call_errorhandler(
3902 errors, &errorHandler,
3903 "utf7", "unterminated shift sequence",
3904 &starts, &e, &startinpos, &endinpos, &exc, &s,
3905 &unicode, &outpos, &p))
3906 goto onError;
3907 if (s < e)
3908 goto restart;
3909 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003910 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003911
3912 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003913 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003914 if (inShift) {
3915 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003916 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003917 }
3918 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003919 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003920 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003921 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003922
Victor Stinnerfe226c02011-10-03 03:52:20 +02003923 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003924 goto onError;
3925
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003926 Py_XDECREF(errorHandler);
3927 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02003928#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02003929 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003930 Py_DECREF(unicode);
3931 return NULL;
3932 }
Victor Stinner17efeed2011-10-04 20:05:46 +02003933#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003934 assert(_PyUnicode_CheckConsistency(unicode, 1));
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003935 return (PyObject *)unicode;
3936
Benjamin Peterson29060642009-01-31 22:14:21 +00003937 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003938 Py_XDECREF(errorHandler);
3939 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003940 Py_DECREF(unicode);
3941 return NULL;
3942}
3943
3944
Alexander Belopolsky40018472011-02-26 01:02:56 +00003945PyObject *
3946PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003947 Py_ssize_t size,
3948 int base64SetO,
3949 int base64WhiteSpace,
3950 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003951{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003952 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003953 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003954 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003955 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003956 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003957 unsigned int base64bits = 0;
3958 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003959 char * out;
3960 char * start;
3961
3962 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003963 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003964
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003965 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003966 return PyErr_NoMemory();
3967
Antoine Pitrou244651a2009-05-04 18:56:13 +00003968 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003969 if (v == NULL)
3970 return NULL;
3971
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003972 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003973 for (;i < size; ++i) {
3974 Py_UNICODE ch = s[i];
3975
Antoine Pitrou244651a2009-05-04 18:56:13 +00003976 if (inShift) {
3977 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
3978 /* shifting out */
3979 if (base64bits) { /* output remaining bits */
3980 *out++ = TO_BASE64(base64buffer << (6-base64bits));
3981 base64buffer = 0;
3982 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003983 }
3984 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003985 /* Characters not in the BASE64 set implicitly unshift the sequence
3986 so no '-' is required, except if the character is itself a '-' */
3987 if (IS_BASE64(ch) || ch == '-') {
3988 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003989 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003990 *out++ = (char) ch;
3991 }
3992 else {
3993 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00003994 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003995 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003996 else { /* not in a shift sequence */
3997 if (ch == '+') {
3998 *out++ = '+';
3999 *out++ = '-';
4000 }
4001 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4002 *out++ = (char) ch;
4003 }
4004 else {
4005 *out++ = '+';
4006 inShift = 1;
4007 goto encode_char;
4008 }
4009 }
4010 continue;
4011encode_char:
4012#ifdef Py_UNICODE_WIDE
4013 if (ch >= 0x10000) {
4014 /* code first surrogate */
4015 base64bits += 16;
4016 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4017 while (base64bits >= 6) {
4018 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4019 base64bits -= 6;
4020 }
4021 /* prepare second surrogate */
4022 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4023 }
4024#endif
4025 base64bits += 16;
4026 base64buffer = (base64buffer << 16) | ch;
4027 while (base64bits >= 6) {
4028 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4029 base64bits -= 6;
4030 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004031 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004032 if (base64bits)
4033 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4034 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004035 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004036 if (_PyBytes_Resize(&v, out - start) < 0)
4037 return NULL;
4038 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004039}
4040
Antoine Pitrou244651a2009-05-04 18:56:13 +00004041#undef IS_BASE64
4042#undef FROM_BASE64
4043#undef TO_BASE64
4044#undef DECODE_DIRECT
4045#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004046
Guido van Rossumd57fd912000-03-10 22:53:23 +00004047/* --- UTF-8 Codec -------------------------------------------------------- */
4048
Tim Petersced69f82003-09-16 20:30:58 +00004049static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004050char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004051 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4052 illegal prefix. See RFC 3629 for details */
4053 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4054 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004055 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004056 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4057 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4058 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4059 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004060 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4061 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 +00004062 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4063 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004064 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4065 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4066 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4067 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4068 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 +00004069};
4070
Alexander Belopolsky40018472011-02-26 01:02:56 +00004071PyObject *
4072PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004073 Py_ssize_t size,
4074 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004075{
Walter Dörwald69652032004-09-07 20:24:22 +00004076 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4077}
4078
Antoine Pitrouab868312009-01-10 15:40:25 +00004079/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4080#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4081
4082/* Mask to quickly check whether a C 'long' contains a
4083 non-ASCII, UTF8-encoded char. */
4084#if (SIZEOF_LONG == 8)
4085# define ASCII_CHAR_MASK 0x8080808080808080L
4086#elif (SIZEOF_LONG == 4)
4087# define ASCII_CHAR_MASK 0x80808080L
4088#else
4089# error C 'long' size should be either 4 or 8!
4090#endif
4091
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004092/* Scans a UTF-8 string and returns the maximum character to be expected,
4093 the size of the decoded unicode string and if any major errors were
4094 encountered.
4095
4096 This function does check basic UTF-8 sanity, it does however NOT CHECK
4097 if the string contains surrogates, and if all continuation bytes are
4098 within the correct ranges, these checks are performed in
4099 PyUnicode_DecodeUTF8Stateful.
4100
4101 If it sets has_errors to 1, it means the value of unicode_size and max_char
4102 will be bogus and you should not rely on useful information in them.
4103 */
4104static Py_UCS4
4105utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
4106 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
4107 int *has_errors)
4108{
4109 Py_ssize_t n;
4110 Py_ssize_t char_count = 0;
4111 Py_UCS4 max_char = 127, new_max;
4112 Py_UCS4 upper_bound;
4113 const unsigned char *p = (const unsigned char *)s;
4114 const unsigned char *end = p + string_size;
4115 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
4116 int err = 0;
4117
4118 for (; p < end && !err; ++p, ++char_count) {
4119 /* Only check value if it's not a ASCII char... */
4120 if (*p < 0x80) {
4121 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4122 an explanation. */
4123 if (!((size_t) p & LONG_PTR_MASK)) {
4124 /* Help register allocation */
4125 register const unsigned char *_p = p;
4126 while (_p < aligned_end) {
4127 unsigned long value = *(unsigned long *) _p;
4128 if (value & ASCII_CHAR_MASK)
4129 break;
4130 _p += SIZEOF_LONG;
4131 char_count += SIZEOF_LONG;
4132 }
4133 p = _p;
4134 if (p == end)
4135 break;
4136 }
4137 }
4138 if (*p >= 0x80) {
4139 n = utf8_code_length[*p];
4140 new_max = max_char;
4141 switch (n) {
4142 /* invalid start byte */
4143 case 0:
4144 err = 1;
4145 break;
4146 case 2:
4147 /* Code points between 0x00FF and 0x07FF inclusive.
4148 Approximate the upper bound of the code point,
4149 if this flips over 255 we can be sure it will be more
4150 than 255 and the string will need 2 bytes per code coint,
4151 if it stays under or equal to 255, we can be sure 1 byte
4152 is enough.
4153 ((*p & 0b00011111) << 6) | 0b00111111 */
4154 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
4155 if (max_char < upper_bound)
4156 new_max = upper_bound;
4157 /* Ensure we track at least that we left ASCII space. */
4158 if (new_max < 128)
4159 new_max = 128;
4160 break;
4161 case 3:
4162 /* Between 0x0FFF and 0xFFFF inclusive, so values are
4163 always > 255 and <= 65535 and will always need 2 bytes. */
4164 if (max_char < 65535)
4165 new_max = 65535;
4166 break;
4167 case 4:
4168 /* Code point will be above 0xFFFF for sure in this case. */
4169 new_max = 65537;
4170 break;
4171 /* Internal error, this should be caught by the first if */
4172 case 1:
4173 default:
4174 assert(0 && "Impossible case in utf8_max_char_and_size");
4175 err = 1;
4176 }
4177 /* Instead of number of overall bytes for this code point,
Georg Brandl7597add2011-10-05 16:36:47 +02004178 n contains the number of following bytes: */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004179 --n;
4180 /* Check if the follow up chars are all valid continuation bytes */
4181 if (n >= 1) {
4182 const unsigned char *cont;
4183 if ((p + n) >= end) {
4184 if (consumed == 0)
4185 /* incomplete data, non-incremental decoding */
4186 err = 1;
4187 break;
4188 }
4189 for (cont = p + 1; cont < (p + n); ++cont) {
4190 if ((*cont & 0xc0) != 0x80) {
4191 err = 1;
4192 break;
4193 }
4194 }
4195 p += n;
4196 }
4197 else
4198 err = 1;
4199 max_char = new_max;
4200 }
4201 }
4202
4203 if (unicode_size)
4204 *unicode_size = char_count;
4205 if (has_errors)
4206 *has_errors = err;
4207 return max_char;
4208}
4209
4210/* Similar to PyUnicode_WRITE but can also write into wstr field
4211 of the legacy unicode representation */
4212#define WRITE_FLEXIBLE_OR_WSTR(kind, buf, index, value) \
4213 do { \
4214 const int k_ = (kind); \
4215 if (k_ == PyUnicode_WCHAR_KIND) \
4216 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
4217 else if (k_ == PyUnicode_1BYTE_KIND) \
4218 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
4219 else if (k_ == PyUnicode_2BYTE_KIND) \
4220 ((Py_UCS2 *)(buf))[(index)] = (Py_UCS2)(value); \
4221 else \
4222 ((Py_UCS4 *)(buf))[(index)] = (Py_UCS4)(value); \
4223 } while (0)
4224
Alexander Belopolsky40018472011-02-26 01:02:56 +00004225PyObject *
4226PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004227 Py_ssize_t size,
4228 const char *errors,
4229 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004230{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004231 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004232 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004233 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004234 Py_ssize_t startinpos;
4235 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004236 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004237 PyUnicodeObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004238 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004239 PyObject *errorHandler = NULL;
4240 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004241 Py_UCS4 maxchar = 0;
4242 Py_ssize_t unicode_size;
4243 Py_ssize_t i;
4244 int kind;
4245 void *data;
4246 int has_errors;
4247 Py_UNICODE *error_outptr;
4248#if SIZEOF_WCHAR_T == 2
4249 Py_ssize_t wchar_offset = 0;
4250#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004251
Walter Dörwald69652032004-09-07 20:24:22 +00004252 if (size == 0) {
4253 if (consumed)
4254 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004255 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004256 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004257 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
4258 consumed, &has_errors);
4259 if (has_errors) {
4260 unicode = _PyUnicode_New(size);
4261 if (!unicode)
4262 return NULL;
4263 kind = PyUnicode_WCHAR_KIND;
4264 data = PyUnicode_AS_UNICODE(unicode);
4265 assert(data != NULL);
4266 }
4267 else {
4268 unicode = (PyUnicodeObject *)PyUnicode_New(unicode_size, maxchar);
4269 if (!unicode)
4270 return NULL;
4271 /* When the string is ASCII only, just use memcpy and return.
4272 unicode_size may be != size if there is an incomplete UTF-8
4273 sequence at the end of the ASCII block. */
4274 if (maxchar < 128 && size == unicode_size) {
4275 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4276 return (PyObject *)unicode;
4277 }
4278 kind = PyUnicode_KIND(unicode);
4279 data = PyUnicode_DATA(unicode);
4280 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004281 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004282 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004283 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004284 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004285
4286 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004287 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004288
4289 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004290 /* Fast path for runs of ASCII characters. Given that common UTF-8
4291 input will consist of an overwhelming majority of ASCII
4292 characters, we try to optimize for this case by checking
4293 as many characters as a C 'long' can contain.
4294 First, check if we can do an aligned read, as most CPUs have
4295 a penalty for unaligned reads.
4296 */
4297 if (!((size_t) s & LONG_PTR_MASK)) {
4298 /* Help register allocation */
4299 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004300 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004301 while (_s < aligned_end) {
4302 /* Read a whole long at a time (either 4 or 8 bytes),
4303 and do a fast unrolled copy if it only contains ASCII
4304 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004305 unsigned long value = *(unsigned long *) _s;
4306 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004307 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004308 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+0, _s[0]);
4309 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+1, _s[1]);
4310 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+2, _s[2]);
4311 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004312#if (SIZEOF_LONG == 8)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004313 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+4, _s[4]);
4314 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+5, _s[5]);
4315 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+6, _s[6]);
4316 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004317#endif
4318 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004319 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004320 }
4321 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004322 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004323 if (s == e)
4324 break;
4325 ch = (unsigned char)*s;
4326 }
4327 }
4328
4329 if (ch < 0x80) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004330 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004331 s++;
4332 continue;
4333 }
4334
4335 n = utf8_code_length[ch];
4336
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004337 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004338 if (consumed)
4339 break;
4340 else {
4341 errmsg = "unexpected end of data";
4342 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004343 endinpos = startinpos+1;
4344 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4345 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004346 goto utf8Error;
4347 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004348 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004349
4350 switch (n) {
4351
4352 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004353 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004354 startinpos = s-starts;
4355 endinpos = startinpos+1;
4356 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004357
4358 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004359 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004360 startinpos = s-starts;
4361 endinpos = startinpos+1;
4362 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004363
4364 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004365 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004366 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004367 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004368 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004369 goto utf8Error;
4370 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004371 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004372 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004373 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004374 break;
4375
4376 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004377 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4378 will result in surrogates in range d800-dfff. Surrogates are
4379 not valid UTF-8 so they are rejected.
4380 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4381 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004382 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004383 (s[2] & 0xc0) != 0x80 ||
4384 ((unsigned char)s[0] == 0xE0 &&
4385 (unsigned char)s[1] < 0xA0) ||
4386 ((unsigned char)s[0] == 0xED &&
4387 (unsigned char)s[1] > 0x9F)) {
4388 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004389 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004390 endinpos = startinpos + 1;
4391
4392 /* if s[1] first two bits are 1 and 0, then the invalid
4393 continuation byte is s[2], so increment endinpos by 1,
4394 if not, s[1] is invalid and endinpos doesn't need to
4395 be incremented. */
4396 if ((s[1] & 0xC0) == 0x80)
4397 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004398 goto utf8Error;
4399 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004400 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004401 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004402 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004403 break;
4404
4405 case 4:
4406 if ((s[1] & 0xc0) != 0x80 ||
4407 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004408 (s[3] & 0xc0) != 0x80 ||
4409 ((unsigned char)s[0] == 0xF0 &&
4410 (unsigned char)s[1] < 0x90) ||
4411 ((unsigned char)s[0] == 0xF4 &&
4412 (unsigned char)s[1] > 0x8F)) {
4413 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004414 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004415 endinpos = startinpos + 1;
4416 if ((s[1] & 0xC0) == 0x80) {
4417 endinpos++;
4418 if ((s[2] & 0xC0) == 0x80)
4419 endinpos++;
4420 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004421 goto utf8Error;
4422 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004423 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004424 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4425 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4426
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004427 /* If the string is flexible or we have native UCS-4, write
4428 directly.. */
4429 if (sizeof(Py_UNICODE) > 2 || kind != PyUnicode_WCHAR_KIND)
4430 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Tim Petersced69f82003-09-16 20:30:58 +00004431
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004432 else {
4433 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00004434
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004435 /* translate from 10000..10FFFF to 0..FFFF */
4436 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00004437
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004438 /* high surrogate = top 10 bits added to D800 */
4439 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4440 (Py_UNICODE)(0xD800 + (ch >> 10)));
4441
4442 /* low surrogate = bottom 10 bits added to DC00 */
4443 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4444 (Py_UNICODE)(0xDC00 + (ch & 0x03FF)));
4445 }
4446#if SIZEOF_WCHAR_T == 2
4447 wchar_offset++;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004448#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004449 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004450 }
4451 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004452 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004453
Benjamin Peterson29060642009-01-31 22:14:21 +00004454 utf8Error:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004455 /* If this is not yet a resizable string, make it one.. */
4456 if (kind != PyUnicode_WCHAR_KIND) {
4457 const Py_UNICODE *u;
4458 PyUnicodeObject *new_unicode = _PyUnicode_New(size);
4459 if (!new_unicode)
4460 goto onError;
4461 u = PyUnicode_AsUnicode((PyObject *)unicode);
4462 if (!u)
4463 goto onError;
4464#if SIZEOF_WCHAR_T == 2
4465 i += wchar_offset;
4466#endif
4467 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(new_unicode), u, i);
4468 Py_DECREF(unicode);
4469 unicode = new_unicode;
4470 kind = 0;
4471 data = PyUnicode_AS_UNICODE(new_unicode);
4472 assert(data != NULL);
4473 }
4474 error_outptr = PyUnicode_AS_UNICODE(unicode) + i;
Benjamin Peterson29060642009-01-31 22:14:21 +00004475 if (unicode_decode_call_errorhandler(
4476 errors, &errorHandler,
4477 "utf8", errmsg,
4478 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004479 &unicode, &i, &error_outptr))
Benjamin Peterson29060642009-01-31 22:14:21 +00004480 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004481 /* Update data because unicode_decode_call_errorhandler might have
4482 re-created or resized the unicode object. */
4483 data = PyUnicode_AS_UNICODE(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004484 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004485 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004486 /* Ensure the unicode_size calculation above was correct: */
4487 assert(kind == PyUnicode_WCHAR_KIND || i == unicode_size);
4488
Walter Dörwald69652032004-09-07 20:24:22 +00004489 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004490 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004491
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004492 /* Adjust length and ready string when it contained errors and
4493 is of the old resizable kind. */
4494 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004495 if (PyUnicode_Resize((PyObject**)&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004496 goto onError;
4497 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004498
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004499 Py_XDECREF(errorHandler);
4500 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004501#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004502 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004503 Py_DECREF(unicode);
4504 return NULL;
4505 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004506#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004507 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00004508 return (PyObject *)unicode;
4509
Benjamin Peterson29060642009-01-31 22:14:21 +00004510 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004511 Py_XDECREF(errorHandler);
4512 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004513 Py_DECREF(unicode);
4514 return NULL;
4515}
4516
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004517#undef WRITE_FLEXIBLE_OR_WSTR
Antoine Pitrouab868312009-01-10 15:40:25 +00004518
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004519#ifdef __APPLE__
4520
4521/* Simplified UTF-8 decoder using surrogateescape error handler,
4522 used to decode the command line arguments on Mac OS X. */
4523
4524wchar_t*
4525_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4526{
4527 int n;
4528 const char *e;
4529 wchar_t *unicode, *p;
4530
4531 /* Note: size will always be longer than the resulting Unicode
4532 character count */
4533 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4534 PyErr_NoMemory();
4535 return NULL;
4536 }
4537 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4538 if (!unicode)
4539 return NULL;
4540
4541 /* Unpack UTF-8 encoded data */
4542 p = unicode;
4543 e = s + size;
4544 while (s < e) {
4545 Py_UCS4 ch = (unsigned char)*s;
4546
4547 if (ch < 0x80) {
4548 *p++ = (wchar_t)ch;
4549 s++;
4550 continue;
4551 }
4552
4553 n = utf8_code_length[ch];
4554 if (s + n > e) {
4555 goto surrogateescape;
4556 }
4557
4558 switch (n) {
4559 case 0:
4560 case 1:
4561 goto surrogateescape;
4562
4563 case 2:
4564 if ((s[1] & 0xc0) != 0x80)
4565 goto surrogateescape;
4566 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4567 assert ((ch > 0x007F) && (ch <= 0x07FF));
4568 *p++ = (wchar_t)ch;
4569 break;
4570
4571 case 3:
4572 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4573 will result in surrogates in range d800-dfff. Surrogates are
4574 not valid UTF-8 so they are rejected.
4575 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4576 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4577 if ((s[1] & 0xc0) != 0x80 ||
4578 (s[2] & 0xc0) != 0x80 ||
4579 ((unsigned char)s[0] == 0xE0 &&
4580 (unsigned char)s[1] < 0xA0) ||
4581 ((unsigned char)s[0] == 0xED &&
4582 (unsigned char)s[1] > 0x9F)) {
4583
4584 goto surrogateescape;
4585 }
4586 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4587 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004588 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004589 break;
4590
4591 case 4:
4592 if ((s[1] & 0xc0) != 0x80 ||
4593 (s[2] & 0xc0) != 0x80 ||
4594 (s[3] & 0xc0) != 0x80 ||
4595 ((unsigned char)s[0] == 0xF0 &&
4596 (unsigned char)s[1] < 0x90) ||
4597 ((unsigned char)s[0] == 0xF4 &&
4598 (unsigned char)s[1] > 0x8F)) {
4599 goto surrogateescape;
4600 }
4601 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4602 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4603 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4604
4605#if SIZEOF_WCHAR_T == 4
4606 *p++ = (wchar_t)ch;
4607#else
4608 /* compute and append the two surrogates: */
4609
4610 /* translate from 10000..10FFFF to 0..FFFF */
4611 ch -= 0x10000;
4612
4613 /* high surrogate = top 10 bits added to D800 */
4614 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4615
4616 /* low surrogate = bottom 10 bits added to DC00 */
4617 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4618#endif
4619 break;
4620 }
4621 s += n;
4622 continue;
4623
4624 surrogateescape:
4625 *p++ = 0xDC00 + ch;
4626 s++;
4627 }
4628 *p = L'\0';
4629 return unicode;
4630}
4631
4632#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004633
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004634/* Primary internal function which creates utf8 encoded bytes objects.
4635
4636 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004637 and allocate exactly as much space needed at the end. Else allocate the
4638 maximum possible needed (4 result bytes per Unicode character), and return
4639 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004640*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004641PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004642_PyUnicode_AsUTF8String(PyObject *obj, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004643{
Tim Peters602f7402002-04-27 18:03:26 +00004644#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004645
Guido van Rossum98297ee2007-11-06 21:34:58 +00004646 Py_ssize_t i; /* index into s of next input byte */
4647 PyObject *result; /* result string object */
4648 char *p; /* next free byte in output buffer */
4649 Py_ssize_t nallocated; /* number of result bytes allocated */
4650 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004651 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004652 PyObject *errorHandler = NULL;
4653 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004654 int kind;
4655 void *data;
4656 Py_ssize_t size;
4657 PyUnicodeObject *unicode = (PyUnicodeObject *)obj;
4658#if SIZEOF_WCHAR_T == 2
4659 Py_ssize_t wchar_offset = 0;
4660#endif
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004661
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004662 if (!PyUnicode_Check(unicode)) {
4663 PyErr_BadArgument();
4664 return NULL;
4665 }
4666
4667 if (PyUnicode_READY(unicode) == -1)
4668 return NULL;
4669
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004670 if (PyUnicode_UTF8(unicode))
4671 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4672 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004673
4674 kind = PyUnicode_KIND(unicode);
4675 data = PyUnicode_DATA(unicode);
4676 size = PyUnicode_GET_LENGTH(unicode);
4677
Tim Peters602f7402002-04-27 18:03:26 +00004678 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004679
Tim Peters602f7402002-04-27 18:03:26 +00004680 if (size <= MAX_SHORT_UNICHARS) {
4681 /* Write into the stack buffer; nallocated can't overflow.
4682 * At the end, we'll allocate exactly as much heap space as it
4683 * turns out we need.
4684 */
4685 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004686 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004687 p = stackbuf;
4688 }
4689 else {
4690 /* Overallocate on the heap, and give the excess back at the end. */
4691 nallocated = size * 4;
4692 if (nallocated / 4 != size) /* overflow! */
4693 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004694 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004695 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004696 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004697 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004698 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004699
Tim Peters602f7402002-04-27 18:03:26 +00004700 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004701 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004702
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004703 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004704 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004705 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004706
Guido van Rossumd57fd912000-03-10 22:53:23 +00004707 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004708 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004709 *p++ = (char)(0xc0 | (ch >> 6));
4710 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004711 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004712 Py_ssize_t newpos;
4713 PyObject *rep;
4714 Py_ssize_t repsize, k, startpos;
4715 startpos = i-1;
4716#if SIZEOF_WCHAR_T == 2
4717 startpos += wchar_offset;
Victor Stinner445a6232010-04-22 20:01:57 +00004718#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004719 rep = unicode_encode_call_errorhandler(
4720 errors, &errorHandler, "utf-8", "surrogates not allowed",
4721 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
4722 &exc, startpos, startpos+1, &newpos);
4723 if (!rep)
4724 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004725
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004726 if (PyBytes_Check(rep))
4727 repsize = PyBytes_GET_SIZE(rep);
4728 else
4729 repsize = PyUnicode_GET_SIZE(rep);
4730
4731 if (repsize > 4) {
4732 Py_ssize_t offset;
4733
4734 if (result == NULL)
4735 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004736 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004737 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004738
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004739 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4740 /* integer overflow */
4741 PyErr_NoMemory();
4742 goto error;
4743 }
4744 nallocated += repsize - 4;
4745 if (result != NULL) {
4746 if (_PyBytes_Resize(&result, nallocated) < 0)
4747 goto error;
4748 } else {
4749 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004750 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004751 goto error;
4752 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4753 }
4754 p = PyBytes_AS_STRING(result) + offset;
4755 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004756
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004757 if (PyBytes_Check(rep)) {
4758 char *prep = PyBytes_AS_STRING(rep);
4759 for(k = repsize; k > 0; k--)
4760 *p++ = *prep++;
4761 } else /* rep is unicode */ {
4762 const Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
4763 Py_UNICODE c;
4764
4765 for(k=0; k<repsize; k++) {
4766 c = prep[k];
4767 if (0x80 <= c) {
4768 raise_encode_exception(&exc, "utf-8",
4769 PyUnicode_AS_UNICODE(unicode),
4770 size, i-1, i,
4771 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004772 goto error;
4773 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004774 *p++ = (char)prep[k];
Victor Stinner31be90b2010-04-22 19:38:16 +00004775 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004776 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004777 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004778 } else if (ch < 0x10000) {
4779 *p++ = (char)(0xe0 | (ch >> 12));
4780 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4781 *p++ = (char)(0x80 | (ch & 0x3f));
4782 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004783 /* Encode UCS4 Unicode ordinals */
4784 *p++ = (char)(0xf0 | (ch >> 18));
4785 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4786 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4787 *p++ = (char)(0x80 | (ch & 0x3f));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004788#if SIZEOF_WCHAR_T == 2
4789 wchar_offset++;
4790#endif
Tim Peters602f7402002-04-27 18:03:26 +00004791 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004792 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004793
Guido van Rossum98297ee2007-11-06 21:34:58 +00004794 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004795 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004796 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004797 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004798 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004799 }
4800 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004801 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004802 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004803 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004804 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004805 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004806
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004807 Py_XDECREF(errorHandler);
4808 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004809 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004810 error:
4811 Py_XDECREF(errorHandler);
4812 Py_XDECREF(exc);
4813 Py_XDECREF(result);
4814 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004815
Tim Peters602f7402002-04-27 18:03:26 +00004816#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004817}
4818
Alexander Belopolsky40018472011-02-26 01:02:56 +00004819PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004820PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4821 Py_ssize_t size,
4822 const char *errors)
4823{
4824 PyObject *v, *unicode;
4825
4826 unicode = PyUnicode_FromUnicode(s, size);
4827 if (unicode == NULL)
4828 return NULL;
4829 v = _PyUnicode_AsUTF8String(unicode, errors);
4830 Py_DECREF(unicode);
4831 return v;
4832}
4833
4834PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004835PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004836{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004837 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004838}
4839
Walter Dörwald41980ca2007-08-16 21:55:45 +00004840/* --- UTF-32 Codec ------------------------------------------------------- */
4841
4842PyObject *
4843PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004844 Py_ssize_t size,
4845 const char *errors,
4846 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004847{
4848 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4849}
4850
4851PyObject *
4852PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004853 Py_ssize_t size,
4854 const char *errors,
4855 int *byteorder,
4856 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004857{
4858 const char *starts = s;
4859 Py_ssize_t startinpos;
4860 Py_ssize_t endinpos;
4861 Py_ssize_t outpos;
4862 PyUnicodeObject *unicode;
4863 Py_UNICODE *p;
4864#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004865 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004866 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004867#else
4868 const int pairs = 0;
4869#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00004870 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004871 int bo = 0; /* assume native ordering by default */
4872 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004873 /* Offsets from q for retrieving bytes in the right order. */
4874#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4875 int iorder[] = {0, 1, 2, 3};
4876#else
4877 int iorder[] = {3, 2, 1, 0};
4878#endif
4879 PyObject *errorHandler = NULL;
4880 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004881
Walter Dörwald41980ca2007-08-16 21:55:45 +00004882 q = (unsigned char *)s;
4883 e = q + size;
4884
4885 if (byteorder)
4886 bo = *byteorder;
4887
4888 /* Check for BOM marks (U+FEFF) in the input and adjust current
4889 byte order setting accordingly. In native mode, the leading BOM
4890 mark is skipped, in all other modes, it is copied to the output
4891 stream as-is (giving a ZWNBSP character). */
4892 if (bo == 0) {
4893 if (size >= 4) {
4894 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004895 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004896#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004897 if (bom == 0x0000FEFF) {
4898 q += 4;
4899 bo = -1;
4900 }
4901 else if (bom == 0xFFFE0000) {
4902 q += 4;
4903 bo = 1;
4904 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004905#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004906 if (bom == 0x0000FEFF) {
4907 q += 4;
4908 bo = 1;
4909 }
4910 else if (bom == 0xFFFE0000) {
4911 q += 4;
4912 bo = -1;
4913 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004914#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004915 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004916 }
4917
4918 if (bo == -1) {
4919 /* force LE */
4920 iorder[0] = 0;
4921 iorder[1] = 1;
4922 iorder[2] = 2;
4923 iorder[3] = 3;
4924 }
4925 else if (bo == 1) {
4926 /* force BE */
4927 iorder[0] = 3;
4928 iorder[1] = 2;
4929 iorder[2] = 1;
4930 iorder[3] = 0;
4931 }
4932
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004933 /* On narrow builds we split characters outside the BMP into two
4934 codepoints => count how much extra space we need. */
4935#ifndef Py_UNICODE_WIDE
4936 for (qq = q; qq < e; qq += 4)
4937 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
4938 pairs++;
4939#endif
4940
4941 /* This might be one to much, because of a BOM */
4942 unicode = _PyUnicode_New((size+3)/4+pairs);
4943 if (!unicode)
4944 return NULL;
4945 if (size == 0)
4946 return (PyObject *)unicode;
4947
4948 /* Unpack UTF-32 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004949 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004950
Walter Dörwald41980ca2007-08-16 21:55:45 +00004951 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004952 Py_UCS4 ch;
4953 /* remaining bytes at the end? (size should be divisible by 4) */
4954 if (e-q<4) {
4955 if (consumed)
4956 break;
4957 errmsg = "truncated data";
4958 startinpos = ((const char *)q)-starts;
4959 endinpos = ((const char *)e)-starts;
4960 goto utf32Error;
4961 /* The remaining input chars are ignored if the callback
4962 chooses to skip the input */
4963 }
4964 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
4965 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004966
Benjamin Peterson29060642009-01-31 22:14:21 +00004967 if (ch >= 0x110000)
4968 {
4969 errmsg = "codepoint not in range(0x110000)";
4970 startinpos = ((const char *)q)-starts;
4971 endinpos = startinpos+4;
4972 goto utf32Error;
4973 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004974#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004975 if (ch >= 0x10000)
4976 {
4977 *p++ = 0xD800 | ((ch-0x10000) >> 10);
4978 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
4979 }
4980 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00004981#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004982 *p++ = ch;
4983 q += 4;
4984 continue;
4985 utf32Error:
4986 outpos = p-PyUnicode_AS_UNICODE(unicode);
4987 if (unicode_decode_call_errorhandler(
4988 errors, &errorHandler,
4989 "utf32", errmsg,
4990 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
4991 &unicode, &outpos, &p))
4992 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004993 }
4994
4995 if (byteorder)
4996 *byteorder = bo;
4997
4998 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004999 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005000
5001 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02005002 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005003 goto onError;
5004
5005 Py_XDECREF(errorHandler);
5006 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005007#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005008 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005009 Py_DECREF(unicode);
5010 return NULL;
5011 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005012#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005013 assert(_PyUnicode_CheckConsistency(unicode, 1));
Walter Dörwald41980ca2007-08-16 21:55:45 +00005014 return (PyObject *)unicode;
5015
Benjamin Peterson29060642009-01-31 22:14:21 +00005016 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005017 Py_DECREF(unicode);
5018 Py_XDECREF(errorHandler);
5019 Py_XDECREF(exc);
5020 return NULL;
5021}
5022
5023PyObject *
5024PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005025 Py_ssize_t size,
5026 const char *errors,
5027 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005028{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005029 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005030 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005031 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005032#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005033 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005034#else
5035 const int pairs = 0;
5036#endif
5037 /* Offsets from p for storing byte pairs in the right order. */
5038#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5039 int iorder[] = {0, 1, 2, 3};
5040#else
5041 int iorder[] = {3, 2, 1, 0};
5042#endif
5043
Benjamin Peterson29060642009-01-31 22:14:21 +00005044#define STORECHAR(CH) \
5045 do { \
5046 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5047 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5048 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5049 p[iorder[0]] = (CH) & 0xff; \
5050 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005051 } while(0)
5052
5053 /* In narrow builds we can output surrogate pairs as one codepoint,
5054 so we need less space. */
5055#ifndef Py_UNICODE_WIDE
5056 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005057 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
5058 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
5059 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005060#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005061 nsize = (size - pairs + (byteorder == 0));
5062 bytesize = nsize * 4;
5063 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005064 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005065 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005066 if (v == NULL)
5067 return NULL;
5068
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005069 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005070 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005071 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005072 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005073 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005074
5075 if (byteorder == -1) {
5076 /* force LE */
5077 iorder[0] = 0;
5078 iorder[1] = 1;
5079 iorder[2] = 2;
5080 iorder[3] = 3;
5081 }
5082 else if (byteorder == 1) {
5083 /* force BE */
5084 iorder[0] = 3;
5085 iorder[1] = 2;
5086 iorder[2] = 1;
5087 iorder[3] = 0;
5088 }
5089
5090 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005091 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005092#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005093 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
5094 Py_UCS4 ch2 = *s;
5095 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
5096 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
5097 s++;
5098 size--;
5099 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005100 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005101#endif
5102 STORECHAR(ch);
5103 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005104
5105 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005106 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005107#undef STORECHAR
5108}
5109
Alexander Belopolsky40018472011-02-26 01:02:56 +00005110PyObject *
5111PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005112{
5113 if (!PyUnicode_Check(unicode)) {
5114 PyErr_BadArgument();
5115 return NULL;
5116 }
5117 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005118 PyUnicode_GET_SIZE(unicode),
5119 NULL,
5120 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005121}
5122
Guido van Rossumd57fd912000-03-10 22:53:23 +00005123/* --- UTF-16 Codec ------------------------------------------------------- */
5124
Tim Peters772747b2001-08-09 22:21:55 +00005125PyObject *
5126PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005127 Py_ssize_t size,
5128 const char *errors,
5129 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005130{
Walter Dörwald69652032004-09-07 20:24:22 +00005131 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5132}
5133
Antoine Pitrouab868312009-01-10 15:40:25 +00005134/* Two masks for fast checking of whether a C 'long' may contain
5135 UTF16-encoded surrogate characters. This is an efficient heuristic,
5136 assuming that non-surrogate characters with a code point >= 0x8000 are
5137 rare in most input.
5138 FAST_CHAR_MASK is used when the input is in native byte ordering,
5139 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005140*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005141#if (SIZEOF_LONG == 8)
5142# define FAST_CHAR_MASK 0x8000800080008000L
5143# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5144#elif (SIZEOF_LONG == 4)
5145# define FAST_CHAR_MASK 0x80008000L
5146# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5147#else
5148# error C 'long' size should be either 4 or 8!
5149#endif
5150
Walter Dörwald69652032004-09-07 20:24:22 +00005151PyObject *
5152PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005153 Py_ssize_t size,
5154 const char *errors,
5155 int *byteorder,
5156 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005157{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005158 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005159 Py_ssize_t startinpos;
5160 Py_ssize_t endinpos;
5161 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005162 PyUnicodeObject *unicode;
5163 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00005164 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005165 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005166 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005167 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005168 /* Offsets from q for retrieving byte pairs in the right order. */
5169#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5170 int ihi = 1, ilo = 0;
5171#else
5172 int ihi = 0, ilo = 1;
5173#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005174 PyObject *errorHandler = NULL;
5175 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005176
5177 /* Note: size will always be longer than the resulting Unicode
5178 character count */
5179 unicode = _PyUnicode_New(size);
5180 if (!unicode)
5181 return NULL;
5182 if (size == 0)
5183 return (PyObject *)unicode;
5184
5185 /* Unpack UTF-16 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005186 p = PyUnicode_AS_UNICODE(unicode);
Tim Peters772747b2001-08-09 22:21:55 +00005187 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005188 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005189
5190 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005191 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005192
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005193 /* Check for BOM marks (U+FEFF) in the input and adjust current
5194 byte order setting accordingly. In native mode, the leading BOM
5195 mark is skipped, in all other modes, it is copied to the output
5196 stream as-is (giving a ZWNBSP character). */
5197 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005198 if (size >= 2) {
5199 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005200#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005201 if (bom == 0xFEFF) {
5202 q += 2;
5203 bo = -1;
5204 }
5205 else if (bom == 0xFFFE) {
5206 q += 2;
5207 bo = 1;
5208 }
Tim Petersced69f82003-09-16 20:30:58 +00005209#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005210 if (bom == 0xFEFF) {
5211 q += 2;
5212 bo = 1;
5213 }
5214 else if (bom == 0xFFFE) {
5215 q += 2;
5216 bo = -1;
5217 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005218#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005219 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005220 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005221
Tim Peters772747b2001-08-09 22:21:55 +00005222 if (bo == -1) {
5223 /* force LE */
5224 ihi = 1;
5225 ilo = 0;
5226 }
5227 else if (bo == 1) {
5228 /* force BE */
5229 ihi = 0;
5230 ilo = 1;
5231 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005232#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5233 native_ordering = ilo < ihi;
5234#else
5235 native_ordering = ilo > ihi;
5236#endif
Tim Peters772747b2001-08-09 22:21:55 +00005237
Antoine Pitrouab868312009-01-10 15:40:25 +00005238 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005239 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005240 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005241 /* First check for possible aligned read of a C 'long'. Unaligned
5242 reads are more expensive, better to defer to another iteration. */
5243 if (!((size_t) q & LONG_PTR_MASK)) {
5244 /* Fast path for runs of non-surrogate chars. */
5245 register const unsigned char *_q = q;
5246 Py_UNICODE *_p = p;
5247 if (native_ordering) {
5248 /* Native ordering is simple: as long as the input cannot
5249 possibly contain a surrogate char, do an unrolled copy
5250 of several 16-bit code points to the target object.
5251 The non-surrogate check is done on several input bytes
5252 at a time (as many as a C 'long' can contain). */
5253 while (_q < aligned_end) {
5254 unsigned long data = * (unsigned long *) _q;
5255 if (data & FAST_CHAR_MASK)
5256 break;
5257 _p[0] = ((unsigned short *) _q)[0];
5258 _p[1] = ((unsigned short *) _q)[1];
5259#if (SIZEOF_LONG == 8)
5260 _p[2] = ((unsigned short *) _q)[2];
5261 _p[3] = ((unsigned short *) _q)[3];
5262#endif
5263 _q += SIZEOF_LONG;
5264 _p += SIZEOF_LONG / 2;
5265 }
5266 }
5267 else {
5268 /* Byteswapped ordering is similar, but we must decompose
5269 the copy bytewise, and take care of zero'ing out the
5270 upper bytes if the target object is in 32-bit units
5271 (that is, in UCS-4 builds). */
5272 while (_q < aligned_end) {
5273 unsigned long data = * (unsigned long *) _q;
5274 if (data & SWAPPED_FAST_CHAR_MASK)
5275 break;
5276 /* Zero upper bytes in UCS-4 builds */
5277#if (Py_UNICODE_SIZE > 2)
5278 _p[0] = 0;
5279 _p[1] = 0;
5280#if (SIZEOF_LONG == 8)
5281 _p[2] = 0;
5282 _p[3] = 0;
5283#endif
5284#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005285 /* Issue #4916; UCS-4 builds on big endian machines must
5286 fill the two last bytes of each 4-byte unit. */
5287#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
5288# define OFF 2
5289#else
5290# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00005291#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005292 ((unsigned char *) _p)[OFF + 1] = _q[0];
5293 ((unsigned char *) _p)[OFF + 0] = _q[1];
5294 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
5295 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
5296#if (SIZEOF_LONG == 8)
5297 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
5298 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
5299 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
5300 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
5301#endif
5302#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00005303 _q += SIZEOF_LONG;
5304 _p += SIZEOF_LONG / 2;
5305 }
5306 }
5307 p = _p;
5308 q = _q;
5309 if (q >= e)
5310 break;
5311 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005312 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005313
Benjamin Peterson14339b62009-01-31 16:36:08 +00005314 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005315
5316 if (ch < 0xD800 || ch > 0xDFFF) {
5317 *p++ = ch;
5318 continue;
5319 }
5320
5321 /* UTF-16 code pair: */
5322 if (q > e) {
5323 errmsg = "unexpected end of data";
5324 startinpos = (((const char *)q) - 2) - starts;
5325 endinpos = ((const char *)e) + 1 - starts;
5326 goto utf16Error;
5327 }
5328 if (0xD800 <= ch && ch <= 0xDBFF) {
5329 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
5330 q += 2;
5331 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00005332#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005333 *p++ = ch;
5334 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005335#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005336 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005337#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005338 continue;
5339 }
5340 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005341 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005342 startinpos = (((const char *)q)-4)-starts;
5343 endinpos = startinpos+2;
5344 goto utf16Error;
5345 }
5346
Benjamin Peterson14339b62009-01-31 16:36:08 +00005347 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005348 errmsg = "illegal encoding";
5349 startinpos = (((const char *)q)-2)-starts;
5350 endinpos = startinpos+2;
5351 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005352
Benjamin Peterson29060642009-01-31 22:14:21 +00005353 utf16Error:
5354 outpos = p - PyUnicode_AS_UNICODE(unicode);
5355 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005356 errors,
5357 &errorHandler,
5358 "utf16", errmsg,
5359 &starts,
5360 (const char **)&e,
5361 &startinpos,
5362 &endinpos,
5363 &exc,
5364 (const char **)&q,
5365 &unicode,
5366 &outpos,
5367 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00005368 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005369 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005370 /* remaining byte at the end? (size should be even) */
5371 if (e == q) {
5372 if (!consumed) {
5373 errmsg = "truncated data";
5374 startinpos = ((const char *)q) - starts;
5375 endinpos = ((const char *)e) + 1 - starts;
5376 outpos = p - PyUnicode_AS_UNICODE(unicode);
5377 if (unicode_decode_call_errorhandler(
5378 errors,
5379 &errorHandler,
5380 "utf16", errmsg,
5381 &starts,
5382 (const char **)&e,
5383 &startinpos,
5384 &endinpos,
5385 &exc,
5386 (const char **)&q,
5387 &unicode,
5388 &outpos,
5389 &p))
5390 goto onError;
5391 /* The remaining input chars are ignored if the callback
5392 chooses to skip the input */
5393 }
5394 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005395
5396 if (byteorder)
5397 *byteorder = bo;
5398
Walter Dörwald69652032004-09-07 20:24:22 +00005399 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005400 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005401
Guido van Rossumd57fd912000-03-10 22:53:23 +00005402 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02005403 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005404 goto onError;
5405
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005406 Py_XDECREF(errorHandler);
5407 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005408#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005409 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005410 Py_DECREF(unicode);
5411 return NULL;
5412 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005413#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005414 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00005415 return (PyObject *)unicode;
5416
Benjamin Peterson29060642009-01-31 22:14:21 +00005417 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005418 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005419 Py_XDECREF(errorHandler);
5420 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005421 return NULL;
5422}
5423
Antoine Pitrouab868312009-01-10 15:40:25 +00005424#undef FAST_CHAR_MASK
5425#undef SWAPPED_FAST_CHAR_MASK
5426
Tim Peters772747b2001-08-09 22:21:55 +00005427PyObject *
5428PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005429 Py_ssize_t size,
5430 const char *errors,
5431 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005432{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005433 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005434 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005435 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005436#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005437 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005438#else
5439 const int pairs = 0;
5440#endif
Tim Peters772747b2001-08-09 22:21:55 +00005441 /* Offsets from p for storing byte pairs in the right order. */
5442#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5443 int ihi = 1, ilo = 0;
5444#else
5445 int ihi = 0, ilo = 1;
5446#endif
5447
Benjamin Peterson29060642009-01-31 22:14:21 +00005448#define STORECHAR(CH) \
5449 do { \
5450 p[ihi] = ((CH) >> 8) & 0xff; \
5451 p[ilo] = (CH) & 0xff; \
5452 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005453 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005454
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005455#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005456 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005457 if (s[i] >= 0x10000)
5458 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005459#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005460 /* 2 * (size + pairs + (byteorder == 0)) */
5461 if (size > PY_SSIZE_T_MAX ||
5462 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005463 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005464 nsize = size + pairs + (byteorder == 0);
5465 bytesize = nsize * 2;
5466 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005467 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005468 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005469 if (v == NULL)
5470 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005471
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005472 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005473 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005474 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005475 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005476 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005477
5478 if (byteorder == -1) {
5479 /* force LE */
5480 ihi = 1;
5481 ilo = 0;
5482 }
5483 else if (byteorder == 1) {
5484 /* force BE */
5485 ihi = 0;
5486 ilo = 1;
5487 }
5488
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005489 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005490 Py_UNICODE ch = *s++;
5491 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005492#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005493 if (ch >= 0x10000) {
5494 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5495 ch = 0xD800 | ((ch-0x10000) >> 10);
5496 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005497#endif
Tim Peters772747b2001-08-09 22:21:55 +00005498 STORECHAR(ch);
5499 if (ch2)
5500 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005501 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005502
5503 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005504 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005505#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005506}
5507
Alexander Belopolsky40018472011-02-26 01:02:56 +00005508PyObject *
5509PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005510{
5511 if (!PyUnicode_Check(unicode)) {
5512 PyErr_BadArgument();
5513 return NULL;
5514 }
5515 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005516 PyUnicode_GET_SIZE(unicode),
5517 NULL,
5518 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005519}
5520
5521/* --- Unicode Escape Codec ----------------------------------------------- */
5522
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005523/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5524 if all the escapes in the string make it still a valid ASCII string.
5525 Returns -1 if any escapes were found which cause the string to
5526 pop out of ASCII range. Otherwise returns the length of the
5527 required buffer to hold the string.
5528 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005529static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005530length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5531{
5532 const unsigned char *p = (const unsigned char *)s;
5533 const unsigned char *end = p + size;
5534 Py_ssize_t length = 0;
5535
5536 if (size < 0)
5537 return -1;
5538
5539 for (; p < end; ++p) {
5540 if (*p > 127) {
5541 /* Non-ASCII */
5542 return -1;
5543 }
5544 else if (*p != '\\') {
5545 /* Normal character */
5546 ++length;
5547 }
5548 else {
5549 /* Backslash-escape, check next char */
5550 ++p;
5551 /* Escape sequence reaches till end of string or
5552 non-ASCII follow-up. */
5553 if (p >= end || *p > 127)
5554 return -1;
5555 switch (*p) {
5556 case '\n':
5557 /* backslash + \n result in zero characters */
5558 break;
5559 case '\\': case '\'': case '\"':
5560 case 'b': case 'f': case 't':
5561 case 'n': case 'r': case 'v': case 'a':
5562 ++length;
5563 break;
5564 case '0': case '1': case '2': case '3':
5565 case '4': case '5': case '6': case '7':
5566 case 'x': case 'u': case 'U': case 'N':
5567 /* these do not guarantee ASCII characters */
5568 return -1;
5569 default:
5570 /* count the backslash + the other character */
5571 length += 2;
5572 }
5573 }
5574 }
5575 return length;
5576}
5577
5578/* Similar to PyUnicode_WRITE but either write into wstr field
5579 or treat string as ASCII. */
5580#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5581 do { \
5582 if ((kind) != PyUnicode_WCHAR_KIND) \
5583 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5584 else \
5585 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5586 } while (0)
5587
5588#define WRITE_WSTR(buf, index, value) \
5589 assert(kind == PyUnicode_WCHAR_KIND), \
5590 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5591
5592
Fredrik Lundh06d12682001-01-24 07:59:11 +00005593static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005594
Alexander Belopolsky40018472011-02-26 01:02:56 +00005595PyObject *
5596PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005597 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005598 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005599{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005600 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005601 Py_ssize_t startinpos;
5602 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005603 int j;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005604 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005605 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005606 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005607 char* message;
5608 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005609 PyObject *errorHandler = NULL;
5610 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005611 Py_ssize_t ascii_length;
5612 Py_ssize_t i;
5613 int kind;
5614 void *data;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005615
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005616 ascii_length = length_of_escaped_ascii_string(s, size);
5617
5618 /* After length_of_escaped_ascii_string() there are two alternatives,
5619 either the string is pure ASCII with named escapes like \n, etc.
5620 and we determined it's exact size (common case)
5621 or it contains \x, \u, ... escape sequences. then we create a
5622 legacy wchar string and resize it at the end of this function. */
5623 if (ascii_length >= 0) {
5624 v = (PyUnicodeObject *)PyUnicode_New(ascii_length, 127);
5625 if (!v)
5626 goto onError;
5627 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
5628 kind = PyUnicode_1BYTE_KIND;
5629 data = PyUnicode_DATA(v);
5630 }
5631 else {
5632 /* Escaped strings will always be longer than the resulting
5633 Unicode string, so we start with size here and then reduce the
5634 length after conversion to the true value.
5635 (but if the error callback returns a long replacement string
5636 we'll have to allocate more space) */
5637 v = _PyUnicode_New(size);
5638 if (!v)
5639 goto onError;
5640 kind = PyUnicode_WCHAR_KIND;
5641 data = PyUnicode_AS_UNICODE(v);
5642 }
5643
Guido van Rossumd57fd912000-03-10 22:53:23 +00005644 if (size == 0)
5645 return (PyObject *)v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005646 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005647 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005648
Guido van Rossumd57fd912000-03-10 22:53:23 +00005649 while (s < end) {
5650 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005651 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005652 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005653
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005654 if (kind == PyUnicode_WCHAR_KIND) {
5655 assert(i < _PyUnicode_WSTR_LENGTH(v));
5656 }
5657 else {
5658 /* The only case in which i == ascii_length is a backslash
5659 followed by a newline. */
5660 assert(i <= ascii_length);
5661 }
5662
Guido van Rossumd57fd912000-03-10 22:53:23 +00005663 /* Non-escape characters are interpreted as Unicode ordinals */
5664 if (*s != '\\') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005665 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char) *s++);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005666 continue;
5667 }
5668
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005669 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005670 /* \ - Escapes */
5671 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005672 c = *s++;
5673 if (s > end)
5674 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005675
5676 if (kind == PyUnicode_WCHAR_KIND) {
5677 assert(i < _PyUnicode_WSTR_LENGTH(v));
5678 }
5679 else {
5680 /* The only case in which i == ascii_length is a backslash
5681 followed by a newline. */
5682 assert(i < ascii_length || (i == ascii_length && c == '\n'));
5683 }
5684
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005685 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005686
Benjamin Peterson29060642009-01-31 22:14:21 +00005687 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005688 case '\n': break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005689 case '\\': WRITE_ASCII_OR_WSTR(kind, data, i++, '\\'); break;
5690 case '\'': WRITE_ASCII_OR_WSTR(kind, data, i++, '\''); break;
5691 case '\"': WRITE_ASCII_OR_WSTR(kind, data, i++, '\"'); break;
5692 case 'b': WRITE_ASCII_OR_WSTR(kind, data, i++, '\b'); break;
5693 /* FF */
5694 case 'f': WRITE_ASCII_OR_WSTR(kind, data, i++, '\014'); break;
5695 case 't': WRITE_ASCII_OR_WSTR(kind, data, i++, '\t'); break;
5696 case 'n': WRITE_ASCII_OR_WSTR(kind, data, i++, '\n'); break;
5697 case 'r': WRITE_ASCII_OR_WSTR(kind, data, i++, '\r'); break;
5698 /* VT */
5699 case 'v': WRITE_ASCII_OR_WSTR(kind, data, i++, '\013'); break;
5700 /* BEL, not classic C */
5701 case 'a': WRITE_ASCII_OR_WSTR(kind, data, i++, '\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005702
Benjamin Peterson29060642009-01-31 22:14:21 +00005703 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005704 case '0': case '1': case '2': case '3':
5705 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005706 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005707 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005708 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005709 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005710 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005711 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005712 WRITE_WSTR(data, i++, x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005713 break;
5714
Benjamin Peterson29060642009-01-31 22:14:21 +00005715 /* hex escapes */
5716 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005717 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005718 digits = 2;
5719 message = "truncated \\xXX escape";
5720 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005721
Benjamin Peterson29060642009-01-31 22:14:21 +00005722 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005723 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005724 digits = 4;
5725 message = "truncated \\uXXXX escape";
5726 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005727
Benjamin Peterson29060642009-01-31 22:14:21 +00005728 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005729 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005730 digits = 8;
5731 message = "truncated \\UXXXXXXXX escape";
5732 hexescape:
5733 chr = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005734 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005735 if (s+digits>end) {
5736 endinpos = size;
5737 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005738 errors, &errorHandler,
5739 "unicodeescape", "end of string in escape sequence",
5740 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005741 &v, &i, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005742 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005743 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005744 goto nextByte;
5745 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005746 for (j = 0; j < digits; ++j) {
5747 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005748 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005749 endinpos = (s+j+1)-starts;
5750 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005751 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005752 errors, &errorHandler,
5753 "unicodeescape", message,
5754 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005755 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005756 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005757 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005758 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005759 }
5760 chr = (chr<<4) & ~0xF;
5761 if (c >= '0' && c <= '9')
5762 chr += c - '0';
5763 else if (c >= 'a' && c <= 'f')
5764 chr += 10 + c - 'a';
5765 else
5766 chr += 10 + c - 'A';
5767 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005768 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005769 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005770 /* _decoding_error will have already written into the
5771 target buffer. */
5772 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005773 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005774 /* when we get here, chr is a 32-bit unicode character */
5775 if (chr <= 0xffff)
5776 /* UCS-2 character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005777 WRITE_WSTR(data, i++, chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005778 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005779 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00005780 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00005781#ifdef Py_UNICODE_WIDE
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005782 WRITE_WSTR(data, i++, chr);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005783#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00005784 chr -= 0x10000L;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005785 WRITE_WSTR(data, i++, 0xD800 + (Py_UNICODE) (chr >> 10));
5786 WRITE_WSTR(data, i++, 0xDC00 + (Py_UNICODE) (chr & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005787#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00005788 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005789 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005790 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005791 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005792 errors, &errorHandler,
5793 "unicodeescape", "illegal Unicode character",
5794 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005795 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005796 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005797 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005798 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005799 break;
5800
Benjamin Peterson29060642009-01-31 22:14:21 +00005801 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005802 case 'N':
5803 message = "malformed \\N character escape";
5804 if (ucnhash_CAPI == NULL) {
5805 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005806 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5807 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005808 if (ucnhash_CAPI == NULL)
5809 goto ucnhashError;
5810 }
5811 if (*s == '{') {
5812 const char *start = s+1;
5813 /* look for the closing brace */
5814 while (*s != '}' && s < end)
5815 s++;
5816 if (s > start && s < end && *s == '}') {
5817 /* found a name. look it up in the unicode database */
5818 message = "unknown Unicode character name";
5819 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005820 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
5821 &chr))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005822 goto store;
5823 }
5824 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005825 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005826 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005827 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005828 errors, &errorHandler,
5829 "unicodeescape", message,
5830 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005831 &v, &i, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005832 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005833 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005834 break;
5835
5836 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005837 if (s > end) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005838 assert(kind == PyUnicode_WCHAR_KIND);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005839 message = "\\ at end of string";
5840 s--;
5841 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005842 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005843 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005844 errors, &errorHandler,
5845 "unicodeescape", message,
5846 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005847 &v, &i, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00005848 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005849 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005850 }
5851 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005852 WRITE_ASCII_OR_WSTR(kind, data, i++, '\\');
5853 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005854 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005855 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005856 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005857 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005858 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005859 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005860 /* Ensure the length prediction worked in case of ASCII strings */
5861 assert(kind == PyUnicode_WCHAR_KIND || i == ascii_length);
5862
Victor Stinnerfe226c02011-10-03 03:52:20 +02005863 if (kind == PyUnicode_WCHAR_KIND)
5864 {
5865 if (PyUnicode_Resize((PyObject**)&v, i) < 0)
5866 goto onError;
Victor Stinnerfe226c02011-10-03 03:52:20 +02005867 }
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005868 Py_XDECREF(errorHandler);
5869 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005870#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005871 if (_PyUnicode_READY_REPLACE(&v)) {
5872 Py_DECREF(v);
5873 return NULL;
5874 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005875#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005876 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00005877 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005878
Benjamin Peterson29060642009-01-31 22:14:21 +00005879 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005880 PyErr_SetString(
5881 PyExc_UnicodeError,
5882 "\\N escapes not supported (can't load unicodedata module)"
5883 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005884 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005885 Py_XDECREF(errorHandler);
5886 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005887 return NULL;
5888
Benjamin Peterson29060642009-01-31 22:14:21 +00005889 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005890 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005891 Py_XDECREF(errorHandler);
5892 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005893 return NULL;
5894}
5895
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005896#undef WRITE_ASCII_OR_WSTR
5897#undef WRITE_WSTR
5898
Guido van Rossumd57fd912000-03-10 22:53:23 +00005899/* Return a Unicode-Escape string version of the Unicode object.
5900
5901 If quotes is true, the string is enclosed in u"" or u'' quotes as
5902 appropriate.
5903
5904*/
5905
Walter Dörwald79e913e2007-05-12 11:08:06 +00005906static const char *hexdigits = "0123456789abcdef";
5907
Alexander Belopolsky40018472011-02-26 01:02:56 +00005908PyObject *
5909PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005910 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005911{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005912 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005913 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005914
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005915#ifdef Py_UNICODE_WIDE
5916 const Py_ssize_t expandsize = 10;
5917#else
5918 const Py_ssize_t expandsize = 6;
5919#endif
5920
Thomas Wouters89f507f2006-12-13 04:49:30 +00005921 /* XXX(nnorwitz): rather than over-allocating, it would be
5922 better to choose a different scheme. Perhaps scan the
5923 first N-chars of the string and allocate based on that size.
5924 */
5925 /* Initial allocation is based on the longest-possible unichr
5926 escape.
5927
5928 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5929 unichr, so in this case it's the longest unichr escape. In
5930 narrow (UTF-16) builds this is five chars per source unichr
5931 since there are two unichrs in the surrogate pair, so in narrow
5932 (UTF-16) builds it's not the longest unichr escape.
5933
5934 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5935 so in the narrow (UTF-16) build case it's the longest unichr
5936 escape.
5937 */
5938
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005939 if (size == 0)
5940 return PyBytes_FromStringAndSize(NULL, 0);
5941
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005942 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005943 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005944
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005945 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005946 2
5947 + expandsize*size
5948 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005949 if (repr == NULL)
5950 return NULL;
5951
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005952 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005953
Guido van Rossumd57fd912000-03-10 22:53:23 +00005954 while (size-- > 0) {
5955 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005956
Walter Dörwald79e913e2007-05-12 11:08:06 +00005957 /* Escape backslashes */
5958 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005959 *p++ = '\\';
5960 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005961 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005962 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005963
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00005964#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005965 /* Map 21-bit characters to '\U00xxxxxx' */
5966 else if (ch >= 0x10000) {
5967 *p++ = '\\';
5968 *p++ = 'U';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005969 *p++ = hexdigits[(ch >> 28) & 0x0000000F];
5970 *p++ = hexdigits[(ch >> 24) & 0x0000000F];
5971 *p++ = hexdigits[(ch >> 20) & 0x0000000F];
5972 *p++ = hexdigits[(ch >> 16) & 0x0000000F];
5973 *p++ = hexdigits[(ch >> 12) & 0x0000000F];
5974 *p++ = hexdigits[(ch >> 8) & 0x0000000F];
5975 *p++ = hexdigits[(ch >> 4) & 0x0000000F];
5976 *p++ = hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005977 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005978 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005979#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005980 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
5981 else if (ch >= 0xD800 && ch < 0xDC00) {
5982 Py_UNICODE ch2;
5983 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00005984
Benjamin Peterson29060642009-01-31 22:14:21 +00005985 ch2 = *s++;
5986 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00005987 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005988 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
5989 *p++ = '\\';
5990 *p++ = 'U';
5991 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
5992 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
5993 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
5994 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
5995 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
5996 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
5997 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
5998 *p++ = hexdigits[ucs & 0x0000000F];
5999 continue;
6000 }
6001 /* Fall through: isolated surrogates are copied as-is */
6002 s--;
6003 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006004 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00006005#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006006
Guido van Rossumd57fd912000-03-10 22:53:23 +00006007 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006008 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006009 *p++ = '\\';
6010 *p++ = 'u';
Walter Dörwald79e913e2007-05-12 11:08:06 +00006011 *p++ = hexdigits[(ch >> 12) & 0x000F];
6012 *p++ = hexdigits[(ch >> 8) & 0x000F];
6013 *p++ = hexdigits[(ch >> 4) & 0x000F];
6014 *p++ = hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006015 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006016
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006017 /* Map special whitespace to '\t', \n', '\r' */
6018 else if (ch == '\t') {
6019 *p++ = '\\';
6020 *p++ = 't';
6021 }
6022 else if (ch == '\n') {
6023 *p++ = '\\';
6024 *p++ = 'n';
6025 }
6026 else if (ch == '\r') {
6027 *p++ = '\\';
6028 *p++ = 'r';
6029 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006030
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006031 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006032 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006033 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006034 *p++ = 'x';
Walter Dörwald79e913e2007-05-12 11:08:06 +00006035 *p++ = hexdigits[(ch >> 4) & 0x000F];
6036 *p++ = hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006037 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006038
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039 /* Copy everything else as-is */
6040 else
6041 *p++ = (char) ch;
6042 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006043
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006044 assert(p - PyBytes_AS_STRING(repr) > 0);
6045 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6046 return NULL;
6047 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006048}
6049
Alexander Belopolsky40018472011-02-26 01:02:56 +00006050PyObject *
6051PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006052{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006053 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006054 if (!PyUnicode_Check(unicode)) {
6055 PyErr_BadArgument();
6056 return NULL;
6057 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00006058 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6059 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006060 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006061}
6062
6063/* --- Raw Unicode Escape Codec ------------------------------------------- */
6064
Alexander Belopolsky40018472011-02-26 01:02:56 +00006065PyObject *
6066PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006067 Py_ssize_t size,
6068 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006069{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006070 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006071 Py_ssize_t startinpos;
6072 Py_ssize_t endinpos;
6073 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006074 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006075 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006076 const char *end;
6077 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006078 PyObject *errorHandler = NULL;
6079 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006080
Guido van Rossumd57fd912000-03-10 22:53:23 +00006081 /* Escaped strings will always be longer than the resulting
6082 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006083 length after conversion to the true value. (But decoding error
6084 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006085 v = _PyUnicode_New(size);
6086 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006087 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006088 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006089 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006090 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006091 end = s + size;
6092 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006093 unsigned char c;
6094 Py_UCS4 x;
6095 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006096 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006097
Benjamin Peterson29060642009-01-31 22:14:21 +00006098 /* Non-escape characters are interpreted as Unicode ordinals */
6099 if (*s != '\\') {
6100 *p++ = (unsigned char)*s++;
6101 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006102 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006103 startinpos = s-starts;
6104
6105 /* \u-escapes are only interpreted iff the number of leading
6106 backslashes if odd */
6107 bs = s;
6108 for (;s < end;) {
6109 if (*s != '\\')
6110 break;
6111 *p++ = (unsigned char)*s++;
6112 }
6113 if (((s - bs) & 1) == 0 ||
6114 s >= end ||
6115 (*s != 'u' && *s != 'U')) {
6116 continue;
6117 }
6118 p--;
6119 count = *s=='u' ? 4 : 8;
6120 s++;
6121
6122 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
6123 outpos = p-PyUnicode_AS_UNICODE(v);
6124 for (x = 0, i = 0; i < count; ++i, ++s) {
6125 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006126 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006127 endinpos = s-starts;
6128 if (unicode_decode_call_errorhandler(
6129 errors, &errorHandler,
6130 "rawunicodeescape", "truncated \\uXXXX",
6131 &starts, &end, &startinpos, &endinpos, &exc, &s,
6132 &v, &outpos, &p))
6133 goto onError;
6134 goto nextByte;
6135 }
6136 x = (x<<4) & ~0xF;
6137 if (c >= '0' && c <= '9')
6138 x += c - '0';
6139 else if (c >= 'a' && c <= 'f')
6140 x += 10 + c - 'a';
6141 else
6142 x += 10 + c - 'A';
6143 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00006144 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00006145 /* UCS-2 character */
6146 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006147 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006148 /* UCS-4 character. Either store directly, or as
6149 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00006150#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006151 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006152#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006153 x -= 0x10000L;
6154 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
6155 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00006156#endif
6157 } else {
6158 endinpos = s-starts;
6159 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006160 if (unicode_decode_call_errorhandler(
6161 errors, &errorHandler,
6162 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006163 &starts, &end, &startinpos, &endinpos, &exc, &s,
6164 &v, &outpos, &p))
6165 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006166 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006167 nextByte:
6168 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006169 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02006170 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006171 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006172 Py_XDECREF(errorHandler);
6173 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006174#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006175 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006176 Py_DECREF(v);
6177 return NULL;
6178 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006179#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006180 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006181 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006182
Benjamin Peterson29060642009-01-31 22:14:21 +00006183 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006184 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006185 Py_XDECREF(errorHandler);
6186 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006187 return NULL;
6188}
6189
Alexander Belopolsky40018472011-02-26 01:02:56 +00006190PyObject *
6191PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006192 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006193{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006194 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006195 char *p;
6196 char *q;
6197
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006198#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006199 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006200#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006201 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006202#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00006203
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006204 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006205 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006206
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006207 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006208 if (repr == NULL)
6209 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00006210 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006211 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006212
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006213 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006214 while (size-- > 0) {
6215 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006216#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006217 /* Map 32-bit characters to '\Uxxxxxxxx' */
6218 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006219 *p++ = '\\';
6220 *p++ = 'U';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00006221 *p++ = hexdigits[(ch >> 28) & 0xf];
6222 *p++ = hexdigits[(ch >> 24) & 0xf];
6223 *p++ = hexdigits[(ch >> 20) & 0xf];
6224 *p++ = hexdigits[(ch >> 16) & 0xf];
6225 *p++ = hexdigits[(ch >> 12) & 0xf];
6226 *p++ = hexdigits[(ch >> 8) & 0xf];
6227 *p++ = hexdigits[(ch >> 4) & 0xf];
6228 *p++ = hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006229 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006230 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00006231#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006232 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
6233 if (ch >= 0xD800 && ch < 0xDC00) {
6234 Py_UNICODE ch2;
6235 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006236
Benjamin Peterson29060642009-01-31 22:14:21 +00006237 ch2 = *s++;
6238 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00006239 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006240 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
6241 *p++ = '\\';
6242 *p++ = 'U';
6243 *p++ = hexdigits[(ucs >> 28) & 0xf];
6244 *p++ = hexdigits[(ucs >> 24) & 0xf];
6245 *p++ = hexdigits[(ucs >> 20) & 0xf];
6246 *p++ = hexdigits[(ucs >> 16) & 0xf];
6247 *p++ = hexdigits[(ucs >> 12) & 0xf];
6248 *p++ = hexdigits[(ucs >> 8) & 0xf];
6249 *p++ = hexdigits[(ucs >> 4) & 0xf];
6250 *p++ = hexdigits[ucs & 0xf];
6251 continue;
6252 }
6253 /* Fall through: isolated surrogates are copied as-is */
6254 s--;
6255 size++;
6256 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006257#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006258 /* Map 16-bit characters to '\uxxxx' */
6259 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006260 *p++ = '\\';
6261 *p++ = 'u';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00006262 *p++ = hexdigits[(ch >> 12) & 0xf];
6263 *p++ = hexdigits[(ch >> 8) & 0xf];
6264 *p++ = hexdigits[(ch >> 4) & 0xf];
6265 *p++ = hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006266 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006267 /* Copy everything else as-is */
6268 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006269 *p++ = (char) ch;
6270 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006271 size = p - q;
6272
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006273 assert(size > 0);
6274 if (_PyBytes_Resize(&repr, size) < 0)
6275 return NULL;
6276 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006277}
6278
Alexander Belopolsky40018472011-02-26 01:02:56 +00006279PyObject *
6280PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006281{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006282 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006283 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00006284 PyErr_BadArgument();
6285 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006286 }
Walter Dörwald711005d2007-05-12 12:03:26 +00006287 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6288 PyUnicode_GET_SIZE(unicode));
6289
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006290 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006291}
6292
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006293/* --- Unicode Internal Codec ------------------------------------------- */
6294
Alexander Belopolsky40018472011-02-26 01:02:56 +00006295PyObject *
6296_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006297 Py_ssize_t size,
6298 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006299{
6300 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006301 Py_ssize_t startinpos;
6302 Py_ssize_t endinpos;
6303 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006304 PyUnicodeObject *v;
6305 Py_UNICODE *p;
6306 const char *end;
6307 const char *reason;
6308 PyObject *errorHandler = NULL;
6309 PyObject *exc = NULL;
6310
Neal Norwitzd43069c2006-01-08 01:12:10 +00006311#ifdef Py_UNICODE_WIDE
6312 Py_UNICODE unimax = PyUnicode_GetMax();
6313#endif
6314
Thomas Wouters89f507f2006-12-13 04:49:30 +00006315 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006316 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
6317 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006318 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006319 /* Intentionally PyUnicode_GET_SIZE instead of PyUnicode_GET_LENGTH
6320 as string was created with the old API. */
6321 if (PyUnicode_GET_SIZE(v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006322 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006323 p = PyUnicode_AS_UNICODE(v);
6324 end = s + size;
6325
6326 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006327 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006328 /* We have to sanity check the raw data, otherwise doom looms for
6329 some malformed UCS-4 data. */
6330 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006331#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006332 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006333#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006334 end-s < Py_UNICODE_SIZE
6335 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006336 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006337 startinpos = s - starts;
6338 if (end-s < Py_UNICODE_SIZE) {
6339 endinpos = end-starts;
6340 reason = "truncated input";
6341 }
6342 else {
6343 endinpos = s - starts + Py_UNICODE_SIZE;
6344 reason = "illegal code point (> 0x10FFFF)";
6345 }
6346 outpos = p - PyUnicode_AS_UNICODE(v);
6347 if (unicode_decode_call_errorhandler(
6348 errors, &errorHandler,
6349 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006350 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00006351 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006352 goto onError;
6353 }
6354 }
6355 else {
6356 p++;
6357 s += Py_UNICODE_SIZE;
6358 }
6359 }
6360
Victor Stinnerfe226c02011-10-03 03:52:20 +02006361 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006362 goto onError;
6363 Py_XDECREF(errorHandler);
6364 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006365#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006366 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006367 Py_DECREF(v);
6368 return NULL;
6369 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006370#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006371 assert(_PyUnicode_CheckConsistency(v, 1));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006372 return (PyObject *)v;
6373
Benjamin Peterson29060642009-01-31 22:14:21 +00006374 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006375 Py_XDECREF(v);
6376 Py_XDECREF(errorHandler);
6377 Py_XDECREF(exc);
6378 return NULL;
6379}
6380
Guido van Rossumd57fd912000-03-10 22:53:23 +00006381/* --- Latin-1 Codec ------------------------------------------------------ */
6382
Alexander Belopolsky40018472011-02-26 01:02:56 +00006383PyObject *
6384PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006385 Py_ssize_t size,
6386 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006387{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006388 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006389 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006390}
6391
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006392/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006393static void
6394make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006395 const char *encoding,
6396 const Py_UNICODE *unicode, Py_ssize_t size,
6397 Py_ssize_t startpos, Py_ssize_t endpos,
6398 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006399{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006400 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006401 *exceptionObject = PyUnicodeEncodeError_Create(
6402 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006403 }
6404 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006405 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6406 goto onError;
6407 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6408 goto onError;
6409 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6410 goto onError;
6411 return;
6412 onError:
6413 Py_DECREF(*exceptionObject);
6414 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006415 }
6416}
6417
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006418/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006419static void
6420raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006421 const char *encoding,
6422 const Py_UNICODE *unicode, Py_ssize_t size,
6423 Py_ssize_t startpos, Py_ssize_t endpos,
6424 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006425{
6426 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006427 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006428 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006429 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006430}
6431
6432/* error handling callback helper:
6433 build arguments, call the callback and check the arguments,
6434 put the result into newpos and return the replacement string, which
6435 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006436static PyObject *
6437unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006438 PyObject **errorHandler,
6439 const char *encoding, const char *reason,
6440 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
6441 Py_ssize_t startpos, Py_ssize_t endpos,
6442 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006443{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006444 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006445
6446 PyObject *restuple;
6447 PyObject *resunicode;
6448
6449 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006450 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006451 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006452 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006453 }
6454
6455 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006456 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006457 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006458 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006459
6460 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006461 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006462 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006463 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006464 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006465 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006466 Py_DECREF(restuple);
6467 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006468 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006469 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006470 &resunicode, newpos)) {
6471 Py_DECREF(restuple);
6472 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006473 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006474 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6475 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6476 Py_DECREF(restuple);
6477 return NULL;
6478 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006479 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006480 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006481 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006482 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6483 Py_DECREF(restuple);
6484 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006485 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006486 Py_INCREF(resunicode);
6487 Py_DECREF(restuple);
6488 return resunicode;
6489}
6490
Alexander Belopolsky40018472011-02-26 01:02:56 +00006491static PyObject *
6492unicode_encode_ucs1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006493 Py_ssize_t size,
6494 const char *errors,
6495 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006496{
6497 /* output object */
6498 PyObject *res;
6499 /* pointers to the beginning and end+1 of input */
6500 const Py_UNICODE *startp = p;
6501 const Py_UNICODE *endp = p + size;
6502 /* pointer to the beginning of the unencodable characters */
6503 /* const Py_UNICODE *badp = NULL; */
6504 /* pointer into the output */
6505 char *str;
6506 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006507 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006508 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6509 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006510 PyObject *errorHandler = NULL;
6511 PyObject *exc = NULL;
6512 /* the following variable is used for caching string comparisons
6513 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6514 int known_errorHandler = -1;
6515
6516 /* allocate enough for a simple encoding without
6517 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006518 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006519 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006520 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006521 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006522 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006523 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006524 ressize = size;
6525
6526 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006527 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006528
Benjamin Peterson29060642009-01-31 22:14:21 +00006529 /* can we encode this? */
6530 if (c<limit) {
6531 /* no overflow check, because we know that the space is enough */
6532 *str++ = (char)c;
6533 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006534 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006535 else {
6536 Py_ssize_t unicodepos = p-startp;
6537 Py_ssize_t requiredsize;
6538 PyObject *repunicode;
6539 Py_ssize_t repsize;
6540 Py_ssize_t newpos;
6541 Py_ssize_t respos;
6542 Py_UNICODE *uni2;
6543 /* startpos for collecting unencodable chars */
6544 const Py_UNICODE *collstart = p;
6545 const Py_UNICODE *collend = p;
6546 /* find all unecodable characters */
6547 while ((collend < endp) && ((*collend)>=limit))
6548 ++collend;
6549 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6550 if (known_errorHandler==-1) {
6551 if ((errors==NULL) || (!strcmp(errors, "strict")))
6552 known_errorHandler = 1;
6553 else if (!strcmp(errors, "replace"))
6554 known_errorHandler = 2;
6555 else if (!strcmp(errors, "ignore"))
6556 known_errorHandler = 3;
6557 else if (!strcmp(errors, "xmlcharrefreplace"))
6558 known_errorHandler = 4;
6559 else
6560 known_errorHandler = 0;
6561 }
6562 switch (known_errorHandler) {
6563 case 1: /* strict */
6564 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
6565 goto onError;
6566 case 2: /* replace */
6567 while (collstart++<collend)
6568 *str++ = '?'; /* fall through */
6569 case 3: /* ignore */
6570 p = collend;
6571 break;
6572 case 4: /* xmlcharrefreplace */
6573 respos = str - PyBytes_AS_STRING(res);
6574 /* determine replacement size (temporarily (mis)uses p) */
6575 for (p = collstart, repsize = 0; p < collend; ++p) {
6576 if (*p<10)
6577 repsize += 2+1+1;
6578 else if (*p<100)
6579 repsize += 2+2+1;
6580 else if (*p<1000)
6581 repsize += 2+3+1;
6582 else if (*p<10000)
6583 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006584#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006585 else
6586 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006587#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006588 else if (*p<100000)
6589 repsize += 2+5+1;
6590 else if (*p<1000000)
6591 repsize += 2+6+1;
6592 else
6593 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006594#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006595 }
6596 requiredsize = respos+repsize+(endp-collend);
6597 if (requiredsize > ressize) {
6598 if (requiredsize<2*ressize)
6599 requiredsize = 2*ressize;
6600 if (_PyBytes_Resize(&res, requiredsize))
6601 goto onError;
6602 str = PyBytes_AS_STRING(res) + respos;
6603 ressize = requiredsize;
6604 }
6605 /* generate replacement (temporarily (mis)uses p) */
6606 for (p = collstart; p < collend; ++p) {
6607 str += sprintf(str, "&#%d;", (int)*p);
6608 }
6609 p = collend;
6610 break;
6611 default:
6612 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
6613 encoding, reason, startp, size, &exc,
6614 collstart-startp, collend-startp, &newpos);
6615 if (repunicode == NULL)
6616 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006617 if (PyBytes_Check(repunicode)) {
6618 /* Directly copy bytes result to output. */
6619 repsize = PyBytes_Size(repunicode);
6620 if (repsize > 1) {
6621 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006622 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006623 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6624 Py_DECREF(repunicode);
6625 goto onError;
6626 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006627 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006628 ressize += repsize-1;
6629 }
6630 memcpy(str, PyBytes_AsString(repunicode), repsize);
6631 str += repsize;
6632 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006633 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006634 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006635 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006636 /* need more space? (at least enough for what we
6637 have+the replacement+the rest of the string, so
6638 we won't have to check space for encodable characters) */
6639 respos = str - PyBytes_AS_STRING(res);
6640 repsize = PyUnicode_GET_SIZE(repunicode);
6641 requiredsize = respos+repsize+(endp-collend);
6642 if (requiredsize > ressize) {
6643 if (requiredsize<2*ressize)
6644 requiredsize = 2*ressize;
6645 if (_PyBytes_Resize(&res, requiredsize)) {
6646 Py_DECREF(repunicode);
6647 goto onError;
6648 }
6649 str = PyBytes_AS_STRING(res) + respos;
6650 ressize = requiredsize;
6651 }
6652 /* check if there is anything unencodable in the replacement
6653 and copy it to the output */
6654 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
6655 c = *uni2;
6656 if (c >= limit) {
6657 raise_encode_exception(&exc, encoding, startp, size,
6658 unicodepos, unicodepos+1, reason);
6659 Py_DECREF(repunicode);
6660 goto onError;
6661 }
6662 *str = (char)c;
6663 }
6664 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006665 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006666 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006667 }
6668 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006669 /* Resize if we allocated to much */
6670 size = str - PyBytes_AS_STRING(res);
6671 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006672 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006673 if (_PyBytes_Resize(&res, size) < 0)
6674 goto onError;
6675 }
6676
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006677 Py_XDECREF(errorHandler);
6678 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006679 return res;
6680
6681 onError:
6682 Py_XDECREF(res);
6683 Py_XDECREF(errorHandler);
6684 Py_XDECREF(exc);
6685 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006686}
6687
Alexander Belopolsky40018472011-02-26 01:02:56 +00006688PyObject *
6689PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006690 Py_ssize_t size,
6691 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006692{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006693 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006694}
6695
Alexander Belopolsky40018472011-02-26 01:02:56 +00006696PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006697_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006698{
6699 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006700 PyErr_BadArgument();
6701 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006702 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006703 if (PyUnicode_READY(unicode) == -1)
6704 return NULL;
6705 /* Fast path: if it is a one-byte string, construct
6706 bytes object directly. */
6707 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6708 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6709 PyUnicode_GET_LENGTH(unicode));
6710 /* Non-Latin-1 characters present. Defer to above function to
6711 raise the exception. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006712 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006713 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006714 errors);
6715}
6716
6717PyObject*
6718PyUnicode_AsLatin1String(PyObject *unicode)
6719{
6720 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006721}
6722
6723/* --- 7-bit ASCII Codec -------------------------------------------------- */
6724
Alexander Belopolsky40018472011-02-26 01:02:56 +00006725PyObject *
6726PyUnicode_DecodeASCII(const char *s,
6727 Py_ssize_t size,
6728 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006729{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006730 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006731 PyUnicodeObject *v;
Victor Stinner702c7342011-10-05 13:50:52 +02006732 Py_UNICODE *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006733 Py_ssize_t startinpos;
6734 Py_ssize_t endinpos;
6735 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006736 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006737 int has_error;
6738 const unsigned char *p = (const unsigned char *)s;
6739 const unsigned char *end = p + size;
6740 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006741 PyObject *errorHandler = NULL;
6742 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006743
Guido van Rossumd57fd912000-03-10 22:53:23 +00006744 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006745 if (size == 1 && (unsigned char)s[0] < 128)
6746 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006747
Victor Stinner702c7342011-10-05 13:50:52 +02006748 has_error = 0;
6749 while (p < end && !has_error) {
6750 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6751 an explanation. */
6752 if (!((size_t) p & LONG_PTR_MASK)) {
6753 /* Help register allocation */
6754 register const unsigned char *_p = p;
6755 while (_p < aligned_end) {
6756 unsigned long value = *(unsigned long *) _p;
6757 if (value & ASCII_CHAR_MASK) {
6758 has_error = 1;
6759 break;
6760 }
6761 _p += SIZEOF_LONG;
6762 }
6763 if (_p == end)
6764 break;
6765 if (has_error)
6766 break;
6767 p = _p;
6768 }
6769 if (*p & 0x80) {
6770 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006771 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006772 }
6773 else {
6774 ++p;
6775 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006776 }
Victor Stinner702c7342011-10-05 13:50:52 +02006777 if (!has_error)
6778 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006779
Guido van Rossumd57fd912000-03-10 22:53:23 +00006780 v = _PyUnicode_New(size);
6781 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006782 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006783 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006784 return (PyObject *)v;
Victor Stinner702c7342011-10-05 13:50:52 +02006785 u = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006786 e = s + size;
6787 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006788 register unsigned char c = (unsigned char)*s;
6789 if (c < 128) {
Victor Stinner702c7342011-10-05 13:50:52 +02006790 *u++ = c;
Benjamin Peterson29060642009-01-31 22:14:21 +00006791 ++s;
6792 }
6793 else {
6794 startinpos = s-starts;
6795 endinpos = startinpos + 1;
Victor Stinner702c7342011-10-05 13:50:52 +02006796 outpos = u - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006797 if (unicode_decode_call_errorhandler(
6798 errors, &errorHandler,
6799 "ascii", "ordinal not in range(128)",
6800 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinner702c7342011-10-05 13:50:52 +02006801 &v, &outpos, &u))
Benjamin Peterson29060642009-01-31 22:14:21 +00006802 goto onError;
6803 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006804 }
Victor Stinner702c7342011-10-05 13:50:52 +02006805 if (u - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
6806 if (PyUnicode_Resize((PyObject**)&v, u - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006807 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006808 Py_XDECREF(errorHandler);
6809 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006810#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006811 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006812 Py_DECREF(v);
6813 return NULL;
6814 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006815#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006816 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006817 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006818
Benjamin Peterson29060642009-01-31 22:14:21 +00006819 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006820 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006821 Py_XDECREF(errorHandler);
6822 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006823 return NULL;
6824}
6825
Alexander Belopolsky40018472011-02-26 01:02:56 +00006826PyObject *
6827PyUnicode_EncodeASCII(const Py_UNICODE *p,
6828 Py_ssize_t size,
6829 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006830{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006831 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006832}
6833
Alexander Belopolsky40018472011-02-26 01:02:56 +00006834PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006835_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006836{
6837 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006838 PyErr_BadArgument();
6839 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006840 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006841 if (PyUnicode_READY(unicode) == -1)
6842 return NULL;
6843 /* Fast path: if it is an ASCII-only string, construct bytes object
6844 directly. Else defer to above function to raise the exception. */
6845 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6846 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6847 PyUnicode_GET_LENGTH(unicode));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006848 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006849 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006850 errors);
6851}
6852
6853PyObject *
6854PyUnicode_AsASCIIString(PyObject *unicode)
6855{
6856 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006857}
6858
Victor Stinner99b95382011-07-04 14:23:54 +02006859#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006860
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006861/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006862
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006863#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006864#define NEED_RETRY
6865#endif
6866
6867/* XXX This code is limited to "true" double-byte encodings, as
6868 a) it assumes an incomplete character consists of a single byte, and
6869 b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
Benjamin Peterson29060642009-01-31 22:14:21 +00006870 encodings, see IsDBCSLeadByteEx documentation. */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006871
Alexander Belopolsky40018472011-02-26 01:02:56 +00006872static int
6873is_dbcs_lead_byte(const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006874{
6875 const char *curr = s + offset;
6876
6877 if (IsDBCSLeadByte(*curr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006878 const char *prev = CharPrev(s, curr);
6879 return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006880 }
6881 return 0;
6882}
6883
6884/*
6885 * Decode MBCS string into unicode object. If 'final' is set, converts
6886 * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
6887 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006888static int
6889decode_mbcs(PyUnicodeObject **v,
6890 const char *s, /* MBCS string */
6891 int size, /* sizeof MBCS string */
6892 int final,
6893 const char *errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006894{
6895 Py_UNICODE *p;
Victor Stinner554f3f02010-06-16 23:33:54 +00006896 Py_ssize_t n;
6897 DWORD usize;
6898 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006899
6900 assert(size >= 0);
6901
Victor Stinner554f3f02010-06-16 23:33:54 +00006902 /* check and handle 'errors' arg */
6903 if (errors==NULL || strcmp(errors, "strict")==0)
6904 flags = MB_ERR_INVALID_CHARS;
6905 else if (strcmp(errors, "ignore")==0)
6906 flags = 0;
6907 else {
6908 PyErr_Format(PyExc_ValueError,
6909 "mbcs encoding does not support errors='%s'",
6910 errors);
6911 return -1;
6912 }
6913
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006914 /* Skip trailing lead-byte unless 'final' is set */
6915 if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006916 --size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006917
6918 /* First get the size of the result */
6919 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00006920 usize = MultiByteToWideChar(CP_ACP, flags, s, size, NULL, 0);
6921 if (usize==0)
6922 goto mbcs_decode_error;
6923 } else
6924 usize = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006925
6926 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006927 /* Create unicode object */
6928 *v = _PyUnicode_New(usize);
6929 if (*v == NULL)
6930 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00006931 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006932 }
6933 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006934 /* Extend unicode object */
6935 n = PyUnicode_GET_SIZE(*v);
Victor Stinner2fd82272011-10-03 04:06:05 +02006936 if (PyUnicode_Resize((PyObject**)v, n + usize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006937 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006938 }
6939
6940 /* Do the conversion */
Victor Stinner554f3f02010-06-16 23:33:54 +00006941 if (usize > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006942 p = PyUnicode_AS_UNICODE(*v) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00006943 if (0 == MultiByteToWideChar(CP_ACP, flags, s, size, p, usize)) {
6944 goto mbcs_decode_error;
Benjamin Peterson29060642009-01-31 22:14:21 +00006945 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006946 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006947 return size;
Victor Stinner554f3f02010-06-16 23:33:54 +00006948
6949mbcs_decode_error:
6950 /* If the last error was ERROR_NO_UNICODE_TRANSLATION, then
6951 we raise a UnicodeDecodeError - else it is a 'generic'
6952 windows error
6953 */
6954 if (GetLastError()==ERROR_NO_UNICODE_TRANSLATION) {
6955 /* Ideally, we should get reason from FormatMessage - this
6956 is the Windows 2000 English version of the message
6957 */
6958 PyObject *exc = NULL;
6959 const char *reason = "No mapping for the Unicode character exists "
6960 "in the target multi-byte code page.";
6961 make_decode_exception(&exc, "mbcs", s, size, 0, 0, reason);
6962 if (exc != NULL) {
6963 PyCodec_StrictErrors(exc);
6964 Py_DECREF(exc);
6965 }
6966 } else {
6967 PyErr_SetFromWindowsErrWithFilename(0, NULL);
6968 }
6969 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006970}
6971
Alexander Belopolsky40018472011-02-26 01:02:56 +00006972PyObject *
6973PyUnicode_DecodeMBCSStateful(const char *s,
6974 Py_ssize_t size,
6975 const char *errors,
6976 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006977{
6978 PyUnicodeObject *v = NULL;
6979 int done;
6980
6981 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006982 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006983
6984#ifdef NEED_RETRY
6985 retry:
6986 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00006987 done = decode_mbcs(&v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006988 else
6989#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00006990 done = decode_mbcs(&v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006991
6992 if (done < 0) {
6993 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006994 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006995 }
6996
6997 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006998 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006999
7000#ifdef NEED_RETRY
7001 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007002 s += done;
7003 size -= done;
7004 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007005 }
7006#endif
Victor Stinner17efeed2011-10-04 20:05:46 +02007007#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007008 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007009 Py_DECREF(v);
7010 return NULL;
7011 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007012#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007013 assert(_PyUnicode_CheckConsistency(v, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007014 return (PyObject *)v;
7015}
7016
Alexander Belopolsky40018472011-02-26 01:02:56 +00007017PyObject *
7018PyUnicode_DecodeMBCS(const char *s,
7019 Py_ssize_t size,
7020 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007021{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007022 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7023}
7024
7025/*
7026 * Convert unicode into string object (MBCS).
7027 * Returns 0 if succeed, -1 otherwise.
7028 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007029static int
7030encode_mbcs(PyObject **repr,
7031 const Py_UNICODE *p, /* unicode */
7032 int size, /* size of unicode */
7033 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007034{
Victor Stinner554f3f02010-06-16 23:33:54 +00007035 BOOL usedDefaultChar = FALSE;
7036 BOOL *pusedDefaultChar;
7037 int mbcssize;
7038 Py_ssize_t n;
7039 PyObject *exc = NULL;
7040 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007041
7042 assert(size >= 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007043
Victor Stinner554f3f02010-06-16 23:33:54 +00007044 /* check and handle 'errors' arg */
7045 if (errors==NULL || strcmp(errors, "strict")==0) {
7046 flags = WC_NO_BEST_FIT_CHARS;
7047 pusedDefaultChar = &usedDefaultChar;
7048 } else if (strcmp(errors, "replace")==0) {
7049 flags = 0;
7050 pusedDefaultChar = NULL;
7051 } else {
7052 PyErr_Format(PyExc_ValueError,
7053 "mbcs encoding does not support errors='%s'",
7054 errors);
7055 return -1;
7056 }
7057
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007058 /* First get the size of the result */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007059 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00007060 mbcssize = WideCharToMultiByte(CP_ACP, flags, p, size, NULL, 0,
7061 NULL, pusedDefaultChar);
Benjamin Peterson29060642009-01-31 22:14:21 +00007062 if (mbcssize == 0) {
7063 PyErr_SetFromWindowsErrWithFilename(0, NULL);
7064 return -1;
7065 }
Victor Stinner554f3f02010-06-16 23:33:54 +00007066 /* If we used a default char, then we failed! */
7067 if (pusedDefaultChar && *pusedDefaultChar)
7068 goto mbcs_encode_error;
7069 } else {
7070 mbcssize = 0;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007071 }
7072
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007073 if (*repr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007074 /* Create string object */
7075 *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
7076 if (*repr == NULL)
7077 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00007078 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007079 }
7080 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007081 /* Extend string object */
7082 n = PyBytes_Size(*repr);
7083 if (_PyBytes_Resize(repr, n + mbcssize) < 0)
7084 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007085 }
7086
7087 /* Do the conversion */
7088 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007089 char *s = PyBytes_AS_STRING(*repr) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00007090 if (0 == WideCharToMultiByte(CP_ACP, flags, p, size, s, mbcssize,
7091 NULL, pusedDefaultChar)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007092 PyErr_SetFromWindowsErrWithFilename(0, NULL);
7093 return -1;
7094 }
Victor Stinner554f3f02010-06-16 23:33:54 +00007095 if (pusedDefaultChar && *pusedDefaultChar)
7096 goto mbcs_encode_error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007097 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007098 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007099
7100mbcs_encode_error:
7101 raise_encode_exception(&exc, "mbcs", p, size, 0, 0, "invalid character");
7102 Py_XDECREF(exc);
7103 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007104}
7105
Alexander Belopolsky40018472011-02-26 01:02:56 +00007106PyObject *
7107PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7108 Py_ssize_t size,
7109 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007110{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007111 PyObject *repr = NULL;
7112 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00007113
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007114#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00007115 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007116 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00007117 ret = encode_mbcs(&repr, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007118 else
7119#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00007120 ret = encode_mbcs(&repr, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007121
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007122 if (ret < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007123 Py_XDECREF(repr);
7124 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007125 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007126
7127#ifdef NEED_RETRY
7128 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007129 p += INT_MAX;
7130 size -= INT_MAX;
7131 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007132 }
7133#endif
7134
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007135 return repr;
7136}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007137
Alexander Belopolsky40018472011-02-26 01:02:56 +00007138PyObject *
7139PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007140{
7141 if (!PyUnicode_Check(unicode)) {
7142 PyErr_BadArgument();
7143 return NULL;
7144 }
7145 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00007146 PyUnicode_GET_SIZE(unicode),
7147 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007148}
7149
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007150#undef NEED_RETRY
7151
Victor Stinner99b95382011-07-04 14:23:54 +02007152#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007153
Guido van Rossumd57fd912000-03-10 22:53:23 +00007154/* --- Character Mapping Codec -------------------------------------------- */
7155
Alexander Belopolsky40018472011-02-26 01:02:56 +00007156PyObject *
7157PyUnicode_DecodeCharmap(const char *s,
7158 Py_ssize_t size,
7159 PyObject *mapping,
7160 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007161{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007162 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007163 Py_ssize_t startinpos;
7164 Py_ssize_t endinpos;
7165 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007166 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007167 PyUnicodeObject *v;
7168 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007169 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007170 PyObject *errorHandler = NULL;
7171 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007172 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007173 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00007174
Guido van Rossumd57fd912000-03-10 22:53:23 +00007175 /* Default to Latin-1 */
7176 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007177 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007178
7179 v = _PyUnicode_New(size);
7180 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007181 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007182 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007183 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007184 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007185 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007186 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007187 mapstring = PyUnicode_AS_UNICODE(mapping);
7188 maplen = PyUnicode_GET_SIZE(mapping);
7189 while (s < e) {
7190 unsigned char ch = *s;
7191 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007192
Benjamin Peterson29060642009-01-31 22:14:21 +00007193 if (ch < maplen)
7194 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00007195
Benjamin Peterson29060642009-01-31 22:14:21 +00007196 if (x == 0xfffe) {
7197 /* undefined mapping */
7198 outpos = p-PyUnicode_AS_UNICODE(v);
7199 startinpos = s-starts;
7200 endinpos = startinpos+1;
7201 if (unicode_decode_call_errorhandler(
7202 errors, &errorHandler,
7203 "charmap", "character maps to <undefined>",
7204 &starts, &e, &startinpos, &endinpos, &exc, &s,
7205 &v, &outpos, &p)) {
7206 goto onError;
7207 }
7208 continue;
7209 }
7210 *p++ = x;
7211 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007212 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007213 }
7214 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007215 while (s < e) {
7216 unsigned char ch = *s;
7217 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007218
Benjamin Peterson29060642009-01-31 22:14:21 +00007219 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7220 w = PyLong_FromLong((long)ch);
7221 if (w == NULL)
7222 goto onError;
7223 x = PyObject_GetItem(mapping, w);
7224 Py_DECREF(w);
7225 if (x == NULL) {
7226 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7227 /* No mapping found means: mapping is undefined. */
7228 PyErr_Clear();
7229 x = Py_None;
7230 Py_INCREF(x);
7231 } else
7232 goto onError;
7233 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007234
Benjamin Peterson29060642009-01-31 22:14:21 +00007235 /* Apply mapping */
7236 if (PyLong_Check(x)) {
7237 long value = PyLong_AS_LONG(x);
7238 if (value < 0 || value > 65535) {
7239 PyErr_SetString(PyExc_TypeError,
7240 "character mapping must be in range(65536)");
7241 Py_DECREF(x);
7242 goto onError;
7243 }
7244 *p++ = (Py_UNICODE)value;
7245 }
7246 else if (x == Py_None) {
7247 /* undefined mapping */
7248 outpos = p-PyUnicode_AS_UNICODE(v);
7249 startinpos = s-starts;
7250 endinpos = startinpos+1;
7251 if (unicode_decode_call_errorhandler(
7252 errors, &errorHandler,
7253 "charmap", "character maps to <undefined>",
7254 &starts, &e, &startinpos, &endinpos, &exc, &s,
7255 &v, &outpos, &p)) {
7256 Py_DECREF(x);
7257 goto onError;
7258 }
7259 Py_DECREF(x);
7260 continue;
7261 }
7262 else if (PyUnicode_Check(x)) {
7263 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007264
Benjamin Peterson29060642009-01-31 22:14:21 +00007265 if (targetsize == 1)
7266 /* 1-1 mapping */
7267 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007268
Benjamin Peterson29060642009-01-31 22:14:21 +00007269 else if (targetsize > 1) {
7270 /* 1-n mapping */
7271 if (targetsize > extrachars) {
7272 /* resize first */
7273 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
7274 Py_ssize_t needed = (targetsize - extrachars) + \
7275 (targetsize << 2);
7276 extrachars += needed;
7277 /* XXX overflow detection missing */
Victor Stinnerfe226c02011-10-03 03:52:20 +02007278 if (PyUnicode_Resize((PyObject**)&v,
Benjamin Peterson29060642009-01-31 22:14:21 +00007279 PyUnicode_GET_SIZE(v) + needed) < 0) {
7280 Py_DECREF(x);
7281 goto onError;
7282 }
7283 p = PyUnicode_AS_UNICODE(v) + oldpos;
7284 }
7285 Py_UNICODE_COPY(p,
7286 PyUnicode_AS_UNICODE(x),
7287 targetsize);
7288 p += targetsize;
7289 extrachars -= targetsize;
7290 }
7291 /* 1-0 mapping: skip the character */
7292 }
7293 else {
7294 /* wrong return value */
7295 PyErr_SetString(PyExc_TypeError,
7296 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007297 Py_DECREF(x);
7298 goto onError;
7299 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007300 Py_DECREF(x);
7301 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007302 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007303 }
7304 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Victor Stinnerfe226c02011-10-03 03:52:20 +02007305 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007306 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007307 Py_XDECREF(errorHandler);
7308 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02007309#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007310 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007311 Py_DECREF(v);
7312 return NULL;
7313 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007314#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007315 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007316 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00007317
Benjamin Peterson29060642009-01-31 22:14:21 +00007318 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007319 Py_XDECREF(errorHandler);
7320 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007321 Py_XDECREF(v);
7322 return NULL;
7323}
7324
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007325/* Charmap encoding: the lookup table */
7326
Alexander Belopolsky40018472011-02-26 01:02:56 +00007327struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007328 PyObject_HEAD
7329 unsigned char level1[32];
7330 int count2, count3;
7331 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007332};
7333
7334static PyObject*
7335encoding_map_size(PyObject *obj, PyObject* args)
7336{
7337 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007338 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007339 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007340}
7341
7342static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007343 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007344 PyDoc_STR("Return the size (in bytes) of this object") },
7345 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007346};
7347
7348static void
7349encoding_map_dealloc(PyObject* o)
7350{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007351 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007352}
7353
7354static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007355 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007356 "EncodingMap", /*tp_name*/
7357 sizeof(struct encoding_map), /*tp_basicsize*/
7358 0, /*tp_itemsize*/
7359 /* methods */
7360 encoding_map_dealloc, /*tp_dealloc*/
7361 0, /*tp_print*/
7362 0, /*tp_getattr*/
7363 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007364 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007365 0, /*tp_repr*/
7366 0, /*tp_as_number*/
7367 0, /*tp_as_sequence*/
7368 0, /*tp_as_mapping*/
7369 0, /*tp_hash*/
7370 0, /*tp_call*/
7371 0, /*tp_str*/
7372 0, /*tp_getattro*/
7373 0, /*tp_setattro*/
7374 0, /*tp_as_buffer*/
7375 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7376 0, /*tp_doc*/
7377 0, /*tp_traverse*/
7378 0, /*tp_clear*/
7379 0, /*tp_richcompare*/
7380 0, /*tp_weaklistoffset*/
7381 0, /*tp_iter*/
7382 0, /*tp_iternext*/
7383 encoding_map_methods, /*tp_methods*/
7384 0, /*tp_members*/
7385 0, /*tp_getset*/
7386 0, /*tp_base*/
7387 0, /*tp_dict*/
7388 0, /*tp_descr_get*/
7389 0, /*tp_descr_set*/
7390 0, /*tp_dictoffset*/
7391 0, /*tp_init*/
7392 0, /*tp_alloc*/
7393 0, /*tp_new*/
7394 0, /*tp_free*/
7395 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007396};
7397
7398PyObject*
7399PyUnicode_BuildEncodingMap(PyObject* string)
7400{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007401 PyObject *result;
7402 struct encoding_map *mresult;
7403 int i;
7404 int need_dict = 0;
7405 unsigned char level1[32];
7406 unsigned char level2[512];
7407 unsigned char *mlevel1, *mlevel2, *mlevel3;
7408 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007409 int kind;
7410 void *data;
7411 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007412
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007413 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007414 PyErr_BadArgument();
7415 return NULL;
7416 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007417 kind = PyUnicode_KIND(string);
7418 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007419 memset(level1, 0xFF, sizeof level1);
7420 memset(level2, 0xFF, sizeof level2);
7421
7422 /* If there isn't a one-to-one mapping of NULL to \0,
7423 or if there are non-BMP characters, we need to use
7424 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007425 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007426 need_dict = 1;
7427 for (i = 1; i < 256; i++) {
7428 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007429 ch = PyUnicode_READ(kind, data, i);
7430 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007431 need_dict = 1;
7432 break;
7433 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007434 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007435 /* unmapped character */
7436 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007437 l1 = ch >> 11;
7438 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007439 if (level1[l1] == 0xFF)
7440 level1[l1] = count2++;
7441 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007442 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007443 }
7444
7445 if (count2 >= 0xFF || count3 >= 0xFF)
7446 need_dict = 1;
7447
7448 if (need_dict) {
7449 PyObject *result = PyDict_New();
7450 PyObject *key, *value;
7451 if (!result)
7452 return NULL;
7453 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007454 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007455 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007456 if (!key || !value)
7457 goto failed1;
7458 if (PyDict_SetItem(result, key, value) == -1)
7459 goto failed1;
7460 Py_DECREF(key);
7461 Py_DECREF(value);
7462 }
7463 return result;
7464 failed1:
7465 Py_XDECREF(key);
7466 Py_XDECREF(value);
7467 Py_DECREF(result);
7468 return NULL;
7469 }
7470
7471 /* Create a three-level trie */
7472 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7473 16*count2 + 128*count3 - 1);
7474 if (!result)
7475 return PyErr_NoMemory();
7476 PyObject_Init(result, &EncodingMapType);
7477 mresult = (struct encoding_map*)result;
7478 mresult->count2 = count2;
7479 mresult->count3 = count3;
7480 mlevel1 = mresult->level1;
7481 mlevel2 = mresult->level23;
7482 mlevel3 = mresult->level23 + 16*count2;
7483 memcpy(mlevel1, level1, 32);
7484 memset(mlevel2, 0xFF, 16*count2);
7485 memset(mlevel3, 0, 128*count3);
7486 count3 = 0;
7487 for (i = 1; i < 256; i++) {
7488 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007489 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007490 /* unmapped character */
7491 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007492 o1 = PyUnicode_READ(kind, data, i)>>11;
7493 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007494 i2 = 16*mlevel1[o1] + o2;
7495 if (mlevel2[i2] == 0xFF)
7496 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007497 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007498 i3 = 128*mlevel2[i2] + o3;
7499 mlevel3[i3] = i;
7500 }
7501 return result;
7502}
7503
7504static int
7505encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
7506{
7507 struct encoding_map *map = (struct encoding_map*)mapping;
7508 int l1 = c>>11;
7509 int l2 = (c>>7) & 0xF;
7510 int l3 = c & 0x7F;
7511 int i;
7512
7513#ifdef Py_UNICODE_WIDE
7514 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007515 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007516 }
7517#endif
7518 if (c == 0)
7519 return 0;
7520 /* level 1*/
7521 i = map->level1[l1];
7522 if (i == 0xFF) {
7523 return -1;
7524 }
7525 /* level 2*/
7526 i = map->level23[16*i+l2];
7527 if (i == 0xFF) {
7528 return -1;
7529 }
7530 /* level 3 */
7531 i = map->level23[16*map->count2 + 128*i + l3];
7532 if (i == 0) {
7533 return -1;
7534 }
7535 return i;
7536}
7537
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007538/* Lookup the character ch in the mapping. If the character
7539 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007540 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007541static PyObject *
7542charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007543{
Christian Heimes217cfd12007-12-02 14:31:20 +00007544 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007545 PyObject *x;
7546
7547 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007548 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007549 x = PyObject_GetItem(mapping, w);
7550 Py_DECREF(w);
7551 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007552 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7553 /* No mapping found means: mapping is undefined. */
7554 PyErr_Clear();
7555 x = Py_None;
7556 Py_INCREF(x);
7557 return x;
7558 } else
7559 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007560 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007561 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007562 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007563 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007564 long value = PyLong_AS_LONG(x);
7565 if (value < 0 || value > 255) {
7566 PyErr_SetString(PyExc_TypeError,
7567 "character mapping must be in range(256)");
7568 Py_DECREF(x);
7569 return NULL;
7570 }
7571 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007572 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007573 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007574 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007575 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007576 /* wrong return value */
7577 PyErr_Format(PyExc_TypeError,
7578 "character mapping must return integer, bytes or None, not %.400s",
7579 x->ob_type->tp_name);
7580 Py_DECREF(x);
7581 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007582 }
7583}
7584
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007585static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007586charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007587{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007588 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7589 /* exponentially overallocate to minimize reallocations */
7590 if (requiredsize < 2*outsize)
7591 requiredsize = 2*outsize;
7592 if (_PyBytes_Resize(outobj, requiredsize))
7593 return -1;
7594 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007595}
7596
Benjamin Peterson14339b62009-01-31 16:36:08 +00007597typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007598 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007599} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007600/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007601 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007602 space is available. Return a new reference to the object that
7603 was put in the output buffer, or Py_None, if the mapping was undefined
7604 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007605 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007606static charmapencode_result
7607charmapencode_output(Py_UNICODE c, PyObject *mapping,
7608 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007609{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007610 PyObject *rep;
7611 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007612 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007613
Christian Heimes90aa7642007-12-19 02:45:37 +00007614 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007615 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007616 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007617 if (res == -1)
7618 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007619 if (outsize<requiredsize)
7620 if (charmapencode_resize(outobj, outpos, requiredsize))
7621 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007622 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007623 outstart[(*outpos)++] = (char)res;
7624 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007625 }
7626
7627 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007628 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007629 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007630 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007631 Py_DECREF(rep);
7632 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007633 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007634 if (PyLong_Check(rep)) {
7635 Py_ssize_t requiredsize = *outpos+1;
7636 if (outsize<requiredsize)
7637 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7638 Py_DECREF(rep);
7639 return enc_EXCEPTION;
7640 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007641 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007642 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007643 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007644 else {
7645 const char *repchars = PyBytes_AS_STRING(rep);
7646 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7647 Py_ssize_t requiredsize = *outpos+repsize;
7648 if (outsize<requiredsize)
7649 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7650 Py_DECREF(rep);
7651 return enc_EXCEPTION;
7652 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007653 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007654 memcpy(outstart + *outpos, repchars, repsize);
7655 *outpos += repsize;
7656 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007657 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007658 Py_DECREF(rep);
7659 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007660}
7661
7662/* handle an error in PyUnicode_EncodeCharmap
7663 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007664static int
7665charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00007666 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007667 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007668 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007669 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007670{
7671 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007672 Py_ssize_t repsize;
7673 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007674 Py_UNICODE *uni2;
7675 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007676 Py_ssize_t collstartpos = *inpos;
7677 Py_ssize_t collendpos = *inpos+1;
7678 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007679 char *encoding = "charmap";
7680 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007681 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007682
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007683 /* find all unencodable characters */
7684 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007685 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007686 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007687 int res = encoding_map_lookup(p[collendpos], mapping);
7688 if (res != -1)
7689 break;
7690 ++collendpos;
7691 continue;
7692 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007693
Benjamin Peterson29060642009-01-31 22:14:21 +00007694 rep = charmapencode_lookup(p[collendpos], mapping);
7695 if (rep==NULL)
7696 return -1;
7697 else if (rep!=Py_None) {
7698 Py_DECREF(rep);
7699 break;
7700 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007701 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007702 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007703 }
7704 /* cache callback name lookup
7705 * (if not done yet, i.e. it's the first error) */
7706 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007707 if ((errors==NULL) || (!strcmp(errors, "strict")))
7708 *known_errorHandler = 1;
7709 else if (!strcmp(errors, "replace"))
7710 *known_errorHandler = 2;
7711 else if (!strcmp(errors, "ignore"))
7712 *known_errorHandler = 3;
7713 else if (!strcmp(errors, "xmlcharrefreplace"))
7714 *known_errorHandler = 4;
7715 else
7716 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007717 }
7718 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007719 case 1: /* strict */
7720 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7721 return -1;
7722 case 2: /* replace */
7723 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007724 x = charmapencode_output('?', mapping, res, respos);
7725 if (x==enc_EXCEPTION) {
7726 return -1;
7727 }
7728 else if (x==enc_FAILED) {
7729 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7730 return -1;
7731 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007732 }
7733 /* fall through */
7734 case 3: /* ignore */
7735 *inpos = collendpos;
7736 break;
7737 case 4: /* xmlcharrefreplace */
7738 /* generate replacement (temporarily (mis)uses p) */
7739 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007740 char buffer[2+29+1+1];
7741 char *cp;
7742 sprintf(buffer, "&#%d;", (int)p[collpos]);
7743 for (cp = buffer; *cp; ++cp) {
7744 x = charmapencode_output(*cp, mapping, res, respos);
7745 if (x==enc_EXCEPTION)
7746 return -1;
7747 else if (x==enc_FAILED) {
7748 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7749 return -1;
7750 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007751 }
7752 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007753 *inpos = collendpos;
7754 break;
7755 default:
7756 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00007757 encoding, reason, p, size, exceptionObject,
7758 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007759 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007760 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00007761 if (PyBytes_Check(repunicode)) {
7762 /* Directly copy bytes result to output. */
7763 Py_ssize_t outsize = PyBytes_Size(*res);
7764 Py_ssize_t requiredsize;
7765 repsize = PyBytes_Size(repunicode);
7766 requiredsize = *respos + repsize;
7767 if (requiredsize > outsize)
7768 /* Make room for all additional bytes. */
7769 if (charmapencode_resize(res, respos, requiredsize)) {
7770 Py_DECREF(repunicode);
7771 return -1;
7772 }
7773 memcpy(PyBytes_AsString(*res) + *respos,
7774 PyBytes_AsString(repunicode), repsize);
7775 *respos += repsize;
7776 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007777 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00007778 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007779 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007780 /* generate replacement */
7781 repsize = PyUnicode_GET_SIZE(repunicode);
7782 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007783 x = charmapencode_output(*uni2, mapping, res, respos);
7784 if (x==enc_EXCEPTION) {
7785 return -1;
7786 }
7787 else if (x==enc_FAILED) {
7788 Py_DECREF(repunicode);
7789 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7790 return -1;
7791 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007792 }
7793 *inpos = newpos;
7794 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007795 }
7796 return 0;
7797}
7798
Alexander Belopolsky40018472011-02-26 01:02:56 +00007799PyObject *
7800PyUnicode_EncodeCharmap(const Py_UNICODE *p,
7801 Py_ssize_t size,
7802 PyObject *mapping,
7803 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007804{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007805 /* output object */
7806 PyObject *res = NULL;
7807 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007808 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007809 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007810 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007811 PyObject *errorHandler = NULL;
7812 PyObject *exc = NULL;
7813 /* the following variable is used for caching string comparisons
7814 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
7815 * 3=ignore, 4=xmlcharrefreplace */
7816 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007817
7818 /* Default to Latin-1 */
7819 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007820 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007821
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007822 /* allocate enough for a simple encoding without
7823 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00007824 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007825 if (res == NULL)
7826 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00007827 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007828 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007829
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007830 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007831 /* try to encode it */
7832 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
7833 if (x==enc_EXCEPTION) /* error */
7834 goto onError;
7835 if (x==enc_FAILED) { /* unencodable character */
7836 if (charmap_encoding_error(p, size, &inpos, mapping,
7837 &exc,
7838 &known_errorHandler, &errorHandler, errors,
7839 &res, &respos)) {
7840 goto onError;
7841 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007842 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007843 else
7844 /* done with this character => adjust input position */
7845 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007846 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007847
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007848 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00007849 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00007850 if (_PyBytes_Resize(&res, respos) < 0)
7851 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00007852
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007853 Py_XDECREF(exc);
7854 Py_XDECREF(errorHandler);
7855 return res;
7856
Benjamin Peterson29060642009-01-31 22:14:21 +00007857 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007858 Py_XDECREF(res);
7859 Py_XDECREF(exc);
7860 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007861 return NULL;
7862}
7863
Alexander Belopolsky40018472011-02-26 01:02:56 +00007864PyObject *
7865PyUnicode_AsCharmapString(PyObject *unicode,
7866 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007867{
7868 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007869 PyErr_BadArgument();
7870 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007871 }
7872 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00007873 PyUnicode_GET_SIZE(unicode),
7874 mapping,
7875 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007876}
7877
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007878/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007879static void
7880make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007881 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007882 Py_ssize_t startpos, Py_ssize_t endpos,
7883 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007884{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007885 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007886 *exceptionObject = _PyUnicodeTranslateError_Create(
7887 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007888 }
7889 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007890 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
7891 goto onError;
7892 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
7893 goto onError;
7894 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
7895 goto onError;
7896 return;
7897 onError:
7898 Py_DECREF(*exceptionObject);
7899 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007900 }
7901}
7902
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007903/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007904static void
7905raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007906 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007907 Py_ssize_t startpos, Py_ssize_t endpos,
7908 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007909{
7910 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007911 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007912 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007913 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007914}
7915
7916/* error handling callback helper:
7917 build arguments, call the callback and check the arguments,
7918 put the result into newpos and return the replacement string, which
7919 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007920static PyObject *
7921unicode_translate_call_errorhandler(const char *errors,
7922 PyObject **errorHandler,
7923 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007924 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007925 Py_ssize_t startpos, Py_ssize_t endpos,
7926 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007927{
Benjamin Peterson142957c2008-07-04 19:55:29 +00007928 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007929
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007930 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007931 PyObject *restuple;
7932 PyObject *resunicode;
7933
7934 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007935 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007936 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007937 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007938 }
7939
7940 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007941 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007942 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007943 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007944
7945 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00007946 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007947 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007948 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007949 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00007950 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00007951 Py_DECREF(restuple);
7952 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007953 }
7954 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00007955 &resunicode, &i_newpos)) {
7956 Py_DECREF(restuple);
7957 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007958 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00007959 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007960 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007961 else
7962 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007963 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007964 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
7965 Py_DECREF(restuple);
7966 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00007967 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007968 Py_INCREF(resunicode);
7969 Py_DECREF(restuple);
7970 return resunicode;
7971}
7972
7973/* Lookup the character ch in the mapping and put the result in result,
7974 which must be decrefed by the caller.
7975 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007976static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007977charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007978{
Christian Heimes217cfd12007-12-02 14:31:20 +00007979 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007980 PyObject *x;
7981
7982 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007983 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007984 x = PyObject_GetItem(mapping, w);
7985 Py_DECREF(w);
7986 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007987 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7988 /* No mapping found means: use 1:1 mapping. */
7989 PyErr_Clear();
7990 *result = NULL;
7991 return 0;
7992 } else
7993 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007994 }
7995 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007996 *result = x;
7997 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007998 }
Christian Heimes217cfd12007-12-02 14:31:20 +00007999 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008000 long value = PyLong_AS_LONG(x);
8001 long max = PyUnicode_GetMax();
8002 if (value < 0 || value > max) {
8003 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008004 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008005 Py_DECREF(x);
8006 return -1;
8007 }
8008 *result = x;
8009 return 0;
8010 }
8011 else if (PyUnicode_Check(x)) {
8012 *result = x;
8013 return 0;
8014 }
8015 else {
8016 /* wrong return value */
8017 PyErr_SetString(PyExc_TypeError,
8018 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008019 Py_DECREF(x);
8020 return -1;
8021 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008022}
8023/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008024 if not reallocate and adjust various state variables.
8025 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008026static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008027charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008028 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008029{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008030 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008031 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008032 /* exponentially overallocate to minimize reallocations */
8033 if (requiredsize < 2 * oldsize)
8034 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008035 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8036 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008037 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008038 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008039 }
8040 return 0;
8041}
8042/* lookup the character, put the result in the output string and adjust
8043 various state variables. Return a new reference to the object that
8044 was put in the output buffer in *result, or Py_None, if the mapping was
8045 undefined (in which case no character was written).
8046 The called must decref result.
8047 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008048static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008049charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8050 PyObject *mapping, Py_UCS4 **output,
8051 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008052 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008053{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008054 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8055 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008056 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008057 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008058 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008059 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008060 }
8061 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008062 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008063 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008064 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008065 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008066 }
8067 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008068 Py_ssize_t repsize;
8069 if (PyUnicode_READY(*res) == -1)
8070 return -1;
8071 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008072 if (repsize==1) {
8073 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008074 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008075 }
8076 else if (repsize!=0) {
8077 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008078 Py_ssize_t requiredsize = *opos +
8079 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008080 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008081 Py_ssize_t i;
8082 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008083 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008084 for(i = 0; i < repsize; i++)
8085 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008086 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008087 }
8088 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008089 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008090 return 0;
8091}
8092
Alexander Belopolsky40018472011-02-26 01:02:56 +00008093PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008094_PyUnicode_TranslateCharmap(PyObject *input,
8095 PyObject *mapping,
8096 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008097{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008098 /* input object */
8099 char *idata;
8100 Py_ssize_t size, i;
8101 int kind;
8102 /* output buffer */
8103 Py_UCS4 *output = NULL;
8104 Py_ssize_t osize;
8105 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008106 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008107 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008108 char *reason = "character maps to <undefined>";
8109 PyObject *errorHandler = NULL;
8110 PyObject *exc = NULL;
8111 /* the following variable is used for caching string comparisons
8112 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8113 * 3=ignore, 4=xmlcharrefreplace */
8114 int known_errorHandler = -1;
8115
Guido van Rossumd57fd912000-03-10 22:53:23 +00008116 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008117 PyErr_BadArgument();
8118 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008119 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008120
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008121 if (PyUnicode_READY(input) == -1)
8122 return NULL;
8123 idata = (char*)PyUnicode_DATA(input);
8124 kind = PyUnicode_KIND(input);
8125 size = PyUnicode_GET_LENGTH(input);
8126 i = 0;
8127
8128 if (size == 0) {
8129 Py_INCREF(input);
8130 return input;
8131 }
8132
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008133 /* allocate enough for a simple 1:1 translation without
8134 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008135 osize = size;
8136 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8137 opos = 0;
8138 if (output == NULL) {
8139 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008140 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008141 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008142
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008143 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008144 /* try to encode it */
8145 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008146 if (charmaptranslate_output(input, i, mapping,
8147 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008148 Py_XDECREF(x);
8149 goto onError;
8150 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008151 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008152 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008153 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008154 else { /* untranslatable character */
8155 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8156 Py_ssize_t repsize;
8157 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008158 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008159 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008160 Py_ssize_t collstart = i;
8161 Py_ssize_t collend = i+1;
8162 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008163
Benjamin Peterson29060642009-01-31 22:14:21 +00008164 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008165 while (collend < size) {
8166 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008167 goto onError;
8168 Py_XDECREF(x);
8169 if (x!=Py_None)
8170 break;
8171 ++collend;
8172 }
8173 /* cache callback name lookup
8174 * (if not done yet, i.e. it's the first error) */
8175 if (known_errorHandler==-1) {
8176 if ((errors==NULL) || (!strcmp(errors, "strict")))
8177 known_errorHandler = 1;
8178 else if (!strcmp(errors, "replace"))
8179 known_errorHandler = 2;
8180 else if (!strcmp(errors, "ignore"))
8181 known_errorHandler = 3;
8182 else if (!strcmp(errors, "xmlcharrefreplace"))
8183 known_errorHandler = 4;
8184 else
8185 known_errorHandler = 0;
8186 }
8187 switch (known_errorHandler) {
8188 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008189 raise_translate_exception(&exc, input, collstart,
8190 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008191 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008192 case 2: /* replace */
8193 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008194 for (coll = collstart; coll<collend; coll++)
8195 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008196 /* fall through */
8197 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008198 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008199 break;
8200 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008201 /* generate replacement (temporarily (mis)uses i) */
8202 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008203 char buffer[2+29+1+1];
8204 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008205 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8206 if (charmaptranslate_makespace(&output, &osize,
8207 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008208 goto onError;
8209 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008210 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008211 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008212 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008213 break;
8214 default:
8215 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008216 reason, input, &exc,
8217 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008218 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008219 goto onError;
8220 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008221 repsize = PyUnicode_GET_LENGTH(repunicode);
8222 if (charmaptranslate_makespace(&output, &osize,
8223 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008224 Py_DECREF(repunicode);
8225 goto onError;
8226 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008227 for (uni2 = 0; repsize-->0; ++uni2)
8228 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8229 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008230 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008231 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008232 }
8233 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008234 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8235 if (!res)
8236 goto onError;
8237 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008238 Py_XDECREF(exc);
8239 Py_XDECREF(errorHandler);
8240 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008241
Benjamin Peterson29060642009-01-31 22:14:21 +00008242 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008243 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008244 Py_XDECREF(exc);
8245 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008246 return NULL;
8247}
8248
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008249/* Deprecated. Use PyUnicode_Translate instead. */
8250PyObject *
8251PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8252 Py_ssize_t size,
8253 PyObject *mapping,
8254 const char *errors)
8255{
8256 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8257 if (!unicode)
8258 return NULL;
8259 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8260}
8261
Alexander Belopolsky40018472011-02-26 01:02:56 +00008262PyObject *
8263PyUnicode_Translate(PyObject *str,
8264 PyObject *mapping,
8265 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008266{
8267 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008268
Guido van Rossumd57fd912000-03-10 22:53:23 +00008269 str = PyUnicode_FromObject(str);
8270 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008271 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008272 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008273 Py_DECREF(str);
8274 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008275
Benjamin Peterson29060642009-01-31 22:14:21 +00008276 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008277 Py_XDECREF(str);
8278 return NULL;
8279}
Tim Petersced69f82003-09-16 20:30:58 +00008280
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008281static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008282fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008283{
8284 /* No need to call PyUnicode_READY(self) because this function is only
8285 called as a callback from fixup() which does it already. */
8286 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8287 const int kind = PyUnicode_KIND(self);
8288 void *data = PyUnicode_DATA(self);
8289 Py_UCS4 maxchar = 0, ch, fixed;
8290 Py_ssize_t i;
8291
8292 for (i = 0; i < len; ++i) {
8293 ch = PyUnicode_READ(kind, data, i);
8294 fixed = 0;
8295 if (ch > 127) {
8296 if (Py_UNICODE_ISSPACE(ch))
8297 fixed = ' ';
8298 else {
8299 const int decimal = Py_UNICODE_TODECIMAL(ch);
8300 if (decimal >= 0)
8301 fixed = '0' + decimal;
8302 }
8303 if (fixed != 0) {
8304 if (fixed > maxchar)
8305 maxchar = fixed;
8306 PyUnicode_WRITE(kind, data, i, fixed);
8307 }
8308 else if (ch > maxchar)
8309 maxchar = ch;
8310 }
8311 else if (ch > maxchar)
8312 maxchar = ch;
8313 }
8314
8315 return maxchar;
8316}
8317
8318PyObject *
8319_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8320{
8321 if (!PyUnicode_Check(unicode)) {
8322 PyErr_BadInternalCall();
8323 return NULL;
8324 }
8325 if (PyUnicode_READY(unicode) == -1)
8326 return NULL;
8327 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8328 /* If the string is already ASCII, just return the same string */
8329 Py_INCREF(unicode);
8330 return unicode;
8331 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008332 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008333}
8334
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008335PyObject *
8336PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8337 Py_ssize_t length)
8338{
8339 PyObject *result;
8340 Py_UNICODE *p; /* write pointer into result */
8341 Py_ssize_t i;
8342 /* Copy to a new string */
8343 result = (PyObject *)_PyUnicode_New(length);
8344 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8345 if (result == NULL)
8346 return result;
8347 p = PyUnicode_AS_UNICODE(result);
8348 /* Iterate over code points */
8349 for (i = 0; i < length; i++) {
8350 Py_UNICODE ch =s[i];
8351 if (ch > 127) {
8352 int decimal = Py_UNICODE_TODECIMAL(ch);
8353 if (decimal >= 0)
8354 p[i] = '0' + decimal;
8355 }
8356 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008357#ifndef DONT_MAKE_RESULT_READY
8358 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008359 Py_DECREF(result);
8360 return NULL;
8361 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008362#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008363 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008364 return result;
8365}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008366/* --- Decimal Encoder ---------------------------------------------------- */
8367
Alexander Belopolsky40018472011-02-26 01:02:56 +00008368int
8369PyUnicode_EncodeDecimal(Py_UNICODE *s,
8370 Py_ssize_t length,
8371 char *output,
8372 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008373{
8374 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008375 PyObject *errorHandler = NULL;
8376 PyObject *exc = NULL;
8377 const char *encoding = "decimal";
8378 const char *reason = "invalid decimal Unicode string";
8379 /* the following variable is used for caching string comparisons
8380 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8381 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008382
8383 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008384 PyErr_BadArgument();
8385 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008386 }
8387
8388 p = s;
8389 end = s + length;
8390 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008391 register Py_UNICODE ch = *p;
8392 int decimal;
8393 PyObject *repunicode;
8394 Py_ssize_t repsize;
8395 Py_ssize_t newpos;
8396 Py_UNICODE *uni2;
8397 Py_UNICODE *collstart;
8398 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008399
Benjamin Peterson29060642009-01-31 22:14:21 +00008400 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008401 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008402 ++p;
8403 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008404 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008405 decimal = Py_UNICODE_TODECIMAL(ch);
8406 if (decimal >= 0) {
8407 *output++ = '0' + decimal;
8408 ++p;
8409 continue;
8410 }
8411 if (0 < ch && ch < 256) {
8412 *output++ = (char)ch;
8413 ++p;
8414 continue;
8415 }
8416 /* All other characters are considered unencodable */
8417 collstart = p;
8418 collend = p+1;
8419 while (collend < end) {
8420 if ((0 < *collend && *collend < 256) ||
8421 !Py_UNICODE_ISSPACE(*collend) ||
8422 Py_UNICODE_TODECIMAL(*collend))
8423 break;
8424 }
8425 /* cache callback name lookup
8426 * (if not done yet, i.e. it's the first error) */
8427 if (known_errorHandler==-1) {
8428 if ((errors==NULL) || (!strcmp(errors, "strict")))
8429 known_errorHandler = 1;
8430 else if (!strcmp(errors, "replace"))
8431 known_errorHandler = 2;
8432 else if (!strcmp(errors, "ignore"))
8433 known_errorHandler = 3;
8434 else if (!strcmp(errors, "xmlcharrefreplace"))
8435 known_errorHandler = 4;
8436 else
8437 known_errorHandler = 0;
8438 }
8439 switch (known_errorHandler) {
8440 case 1: /* strict */
8441 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
8442 goto onError;
8443 case 2: /* replace */
8444 for (p = collstart; p < collend; ++p)
8445 *output++ = '?';
8446 /* fall through */
8447 case 3: /* ignore */
8448 p = collend;
8449 break;
8450 case 4: /* xmlcharrefreplace */
8451 /* generate replacement (temporarily (mis)uses p) */
8452 for (p = collstart; p < collend; ++p)
8453 output += sprintf(output, "&#%d;", (int)*p);
8454 p = collend;
8455 break;
8456 default:
8457 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
8458 encoding, reason, s, length, &exc,
8459 collstart-s, collend-s, &newpos);
8460 if (repunicode == NULL)
8461 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008462 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008463 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008464 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8465 Py_DECREF(repunicode);
8466 goto onError;
8467 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008468 /* generate replacement */
8469 repsize = PyUnicode_GET_SIZE(repunicode);
8470 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
8471 Py_UNICODE ch = *uni2;
8472 if (Py_UNICODE_ISSPACE(ch))
8473 *output++ = ' ';
8474 else {
8475 decimal = Py_UNICODE_TODECIMAL(ch);
8476 if (decimal >= 0)
8477 *output++ = '0' + decimal;
8478 else if (0 < ch && ch < 256)
8479 *output++ = (char)ch;
8480 else {
8481 Py_DECREF(repunicode);
8482 raise_encode_exception(&exc, encoding,
8483 s, length, collstart-s, collend-s, reason);
8484 goto onError;
8485 }
8486 }
8487 }
8488 p = s + newpos;
8489 Py_DECREF(repunicode);
8490 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008491 }
8492 /* 0-terminate the output string */
8493 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008494 Py_XDECREF(exc);
8495 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008496 return 0;
8497
Benjamin Peterson29060642009-01-31 22:14:21 +00008498 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008499 Py_XDECREF(exc);
8500 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008501 return -1;
8502}
8503
Guido van Rossumd57fd912000-03-10 22:53:23 +00008504/* --- Helpers ------------------------------------------------------------ */
8505
Victor Stinnerc3cec782011-10-05 21:24:08 +02008506#include "stringlib/asciilib.h"
8507#include "stringlib/fastsearch.h"
8508#include "stringlib/partition.h"
8509#include "stringlib/split.h"
8510#include "stringlib/count.h"
8511#include "stringlib/find.h"
8512#include "stringlib/localeutil.h"
8513#include "stringlib/undef.h"
8514
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008515#include "stringlib/ucs1lib.h"
8516#include "stringlib/fastsearch.h"
8517#include "stringlib/partition.h"
8518#include "stringlib/split.h"
8519#include "stringlib/count.h"
8520#include "stringlib/find.h"
8521#include "stringlib/localeutil.h"
8522#include "stringlib/undef.h"
8523
8524#include "stringlib/ucs2lib.h"
8525#include "stringlib/fastsearch.h"
8526#include "stringlib/partition.h"
8527#include "stringlib/split.h"
8528#include "stringlib/count.h"
8529#include "stringlib/find.h"
8530#include "stringlib/localeutil.h"
8531#include "stringlib/undef.h"
8532
8533#include "stringlib/ucs4lib.h"
8534#include "stringlib/fastsearch.h"
8535#include "stringlib/partition.h"
8536#include "stringlib/split.h"
8537#include "stringlib/count.h"
8538#include "stringlib/find.h"
8539#include "stringlib/localeutil.h"
8540#include "stringlib/undef.h"
8541
8542static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008543any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008544 Py_ssize_t start,
8545 Py_ssize_t end)
8546{
8547 int kind1, kind2, kind;
8548 void *buf1, *buf2;
8549 Py_ssize_t len1, len2, result;
8550
8551 kind1 = PyUnicode_KIND(s1);
8552 kind2 = PyUnicode_KIND(s2);
8553 kind = kind1 > kind2 ? kind1 : kind2;
8554 buf1 = PyUnicode_DATA(s1);
8555 buf2 = PyUnicode_DATA(s2);
8556 if (kind1 != kind)
8557 buf1 = _PyUnicode_AsKind(s1, kind);
8558 if (!buf1)
8559 return -2;
8560 if (kind2 != kind)
8561 buf2 = _PyUnicode_AsKind(s2, kind);
8562 if (!buf2) {
8563 if (kind1 != kind) PyMem_Free(buf1);
8564 return -2;
8565 }
8566 len1 = PyUnicode_GET_LENGTH(s1);
8567 len2 = PyUnicode_GET_LENGTH(s2);
8568
Victor Stinner794d5672011-10-10 03:21:36 +02008569 if (direction > 0) {
8570 switch(kind) {
8571 case PyUnicode_1BYTE_KIND:
8572 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8573 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8574 else
8575 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8576 break;
8577 case PyUnicode_2BYTE_KIND:
8578 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8579 break;
8580 case PyUnicode_4BYTE_KIND:
8581 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8582 break;
8583 default:
8584 assert(0); result = -2;
8585 }
8586 }
8587 else {
8588 switch(kind) {
8589 case PyUnicode_1BYTE_KIND:
8590 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8591 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8592 else
8593 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8594 break;
8595 case PyUnicode_2BYTE_KIND:
8596 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8597 break;
8598 case PyUnicode_4BYTE_KIND:
8599 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8600 break;
8601 default:
8602 assert(0); result = -2;
8603 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008604 }
8605
8606 if (kind1 != kind)
8607 PyMem_Free(buf1);
8608 if (kind2 != kind)
8609 PyMem_Free(buf2);
8610
8611 return result;
8612}
8613
8614Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02008615_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008616 Py_ssize_t n_buffer,
8617 void *digits, Py_ssize_t n_digits,
8618 Py_ssize_t min_width,
8619 const char *grouping,
8620 const char *thousands_sep)
8621{
8622 switch(kind) {
8623 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008624 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
8625 return _PyUnicode_ascii_InsertThousandsGrouping(
8626 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
8627 min_width, grouping, thousands_sep);
8628 else
8629 return _PyUnicode_ucs1_InsertThousandsGrouping(
8630 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
8631 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008632 case PyUnicode_2BYTE_KIND:
8633 return _PyUnicode_ucs2_InsertThousandsGrouping(
8634 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
8635 min_width, grouping, thousands_sep);
8636 case PyUnicode_4BYTE_KIND:
8637 return _PyUnicode_ucs4_InsertThousandsGrouping(
8638 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
8639 min_width, grouping, thousands_sep);
8640 }
8641 assert(0);
8642 return -1;
8643}
8644
8645
Eric Smith8c663262007-08-25 02:26:07 +00008646#include "stringlib/unicodedefs.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00008647#include "stringlib/fastsearch.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008648
Thomas Wouters477c8d52006-05-27 19:21:47 +00008649#include "stringlib/count.h"
8650#include "stringlib/find.h"
Eric Smith5807c412008-05-11 21:00:57 +00008651
Thomas Wouters477c8d52006-05-27 19:21:47 +00008652/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008653#define ADJUST_INDICES(start, end, len) \
8654 if (end > len) \
8655 end = len; \
8656 else if (end < 0) { \
8657 end += len; \
8658 if (end < 0) \
8659 end = 0; \
8660 } \
8661 if (start < 0) { \
8662 start += len; \
8663 if (start < 0) \
8664 start = 0; \
8665 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008666
Alexander Belopolsky40018472011-02-26 01:02:56 +00008667Py_ssize_t
8668PyUnicode_Count(PyObject *str,
8669 PyObject *substr,
8670 Py_ssize_t start,
8671 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008672{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008673 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008674 PyUnicodeObject* str_obj;
8675 PyUnicodeObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008676 int kind1, kind2, kind;
8677 void *buf1 = NULL, *buf2 = NULL;
8678 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008679
Thomas Wouters477c8d52006-05-27 19:21:47 +00008680 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008681 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008682 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008683 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02008684 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008685 Py_DECREF(str_obj);
8686 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008687 }
Tim Petersced69f82003-09-16 20:30:58 +00008688
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008689 kind1 = PyUnicode_KIND(str_obj);
8690 kind2 = PyUnicode_KIND(sub_obj);
8691 kind = kind1 > kind2 ? kind1 : kind2;
8692 buf1 = PyUnicode_DATA(str_obj);
8693 if (kind1 != kind)
8694 buf1 = _PyUnicode_AsKind((PyObject*)str_obj, kind);
8695 if (!buf1)
8696 goto onError;
8697 buf2 = PyUnicode_DATA(sub_obj);
8698 if (kind2 != kind)
8699 buf2 = _PyUnicode_AsKind((PyObject*)sub_obj, kind);
8700 if (!buf2)
8701 goto onError;
8702 len1 = PyUnicode_GET_LENGTH(str_obj);
8703 len2 = PyUnicode_GET_LENGTH(sub_obj);
8704
8705 ADJUST_INDICES(start, end, len1);
8706 switch(kind) {
8707 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008708 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
8709 result = asciilib_count(
8710 ((Py_UCS1*)buf1) + start, end - start,
8711 buf2, len2, PY_SSIZE_T_MAX
8712 );
8713 else
8714 result = ucs1lib_count(
8715 ((Py_UCS1*)buf1) + start, end - start,
8716 buf2, len2, PY_SSIZE_T_MAX
8717 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008718 break;
8719 case PyUnicode_2BYTE_KIND:
8720 result = ucs2lib_count(
8721 ((Py_UCS2*)buf1) + start, end - start,
8722 buf2, len2, PY_SSIZE_T_MAX
8723 );
8724 break;
8725 case PyUnicode_4BYTE_KIND:
8726 result = ucs4lib_count(
8727 ((Py_UCS4*)buf1) + start, end - start,
8728 buf2, len2, PY_SSIZE_T_MAX
8729 );
8730 break;
8731 default:
8732 assert(0); result = 0;
8733 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008734
8735 Py_DECREF(sub_obj);
8736 Py_DECREF(str_obj);
8737
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008738 if (kind1 != kind)
8739 PyMem_Free(buf1);
8740 if (kind2 != kind)
8741 PyMem_Free(buf2);
8742
Guido van Rossumd57fd912000-03-10 22:53:23 +00008743 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008744 onError:
8745 Py_DECREF(sub_obj);
8746 Py_DECREF(str_obj);
8747 if (kind1 != kind && buf1)
8748 PyMem_Free(buf1);
8749 if (kind2 != kind && buf2)
8750 PyMem_Free(buf2);
8751 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008752}
8753
Alexander Belopolsky40018472011-02-26 01:02:56 +00008754Py_ssize_t
8755PyUnicode_Find(PyObject *str,
8756 PyObject *sub,
8757 Py_ssize_t start,
8758 Py_ssize_t end,
8759 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008760{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008761 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008762
Guido van Rossumd57fd912000-03-10 22:53:23 +00008763 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008764 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008765 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008766 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008767 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008768 Py_DECREF(str);
8769 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008770 }
Tim Petersced69f82003-09-16 20:30:58 +00008771
Victor Stinner794d5672011-10-10 03:21:36 +02008772 result = any_find_slice(direction,
8773 str, sub, start, end
8774 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00008775
Guido van Rossumd57fd912000-03-10 22:53:23 +00008776 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008777 Py_DECREF(sub);
8778
Guido van Rossumd57fd912000-03-10 22:53:23 +00008779 return result;
8780}
8781
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008782Py_ssize_t
8783PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
8784 Py_ssize_t start, Py_ssize_t end,
8785 int direction)
8786{
8787 char *result;
8788 int kind;
8789 if (PyUnicode_READY(str) == -1)
8790 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02008791 if (start < 0 || end < 0) {
8792 PyErr_SetString(PyExc_IndexError, "string index out of range");
8793 return -2;
8794 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008795 if (end > PyUnicode_GET_LENGTH(str))
8796 end = PyUnicode_GET_LENGTH(str);
8797 kind = PyUnicode_KIND(str);
8798 result = findchar(PyUnicode_1BYTE_DATA(str)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02008799 + kind*start,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008800 kind,
8801 end-start, ch, direction);
8802 if (!result)
8803 return -1;
8804 return (result-(char*)PyUnicode_DATA(str)) >> (kind-1);
8805}
8806
Alexander Belopolsky40018472011-02-26 01:02:56 +00008807static int
8808tailmatch(PyUnicodeObject *self,
8809 PyUnicodeObject *substring,
8810 Py_ssize_t start,
8811 Py_ssize_t end,
8812 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008813{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008814 int kind_self;
8815 int kind_sub;
8816 void *data_self;
8817 void *data_sub;
8818 Py_ssize_t offset;
8819 Py_ssize_t i;
8820 Py_ssize_t end_sub;
8821
8822 if (PyUnicode_READY(self) == -1 ||
8823 PyUnicode_READY(substring) == -1)
8824 return 0;
8825
8826 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008827 return 1;
8828
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008829 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
8830 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008831 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00008832 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008833
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008834 kind_self = PyUnicode_KIND(self);
8835 data_self = PyUnicode_DATA(self);
8836 kind_sub = PyUnicode_KIND(substring);
8837 data_sub = PyUnicode_DATA(substring);
8838 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
8839
8840 if (direction > 0)
8841 offset = end;
8842 else
8843 offset = start;
8844
8845 if (PyUnicode_READ(kind_self, data_self, offset) ==
8846 PyUnicode_READ(kind_sub, data_sub, 0) &&
8847 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
8848 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
8849 /* If both are of the same kind, memcmp is sufficient */
8850 if (kind_self == kind_sub) {
8851 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02008852 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008853 data_sub,
8854 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02008855 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008856 }
8857 /* otherwise we have to compare each character by first accesing it */
8858 else {
8859 /* We do not need to compare 0 and len(substring)-1 because
8860 the if statement above ensured already that they are equal
8861 when we end up here. */
8862 // TODO: honor direction and do a forward or backwards search
8863 for (i = 1; i < end_sub; ++i) {
8864 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
8865 PyUnicode_READ(kind_sub, data_sub, i))
8866 return 0;
8867 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008868 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008869 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008870 }
8871
8872 return 0;
8873}
8874
Alexander Belopolsky40018472011-02-26 01:02:56 +00008875Py_ssize_t
8876PyUnicode_Tailmatch(PyObject *str,
8877 PyObject *substr,
8878 Py_ssize_t start,
8879 Py_ssize_t end,
8880 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008881{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008882 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008883
Guido van Rossumd57fd912000-03-10 22:53:23 +00008884 str = PyUnicode_FromObject(str);
8885 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008886 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008887 substr = PyUnicode_FromObject(substr);
8888 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008889 Py_DECREF(str);
8890 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008891 }
Tim Petersced69f82003-09-16 20:30:58 +00008892
Guido van Rossumd57fd912000-03-10 22:53:23 +00008893 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00008894 (PyUnicodeObject *)substr,
8895 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008896 Py_DECREF(str);
8897 Py_DECREF(substr);
8898 return result;
8899}
8900
Guido van Rossumd57fd912000-03-10 22:53:23 +00008901/* Apply fixfct filter to the Unicode object self and return a
8902 reference to the modified object */
8903
Alexander Belopolsky40018472011-02-26 01:02:56 +00008904static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02008905fixup(PyObject *self,
8906 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008907{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008908 PyObject *u;
8909 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008910
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008911 if (PyUnicode_READY(self) == -1)
8912 return NULL;
8913 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
8914 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
8915 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008916 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008917 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00008918
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008919 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02008920 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00008921
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008922 /* fix functions return the new maximum character in a string,
8923 if the kind of the resulting unicode object does not change,
8924 everything is fine. Otherwise we need to change the string kind
8925 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02008926 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008927 if (maxchar_new == 0)
8928 /* do nothing, keep maxchar_new at 0 which means no changes. */;
8929 else if (maxchar_new <= 127)
8930 maxchar_new = 127;
8931 else if (maxchar_new <= 255)
8932 maxchar_new = 255;
8933 else if (maxchar_new <= 65535)
8934 maxchar_new = 65535;
8935 else
8936 maxchar_new = 1114111; /* 0x10ffff */
8937
8938 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008939 /* fixfct should return TRUE if it modified the buffer. If
8940 FALSE, return a reference to the original buffer instead
8941 (to save space, not time) */
8942 Py_INCREF(self);
8943 Py_DECREF(u);
8944 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008945 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008946 else if (maxchar_new == maxchar_old) {
8947 return u;
8948 }
8949 else {
8950 /* In case the maximum character changed, we need to
8951 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008952 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008953 if (v == NULL) {
8954 Py_DECREF(u);
8955 return NULL;
8956 }
8957 if (maxchar_new > maxchar_old) {
8958 /* If the maxchar increased so that the kind changed, not all
8959 characters are representable anymore and we need to fix the
8960 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02008961 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02008962 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008963 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
8964 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008965 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02008966 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008967 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008968
8969 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008970 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008971 return v;
8972 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008973}
8974
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008975static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008976fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008977{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008978 /* No need to call PyUnicode_READY(self) because this function is only
8979 called as a callback from fixup() which does it already. */
8980 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8981 const int kind = PyUnicode_KIND(self);
8982 void *data = PyUnicode_DATA(self);
8983 int touched = 0;
8984 Py_UCS4 maxchar = 0;
8985 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008986
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008987 for (i = 0; i < len; ++i) {
8988 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8989 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
8990 if (up != ch) {
8991 if (up > maxchar)
8992 maxchar = up;
8993 PyUnicode_WRITE(kind, data, i, up);
8994 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008995 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008996 else if (ch > maxchar)
8997 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008998 }
8999
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009000 if (touched)
9001 return maxchar;
9002 else
9003 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009004}
9005
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009006static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009007fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009008{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009009 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9010 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9011 const int kind = PyUnicode_KIND(self);
9012 void *data = PyUnicode_DATA(self);
9013 int touched = 0;
9014 Py_UCS4 maxchar = 0;
9015 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009016
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009017 for(i = 0; i < len; ++i) {
9018 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9019 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9020 if (lo != ch) {
9021 if (lo > maxchar)
9022 maxchar = lo;
9023 PyUnicode_WRITE(kind, data, i, lo);
9024 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009025 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009026 else if (ch > maxchar)
9027 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009028 }
9029
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009030 if (touched)
9031 return maxchar;
9032 else
9033 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009034}
9035
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009036static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009037fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009038{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009039 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9040 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9041 const int kind = PyUnicode_KIND(self);
9042 void *data = PyUnicode_DATA(self);
9043 int touched = 0;
9044 Py_UCS4 maxchar = 0;
9045 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009046
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009047 for(i = 0; i < len; ++i) {
9048 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9049 Py_UCS4 nu = 0;
9050
9051 if (Py_UNICODE_ISUPPER(ch))
9052 nu = Py_UNICODE_TOLOWER(ch);
9053 else if (Py_UNICODE_ISLOWER(ch))
9054 nu = Py_UNICODE_TOUPPER(ch);
9055
9056 if (nu != 0) {
9057 if (nu > maxchar)
9058 maxchar = nu;
9059 PyUnicode_WRITE(kind, data, i, nu);
9060 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009061 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009062 else if (ch > maxchar)
9063 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009064 }
9065
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009066 if (touched)
9067 return maxchar;
9068 else
9069 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009070}
9071
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009072static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009073fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009074{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009075 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9076 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9077 const int kind = PyUnicode_KIND(self);
9078 void *data = PyUnicode_DATA(self);
9079 int touched = 0;
9080 Py_UCS4 maxchar = 0;
9081 Py_ssize_t i = 0;
9082 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009083
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009084 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009085 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009086
9087 ch = PyUnicode_READ(kind, data, i);
9088 if (!Py_UNICODE_ISUPPER(ch)) {
9089 maxchar = Py_UNICODE_TOUPPER(ch);
9090 PyUnicode_WRITE(kind, data, i, maxchar);
9091 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009092 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009093 ++i;
9094 for(; i < len; ++i) {
9095 ch = PyUnicode_READ(kind, data, i);
9096 if (!Py_UNICODE_ISLOWER(ch)) {
9097 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9098 if (lo > maxchar)
9099 maxchar = lo;
9100 PyUnicode_WRITE(kind, data, i, lo);
9101 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009102 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009103 else if (ch > maxchar)
9104 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009105 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009106
9107 if (touched)
9108 return maxchar;
9109 else
9110 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009111}
9112
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009113static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009114fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009115{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009116 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9117 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9118 const int kind = PyUnicode_KIND(self);
9119 void *data = PyUnicode_DATA(self);
9120 Py_UCS4 maxchar = 0;
9121 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009122 int previous_is_cased;
9123
9124 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009125 if (len == 1) {
9126 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9127 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9128 if (ti != ch) {
9129 PyUnicode_WRITE(kind, data, i, ti);
9130 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009131 }
9132 else
9133 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009134 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009135 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009136 for(; i < len; ++i) {
9137 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9138 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009139
Benjamin Peterson29060642009-01-31 22:14:21 +00009140 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009141 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009142 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009143 nu = Py_UNICODE_TOTITLE(ch);
9144
9145 if (nu > maxchar)
9146 maxchar = nu;
9147 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009148
Benjamin Peterson29060642009-01-31 22:14:21 +00009149 if (Py_UNICODE_ISLOWER(ch) ||
9150 Py_UNICODE_ISUPPER(ch) ||
9151 Py_UNICODE_ISTITLE(ch))
9152 previous_is_cased = 1;
9153 else
9154 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009155 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009156 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009157}
9158
Tim Peters8ce9f162004-08-27 01:49:32 +00009159PyObject *
9160PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009161{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009162 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009163 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009164 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009165 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009166 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9167 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009168 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009169 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009170 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009171 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009172 int use_memcpy;
9173 unsigned char *res_data = NULL, *sep_data = NULL;
9174 PyObject *last_obj;
9175 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009176
Tim Peters05eba1f2004-08-27 21:32:02 +00009177 fseq = PySequence_Fast(seq, "");
9178 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009179 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009180 }
9181
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009182 /* NOTE: the following code can't call back into Python code,
9183 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009184 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009185
Tim Peters05eba1f2004-08-27 21:32:02 +00009186 seqlen = PySequence_Fast_GET_SIZE(fseq);
9187 /* If empty sequence, return u"". */
9188 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009189 Py_DECREF(fseq);
9190 Py_INCREF(unicode_empty);
9191 res = unicode_empty;
9192 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009193 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009194
Tim Peters05eba1f2004-08-27 21:32:02 +00009195 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009196 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009197 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009198 if (seqlen == 1) {
9199 if (PyUnicode_CheckExact(items[0])) {
9200 res = items[0];
9201 Py_INCREF(res);
9202 Py_DECREF(fseq);
9203 return res;
9204 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009205 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009206 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009207 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009208 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009209 /* Set up sep and seplen */
9210 if (separator == NULL) {
9211 /* fall back to a blank space separator */
9212 sep = PyUnicode_FromOrdinal(' ');
9213 if (!sep)
9214 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009215 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009216 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009217 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009218 else {
9219 if (!PyUnicode_Check(separator)) {
9220 PyErr_Format(PyExc_TypeError,
9221 "separator: expected str instance,"
9222 " %.80s found",
9223 Py_TYPE(separator)->tp_name);
9224 goto onError;
9225 }
9226 if (PyUnicode_READY(separator))
9227 goto onError;
9228 sep = separator;
9229 seplen = PyUnicode_GET_LENGTH(separator);
9230 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9231 /* inc refcount to keep this code path symmetric with the
9232 above case of a blank separator */
9233 Py_INCREF(sep);
9234 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009235 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009236 }
9237
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009238 /* There are at least two things to join, or else we have a subclass
9239 * of str in the sequence.
9240 * Do a pre-pass to figure out the total amount of space we'll
9241 * need (sz), and see whether all argument are strings.
9242 */
9243 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009244#ifdef Py_DEBUG
9245 use_memcpy = 0;
9246#else
9247 use_memcpy = 1;
9248#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009249 for (i = 0; i < seqlen; i++) {
9250 const Py_ssize_t old_sz = sz;
9251 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009252 if (!PyUnicode_Check(item)) {
9253 PyErr_Format(PyExc_TypeError,
9254 "sequence item %zd: expected str instance,"
9255 " %.80s found",
9256 i, Py_TYPE(item)->tp_name);
9257 goto onError;
9258 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009259 if (PyUnicode_READY(item) == -1)
9260 goto onError;
9261 sz += PyUnicode_GET_LENGTH(item);
9262 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009263 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009264 if (i != 0)
9265 sz += seplen;
9266 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9267 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009268 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009269 goto onError;
9270 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009271 if (use_memcpy && last_obj != NULL) {
9272 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9273 use_memcpy = 0;
9274 }
9275 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009276 }
Tim Petersced69f82003-09-16 20:30:58 +00009277
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009278 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009279 if (res == NULL)
9280 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009281
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009282 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009283#ifdef Py_DEBUG
9284 use_memcpy = 0;
9285#else
9286 if (use_memcpy) {
9287 res_data = PyUnicode_1BYTE_DATA(res);
9288 kind = PyUnicode_KIND(res);
9289 if (seplen != 0)
9290 sep_data = PyUnicode_1BYTE_DATA(sep);
9291 }
9292#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009293 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009294 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009295 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009296 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009297 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009298 if (use_memcpy) {
9299 Py_MEMCPY(res_data,
9300 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009301 kind * seplen);
9302 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009303 }
9304 else {
9305 copy_characters(res, res_offset, sep, 0, seplen);
9306 res_offset += seplen;
9307 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009308 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009309 itemlen = PyUnicode_GET_LENGTH(item);
9310 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009311 if (use_memcpy) {
9312 Py_MEMCPY(res_data,
9313 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009314 kind * itemlen);
9315 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009316 }
9317 else {
9318 copy_characters(res, res_offset, item, 0, itemlen);
9319 res_offset += itemlen;
9320 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009321 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009322 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009323 if (use_memcpy)
9324 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009325 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009326 else
9327 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009328
Tim Peters05eba1f2004-08-27 21:32:02 +00009329 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009330 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009331 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009332 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009333
Benjamin Peterson29060642009-01-31 22:14:21 +00009334 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009335 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009336 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009337 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009338 return NULL;
9339}
9340
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009341#define FILL(kind, data, value, start, length) \
9342 do { \
9343 Py_ssize_t i_ = 0; \
9344 assert(kind != PyUnicode_WCHAR_KIND); \
9345 switch ((kind)) { \
9346 case PyUnicode_1BYTE_KIND: { \
9347 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9348 memset(to_, (unsigned char)value, length); \
9349 break; \
9350 } \
9351 case PyUnicode_2BYTE_KIND: { \
9352 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9353 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9354 break; \
9355 } \
9356 default: { \
9357 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9358 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9359 break; \
9360 } \
9361 } \
9362 } while (0)
9363
Victor Stinner9310abb2011-10-05 00:59:23 +02009364static PyObject *
9365pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009366 Py_ssize_t left,
9367 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009368 Py_UCS4 fill)
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;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009372 int kind;
9373 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009374
9375 if (left < 0)
9376 left = 0;
9377 if (right < 0)
9378 right = 0;
9379
Tim Peters7a29bd52001-09-12 03:03:31 +00009380 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009381 Py_INCREF(self);
9382 return self;
9383 }
9384
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009385 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9386 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009387 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9388 return NULL;
9389 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009390 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9391 if (fill > maxchar)
9392 maxchar = fill;
9393 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009394 if (!u)
9395 return NULL;
9396
9397 kind = PyUnicode_KIND(u);
9398 data = PyUnicode_DATA(u);
9399 if (left)
9400 FILL(kind, data, fill, 0, left);
9401 if (right)
9402 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009403 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009404 assert(_PyUnicode_CheckConsistency(u, 1));
9405 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009406}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009407#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009408
Alexander Belopolsky40018472011-02-26 01:02:56 +00009409PyObject *
9410PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009411{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009412 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009413
9414 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009415 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009416 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009417
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009418 switch(PyUnicode_KIND(string)) {
9419 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009420 if (PyUnicode_IS_ASCII(string))
9421 list = asciilib_splitlines(
9422 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9423 PyUnicode_GET_LENGTH(string), keepends);
9424 else
9425 list = ucs1lib_splitlines(
9426 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9427 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009428 break;
9429 case PyUnicode_2BYTE_KIND:
9430 list = ucs2lib_splitlines(
9431 (PyObject*) string, PyUnicode_2BYTE_DATA(string),
9432 PyUnicode_GET_LENGTH(string), keepends);
9433 break;
9434 case PyUnicode_4BYTE_KIND:
9435 list = ucs4lib_splitlines(
9436 (PyObject*) string, PyUnicode_4BYTE_DATA(string),
9437 PyUnicode_GET_LENGTH(string), keepends);
9438 break;
9439 default:
9440 assert(0);
9441 list = 0;
9442 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009443 Py_DECREF(string);
9444 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009445}
9446
Alexander Belopolsky40018472011-02-26 01:02:56 +00009447static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009448split(PyObject *self,
9449 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009450 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009451{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009452 int kind1, kind2, kind;
9453 void *buf1, *buf2;
9454 Py_ssize_t len1, len2;
9455 PyObject* out;
9456
Guido van Rossumd57fd912000-03-10 22:53:23 +00009457 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009458 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009459
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009460 if (PyUnicode_READY(self) == -1)
9461 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009462
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009463 if (substring == NULL)
9464 switch(PyUnicode_KIND(self)) {
9465 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009466 if (PyUnicode_IS_ASCII(self))
9467 return asciilib_split_whitespace(
9468 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9469 PyUnicode_GET_LENGTH(self), maxcount
9470 );
9471 else
9472 return ucs1lib_split_whitespace(
9473 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9474 PyUnicode_GET_LENGTH(self), maxcount
9475 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009476 case PyUnicode_2BYTE_KIND:
9477 return ucs2lib_split_whitespace(
9478 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9479 PyUnicode_GET_LENGTH(self), maxcount
9480 );
9481 case PyUnicode_4BYTE_KIND:
9482 return ucs4lib_split_whitespace(
9483 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
9484 PyUnicode_GET_LENGTH(self), maxcount
9485 );
9486 default:
9487 assert(0);
9488 return NULL;
9489 }
9490
9491 if (PyUnicode_READY(substring) == -1)
9492 return NULL;
9493
9494 kind1 = PyUnicode_KIND(self);
9495 kind2 = PyUnicode_KIND(substring);
9496 kind = kind1 > kind2 ? kind1 : kind2;
9497 buf1 = PyUnicode_DATA(self);
9498 buf2 = PyUnicode_DATA(substring);
9499 if (kind1 != kind)
9500 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9501 if (!buf1)
9502 return NULL;
9503 if (kind2 != kind)
9504 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9505 if (!buf2) {
9506 if (kind1 != kind) PyMem_Free(buf1);
9507 return NULL;
9508 }
9509 len1 = PyUnicode_GET_LENGTH(self);
9510 len2 = PyUnicode_GET_LENGTH(substring);
9511
9512 switch(kind) {
9513 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009514 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9515 out = asciilib_split(
9516 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9517 else
9518 out = ucs1lib_split(
9519 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009520 break;
9521 case PyUnicode_2BYTE_KIND:
9522 out = ucs2lib_split(
9523 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9524 break;
9525 case PyUnicode_4BYTE_KIND:
9526 out = ucs4lib_split(
9527 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9528 break;
9529 default:
9530 out = NULL;
9531 }
9532 if (kind1 != kind)
9533 PyMem_Free(buf1);
9534 if (kind2 != kind)
9535 PyMem_Free(buf2);
9536 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009537}
9538
Alexander Belopolsky40018472011-02-26 01:02:56 +00009539static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009540rsplit(PyObject *self,
9541 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009542 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009543{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009544 int kind1, kind2, kind;
9545 void *buf1, *buf2;
9546 Py_ssize_t len1, len2;
9547 PyObject* out;
9548
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009549 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009550 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009551
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009552 if (PyUnicode_READY(self) == -1)
9553 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009554
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009555 if (substring == NULL)
9556 switch(PyUnicode_KIND(self)) {
9557 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009558 if (PyUnicode_IS_ASCII(self))
9559 return asciilib_rsplit_whitespace(
9560 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9561 PyUnicode_GET_LENGTH(self), maxcount
9562 );
9563 else
9564 return ucs1lib_rsplit_whitespace(
9565 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9566 PyUnicode_GET_LENGTH(self), maxcount
9567 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009568 case PyUnicode_2BYTE_KIND:
9569 return ucs2lib_rsplit_whitespace(
9570 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9571 PyUnicode_GET_LENGTH(self), maxcount
9572 );
9573 case PyUnicode_4BYTE_KIND:
9574 return ucs4lib_rsplit_whitespace(
9575 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
9576 PyUnicode_GET_LENGTH(self), maxcount
9577 );
9578 default:
9579 assert(0);
9580 return NULL;
9581 }
9582
9583 if (PyUnicode_READY(substring) == -1)
9584 return NULL;
9585
9586 kind1 = PyUnicode_KIND(self);
9587 kind2 = PyUnicode_KIND(substring);
9588 kind = kind1 > kind2 ? kind1 : kind2;
9589 buf1 = PyUnicode_DATA(self);
9590 buf2 = PyUnicode_DATA(substring);
9591 if (kind1 != kind)
9592 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9593 if (!buf1)
9594 return NULL;
9595 if (kind2 != kind)
9596 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9597 if (!buf2) {
9598 if (kind1 != kind) PyMem_Free(buf1);
9599 return NULL;
9600 }
9601 len1 = PyUnicode_GET_LENGTH(self);
9602 len2 = PyUnicode_GET_LENGTH(substring);
9603
9604 switch(kind) {
9605 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009606 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9607 out = asciilib_rsplit(
9608 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9609 else
9610 out = ucs1lib_rsplit(
9611 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009612 break;
9613 case PyUnicode_2BYTE_KIND:
9614 out = ucs2lib_rsplit(
9615 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9616 break;
9617 case PyUnicode_4BYTE_KIND:
9618 out = ucs4lib_rsplit(
9619 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9620 break;
9621 default:
9622 out = NULL;
9623 }
9624 if (kind1 != kind)
9625 PyMem_Free(buf1);
9626 if (kind2 != kind)
9627 PyMem_Free(buf2);
9628 return out;
9629}
9630
9631static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009632anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9633 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009634{
9635 switch(kind) {
9636 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009637 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
9638 return asciilib_find(buf1, len1, buf2, len2, offset);
9639 else
9640 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009641 case PyUnicode_2BYTE_KIND:
9642 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9643 case PyUnicode_4BYTE_KIND:
9644 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9645 }
9646 assert(0);
9647 return -1;
9648}
9649
9650static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009651anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
9652 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009653{
9654 switch(kind) {
9655 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009656 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
9657 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
9658 else
9659 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009660 case PyUnicode_2BYTE_KIND:
9661 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
9662 case PyUnicode_4BYTE_KIND:
9663 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
9664 }
9665 assert(0);
9666 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009667}
9668
Alexander Belopolsky40018472011-02-26 01:02:56 +00009669static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009670replace(PyObject *self, PyObject *str1,
9671 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009672{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009673 PyObject *u;
9674 char *sbuf = PyUnicode_DATA(self);
9675 char *buf1 = PyUnicode_DATA(str1);
9676 char *buf2 = PyUnicode_DATA(str2);
9677 int srelease = 0, release1 = 0, release2 = 0;
9678 int skind = PyUnicode_KIND(self);
9679 int kind1 = PyUnicode_KIND(str1);
9680 int kind2 = PyUnicode_KIND(str2);
9681 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
9682 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
9683 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009684
9685 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009686 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009687 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009688 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009689
Victor Stinner59de0ee2011-10-07 10:01:28 +02009690 if (str1 == str2)
9691 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009692 if (skind < kind1)
9693 /* substring too wide to be present */
9694 goto nothing;
9695
9696 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +00009697 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009698 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009699 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009700 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009701 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009702 /* replace characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009703 Py_UCS4 u1, u2, maxchar;
9704 int mayshrink, rkind;
9705 u1 = PyUnicode_READ_CHAR(str1, 0);
9706 if (!findchar(sbuf, PyUnicode_KIND(self),
9707 slen, u1, 1))
Thomas Wouters477c8d52006-05-27 19:21:47 +00009708 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009709 u2 = PyUnicode_READ_CHAR(str2, 0);
9710 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9711 /* Replacing u1 with u2 may cause a maxchar reduction in the
9712 result string. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009713 if (u2 > maxchar) {
9714 maxchar = u2;
9715 mayshrink = 0;
9716 }
Victor Stinnerb9275c12011-10-05 14:01:42 +02009717 else
9718 mayshrink = maxchar > 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009719 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009720 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009721 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009722 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009723 rkind = PyUnicode_KIND(u);
9724 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
9725 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009726 if (--maxcount < 0)
9727 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009728 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009729 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009730 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +02009731 unicode_adjust_maxchar(&u);
9732 if (u == NULL)
9733 goto error;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009734 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009735 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009736 int rkind = skind;
9737 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +02009738 PyObject *rstr;
9739 Py_UCS4 maxchar;
9740
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009741 if (kind1 < rkind) {
9742 /* widen substring */
9743 buf1 = _PyUnicode_AsKind(str1, rkind);
9744 if (!buf1) goto error;
9745 release1 = 1;
9746 }
Victor Stinnerc3cec782011-10-05 21:24:08 +02009747 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009748 if (i < 0)
9749 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009750 if (rkind > kind2) {
9751 /* widen replacement */
9752 buf2 = _PyUnicode_AsKind(str2, rkind);
9753 if (!buf2) goto error;
9754 release2 = 1;
9755 }
9756 else if (rkind < kind2) {
9757 /* widen self and buf1 */
9758 rkind = kind2;
9759 if (release1) PyMem_Free(buf1);
9760 sbuf = _PyUnicode_AsKind(self, rkind);
9761 if (!sbuf) goto error;
9762 srelease = 1;
9763 buf1 = _PyUnicode_AsKind(str1, rkind);
9764 if (!buf1) goto error;
9765 release1 = 1;
9766 }
Victor Stinner25a4b292011-10-06 12:31:55 +02009767 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9768 maxchar = Py_MAX(maxchar, PyUnicode_MAX_CHAR_VALUE(str2));
9769 rstr = PyUnicode_New(slen, maxchar);
9770 if (!rstr)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009771 goto error;
Victor Stinner25a4b292011-10-06 12:31:55 +02009772 res = PyUnicode_DATA(rstr);
9773
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009774 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009775 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009776 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009777 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009778 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009779 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009780
9781 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +02009782 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009783 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +02009784 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009785 if (i == -1)
9786 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009787 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009788 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009789 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009790 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009791 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009792
Victor Stinner25a4b292011-10-06 12:31:55 +02009793 u = rstr;
9794 unicode_adjust_maxchar(&u);
9795 if (!u)
9796 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009797 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009798 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009799
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009800 Py_ssize_t n, i, j, ires;
9801 Py_ssize_t product, new_size;
9802 int rkind = skind;
Victor Stinner25a4b292011-10-06 12:31:55 +02009803 PyObject *rstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009804 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +02009805 Py_UCS4 maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009806
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009807 if (kind1 < rkind) {
9808 buf1 = _PyUnicode_AsKind(str1, rkind);
9809 if (!buf1) goto error;
9810 release1 = 1;
9811 }
Victor Stinnerc3cec782011-10-05 21:24:08 +02009812 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009813 if (n == 0)
9814 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009815 if (kind2 < rkind) {
9816 buf2 = _PyUnicode_AsKind(str2, rkind);
9817 if (!buf2) goto error;
9818 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009819 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009820 else if (kind2 > rkind) {
9821 rkind = kind2;
9822 sbuf = _PyUnicode_AsKind(self, rkind);
9823 if (!sbuf) goto error;
9824 srelease = 1;
9825 if (release1) PyMem_Free(buf1);
9826 buf1 = _PyUnicode_AsKind(str1, rkind);
9827 if (!buf1) goto error;
9828 release1 = 1;
9829 }
9830 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
9831 PyUnicode_GET_LENGTH(str1))); */
9832 product = n * (len2-len1);
9833 if ((product / (len2-len1)) != n) {
9834 PyErr_SetString(PyExc_OverflowError,
9835 "replace string is too long");
9836 goto error;
9837 }
9838 new_size = slen + product;
9839 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
9840 PyErr_SetString(PyExc_OverflowError,
9841 "replace string is too long");
9842 goto error;
9843 }
Victor Stinner25a4b292011-10-06 12:31:55 +02009844 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9845 maxchar = Py_MAX(maxchar, PyUnicode_MAX_CHAR_VALUE(str2));
9846 rstr = PyUnicode_New(new_size, maxchar);
9847 if (!rstr)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009848 goto error;
Victor Stinner25a4b292011-10-06 12:31:55 +02009849 res = PyUnicode_DATA(rstr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009850 ires = i = 0;
9851 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009852 while (n-- > 0) {
9853 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +02009854 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009855 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +02009856 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009857 if (j == -1)
9858 break;
9859 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009860 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009861 memcpy(res + rkind * ires,
9862 sbuf + rkind * i,
9863 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009864 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009865 }
9866 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009867 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009868 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009869 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009870 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009871 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009872 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009873 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009874 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009875 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +00009876 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009877 memcpy(res + rkind * ires,
9878 sbuf + rkind * i,
9879 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00009880 } else {
9881 /* interleave */
9882 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009883 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009884 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009885 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009886 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009887 if (--n <= 0)
9888 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009889 memcpy(res + rkind * ires,
9890 sbuf + rkind * i,
9891 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009892 ires++;
9893 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009894 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009895 memcpy(res + rkind * ires,
9896 sbuf + rkind * i,
9897 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00009898 }
Victor Stinner25a4b292011-10-06 12:31:55 +02009899 u = rstr;
9900 unicode_adjust_maxchar(&u);
9901 if (u == NULL)
9902 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009903 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009904 if (srelease)
9905 PyMem_FREE(sbuf);
9906 if (release1)
9907 PyMem_FREE(buf1);
9908 if (release2)
9909 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009910 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009911 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009912
Benjamin Peterson29060642009-01-31 22:14:21 +00009913 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00009914 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009915 if (srelease)
9916 PyMem_FREE(sbuf);
9917 if (release1)
9918 PyMem_FREE(buf1);
9919 if (release2)
9920 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009921 if (PyUnicode_CheckExact(self)) {
9922 Py_INCREF(self);
9923 return (PyObject *) self;
9924 }
Victor Stinner034f6cf2011-09-30 02:26:44 +02009925 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009926 error:
9927 if (srelease && sbuf)
9928 PyMem_FREE(sbuf);
9929 if (release1 && buf1)
9930 PyMem_FREE(buf1);
9931 if (release2 && buf2)
9932 PyMem_FREE(buf2);
9933 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009934}
9935
9936/* --- Unicode Object Methods --------------------------------------------- */
9937
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009938PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009939 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009940\n\
9941Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009942characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009943
9944static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +02009945unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009946{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009947 return fixup(self, fixtitle);
9948}
9949
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009950PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009951 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009952\n\
9953Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +00009954have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009955
9956static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +02009957unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009958{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009959 return fixup(self, fixcapitalize);
9960}
9961
9962#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009963PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009964 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009965\n\
9966Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009967normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009968
9969static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009970unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009971{
9972 PyObject *list;
9973 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009974 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009975
Guido van Rossumd57fd912000-03-10 22:53:23 +00009976 /* Split into words */
9977 list = split(self, NULL, -1);
9978 if (!list)
9979 return NULL;
9980
9981 /* Capitalize each word */
9982 for (i = 0; i < PyList_GET_SIZE(list); i++) {
9983 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00009984 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009985 if (item == NULL)
9986 goto onError;
9987 Py_DECREF(PyList_GET_ITEM(list, i));
9988 PyList_SET_ITEM(list, i, item);
9989 }
9990
9991 /* Join the words to form a new string */
9992 item = PyUnicode_Join(NULL, list);
9993
Benjamin Peterson29060642009-01-31 22:14:21 +00009994 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009995 Py_DECREF(list);
9996 return (PyObject *)item;
9997}
9998#endif
9999
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010000/* Argument converter. Coerces to a single unicode character */
10001
10002static int
10003convert_uc(PyObject *obj, void *addr)
10004{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010005 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010006 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010007
Benjamin Peterson14339b62009-01-31 16:36:08 +000010008 uniobj = PyUnicode_FromObject(obj);
10009 if (uniobj == NULL) {
10010 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010011 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010012 return 0;
10013 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010014 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010015 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010016 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010017 Py_DECREF(uniobj);
10018 return 0;
10019 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010020 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010021 Py_DECREF(uniobj);
10022 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010023}
10024
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010025PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010026 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010027\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010028Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010029done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010030
10031static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010032unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010033{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010034 Py_ssize_t marg, left;
10035 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010036 Py_UCS4 fillchar = ' ';
10037
Victor Stinnere9a29352011-10-01 02:14:59 +020010038 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010039 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010040
Victor Stinnere9a29352011-10-01 02:14:59 +020010041 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010042 return NULL;
10043
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010044 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010045 Py_INCREF(self);
10046 return (PyObject*) self;
10047 }
10048
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010049 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010050 left = marg / 2 + (marg & width & 1);
10051
Victor Stinner9310abb2011-10-05 00:59:23 +020010052 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010053}
10054
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010055/* This function assumes that str1 and str2 are readied by the caller. */
10056
Marc-André Lemburge5034372000-08-08 08:04:29 +000010057static int
10058unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
10059{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010060 int kind1, kind2;
10061 void *data1, *data2;
10062 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010063
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010064 kind1 = PyUnicode_KIND(str1);
10065 kind2 = PyUnicode_KIND(str2);
10066 data1 = PyUnicode_DATA(str1);
10067 data2 = PyUnicode_DATA(str2);
10068 len1 = PyUnicode_GET_LENGTH(str1);
10069 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010070
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010071 for (i = 0; i < len1 && i < len2; ++i) {
10072 Py_UCS4 c1, c2;
10073 c1 = PyUnicode_READ(kind1, data1, i);
10074 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010075
10076 if (c1 != c2)
10077 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010078 }
10079
10080 return (len1 < len2) ? -1 : (len1 != len2);
10081}
10082
Alexander Belopolsky40018472011-02-26 01:02:56 +000010083int
10084PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010085{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010086 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10087 if (PyUnicode_READY(left) == -1 ||
10088 PyUnicode_READY(right) == -1)
10089 return -1;
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010090 return unicode_compare((PyUnicodeObject *)left,
10091 (PyUnicodeObject *)right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010092 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010093 PyErr_Format(PyExc_TypeError,
10094 "Can't compare %.100s and %.100s",
10095 left->ob_type->tp_name,
10096 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010097 return -1;
10098}
10099
Martin v. Löwis5b222132007-06-10 09:51:05 +000010100int
10101PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10102{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010103 Py_ssize_t i;
10104 int kind;
10105 void *data;
10106 Py_UCS4 chr;
10107
Victor Stinner910337b2011-10-03 03:20:16 +020010108 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010109 if (PyUnicode_READY(uni) == -1)
10110 return -1;
10111 kind = PyUnicode_KIND(uni);
10112 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010113 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010114 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10115 if (chr != str[i])
10116 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010117 /* This check keeps Python strings that end in '\0' from comparing equal
10118 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010119 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010120 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010121 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010122 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010123 return 0;
10124}
10125
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010126
Benjamin Peterson29060642009-01-31 22:14:21 +000010127#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010128 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010129
Alexander Belopolsky40018472011-02-26 01:02:56 +000010130PyObject *
10131PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010132{
10133 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010134
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010135 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10136 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010137 if (PyUnicode_READY(left) == -1 ||
10138 PyUnicode_READY(right) == -1)
10139 return NULL;
10140 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10141 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010142 if (op == Py_EQ) {
10143 Py_INCREF(Py_False);
10144 return Py_False;
10145 }
10146 if (op == Py_NE) {
10147 Py_INCREF(Py_True);
10148 return Py_True;
10149 }
10150 }
10151 if (left == right)
10152 result = 0;
10153 else
10154 result = unicode_compare((PyUnicodeObject *)left,
10155 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010156
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010157 /* Convert the return value to a Boolean */
10158 switch (op) {
10159 case Py_EQ:
10160 v = TEST_COND(result == 0);
10161 break;
10162 case Py_NE:
10163 v = TEST_COND(result != 0);
10164 break;
10165 case Py_LE:
10166 v = TEST_COND(result <= 0);
10167 break;
10168 case Py_GE:
10169 v = TEST_COND(result >= 0);
10170 break;
10171 case Py_LT:
10172 v = TEST_COND(result == -1);
10173 break;
10174 case Py_GT:
10175 v = TEST_COND(result == 1);
10176 break;
10177 default:
10178 PyErr_BadArgument();
10179 return NULL;
10180 }
10181 Py_INCREF(v);
10182 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010183 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010184
Brian Curtindfc80e32011-08-10 20:28:54 -050010185 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010186}
10187
Alexander Belopolsky40018472011-02-26 01:02:56 +000010188int
10189PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010190{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010191 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010192 int kind1, kind2, kind;
10193 void *buf1, *buf2;
10194 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010195 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010196
10197 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010198 sub = PyUnicode_FromObject(element);
10199 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010200 PyErr_Format(PyExc_TypeError,
10201 "'in <string>' requires string as left operand, not %s",
10202 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010203 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010204 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010205 if (PyUnicode_READY(sub) == -1)
10206 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010207
Thomas Wouters477c8d52006-05-27 19:21:47 +000010208 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010209 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010210 Py_DECREF(sub);
10211 return -1;
10212 }
10213
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010214 kind1 = PyUnicode_KIND(str);
10215 kind2 = PyUnicode_KIND(sub);
10216 kind = kind1 > kind2 ? kind1 : kind2;
10217 buf1 = PyUnicode_DATA(str);
10218 buf2 = PyUnicode_DATA(sub);
10219 if (kind1 != kind)
10220 buf1 = _PyUnicode_AsKind((PyObject*)str, kind);
10221 if (!buf1) {
10222 Py_DECREF(sub);
10223 return -1;
10224 }
10225 if (kind2 != kind)
10226 buf2 = _PyUnicode_AsKind((PyObject*)sub, kind);
10227 if (!buf2) {
10228 Py_DECREF(sub);
10229 if (kind1 != kind) PyMem_Free(buf1);
10230 return -1;
10231 }
10232 len1 = PyUnicode_GET_LENGTH(str);
10233 len2 = PyUnicode_GET_LENGTH(sub);
10234
10235 switch(kind) {
10236 case PyUnicode_1BYTE_KIND:
10237 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10238 break;
10239 case PyUnicode_2BYTE_KIND:
10240 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10241 break;
10242 case PyUnicode_4BYTE_KIND:
10243 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10244 break;
10245 default:
10246 result = -1;
10247 assert(0);
10248 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010249
10250 Py_DECREF(str);
10251 Py_DECREF(sub);
10252
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010253 if (kind1 != kind)
10254 PyMem_Free(buf1);
10255 if (kind2 != kind)
10256 PyMem_Free(buf2);
10257
Guido van Rossum403d68b2000-03-13 15:55:09 +000010258 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010259}
10260
Guido van Rossumd57fd912000-03-10 22:53:23 +000010261/* Concat to string or Unicode object giving a new Unicode object. */
10262
Alexander Belopolsky40018472011-02-26 01:02:56 +000010263PyObject *
10264PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010265{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010266 PyObject *u = NULL, *v = NULL, *w;
10267 Py_UCS4 maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010268
10269 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010270 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010271 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010272 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010273 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010274 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010275 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010276
10277 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010278 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010279 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010280 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010281 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010282 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010283 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010284 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010285 }
10286
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinnerff9e50f2011-09-28 22:17:19 +020010288 maxchar = Py_MAX(maxchar, PyUnicode_MAX_CHAR_VALUE(v));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010289
Guido van Rossumd57fd912000-03-10 22:53:23 +000010290 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010291 w = PyUnicode_New(
10292 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10293 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010294 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010295 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010296 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10297 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010298 Py_DECREF(u);
10299 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010300 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010301 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010302
Benjamin Peterson29060642009-01-31 22:14:21 +000010303 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010304 Py_XDECREF(u);
10305 Py_XDECREF(v);
10306 return NULL;
10307}
10308
Victor Stinnerb0923652011-10-04 01:17:31 +020010309static void
10310unicode_append_inplace(PyObject **p_left, PyObject *right)
10311{
10312 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010313
10314 assert(PyUnicode_IS_READY(*p_left));
10315 assert(PyUnicode_IS_READY(right));
10316
10317 left_len = PyUnicode_GET_LENGTH(*p_left);
10318 right_len = PyUnicode_GET_LENGTH(right);
10319 if (left_len > PY_SSIZE_T_MAX - right_len) {
10320 PyErr_SetString(PyExc_OverflowError,
10321 "strings are too large to concat");
10322 goto error;
10323 }
10324 new_len = left_len + right_len;
10325
10326 /* Now we own the last reference to 'left', so we can resize it
10327 * in-place.
10328 */
10329 if (unicode_resize(p_left, new_len) != 0) {
10330 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10331 * deallocated so it cannot be put back into
10332 * 'variable'. The MemoryError is raised when there
10333 * is no value in 'variable', which might (very
10334 * remotely) be a cause of incompatibilities.
10335 */
10336 goto error;
10337 }
10338 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010339 copy_characters(*p_left, left_len, right, 0, right_len);
10340 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010341 return;
10342
10343error:
10344 Py_DECREF(*p_left);
10345 *p_left = NULL;
10346}
10347
Walter Dörwald1ab83302007-05-18 17:15:44 +000010348void
Victor Stinner23e56682011-10-03 03:54:37 +020010349PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010350{
Victor Stinner23e56682011-10-03 03:54:37 +020010351 PyObject *left, *res;
10352
10353 if (p_left == NULL) {
10354 if (!PyErr_Occurred())
10355 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010356 return;
10357 }
Victor Stinner23e56682011-10-03 03:54:37 +020010358 left = *p_left;
10359 if (right == NULL || !PyUnicode_Check(left)) {
10360 if (!PyErr_Occurred())
10361 PyErr_BadInternalCall();
10362 goto error;
10363 }
10364
Victor Stinnere1335c72011-10-04 20:53:03 +020010365 if (PyUnicode_READY(left))
10366 goto error;
10367 if (PyUnicode_READY(right))
10368 goto error;
10369
Victor Stinner23e56682011-10-03 03:54:37 +020010370 if (PyUnicode_CheckExact(left) && left != unicode_empty
10371 && PyUnicode_CheckExact(right) && right != unicode_empty
10372 && unicode_resizable(left)
10373 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10374 || _PyUnicode_WSTR(left) != NULL))
10375 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010376 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10377 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010378 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010379 not so different than duplicating the string. */
10380 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010381 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010382 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010383 if (p_left != NULL)
10384 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010385 return;
10386 }
10387 }
10388
10389 res = PyUnicode_Concat(left, right);
10390 if (res == NULL)
10391 goto error;
10392 Py_DECREF(left);
10393 *p_left = res;
10394 return;
10395
10396error:
10397 Py_DECREF(*p_left);
10398 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010399}
10400
10401void
10402PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10403{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010404 PyUnicode_Append(pleft, right);
10405 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010406}
10407
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010408PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010409 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010410\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010411Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010412string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010413interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010414
10415static PyObject *
10416unicode_count(PyUnicodeObject *self, PyObject *args)
10417{
10418 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010419 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010420 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010421 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010422 int kind1, kind2, kind;
10423 void *buf1, *buf2;
10424 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010425
Jesus Ceaac451502011-04-20 17:09:23 +020010426 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10427 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010428 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010429
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010430 kind1 = PyUnicode_KIND(self);
10431 kind2 = PyUnicode_KIND(substring);
10432 kind = kind1 > kind2 ? kind1 : kind2;
10433 buf1 = PyUnicode_DATA(self);
10434 buf2 = PyUnicode_DATA(substring);
10435 if (kind1 != kind)
10436 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10437 if (!buf1) {
10438 Py_DECREF(substring);
10439 return NULL;
10440 }
10441 if (kind2 != kind)
10442 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10443 if (!buf2) {
10444 Py_DECREF(substring);
10445 if (kind1 != kind) PyMem_Free(buf1);
10446 return NULL;
10447 }
10448 len1 = PyUnicode_GET_LENGTH(self);
10449 len2 = PyUnicode_GET_LENGTH(substring);
10450
10451 ADJUST_INDICES(start, end, len1);
10452 switch(kind) {
10453 case PyUnicode_1BYTE_KIND:
10454 iresult = ucs1lib_count(
10455 ((Py_UCS1*)buf1) + start, end - start,
10456 buf2, len2, PY_SSIZE_T_MAX
10457 );
10458 break;
10459 case PyUnicode_2BYTE_KIND:
10460 iresult = ucs2lib_count(
10461 ((Py_UCS2*)buf1) + start, end - start,
10462 buf2, len2, PY_SSIZE_T_MAX
10463 );
10464 break;
10465 case PyUnicode_4BYTE_KIND:
10466 iresult = ucs4lib_count(
10467 ((Py_UCS4*)buf1) + start, end - start,
10468 buf2, len2, PY_SSIZE_T_MAX
10469 );
10470 break;
10471 default:
10472 assert(0); iresult = 0;
10473 }
10474
10475 result = PyLong_FromSsize_t(iresult);
10476
10477 if (kind1 != kind)
10478 PyMem_Free(buf1);
10479 if (kind2 != kind)
10480 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010481
10482 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010483
Guido van Rossumd57fd912000-03-10 22:53:23 +000010484 return result;
10485}
10486
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010487PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010488 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010489\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010490Encode S using the codec registered for encoding. Default encoding\n\
10491is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010492handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010493a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10494'xmlcharrefreplace' as well as any other name registered with\n\
10495codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010496
10497static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +000010498unicode_encode(PyUnicodeObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010499{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010500 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010501 char *encoding = NULL;
10502 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010503
Benjamin Peterson308d6372009-09-18 21:42:35 +000010504 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10505 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010506 return NULL;
Georg Brandl3b9406b2010-12-03 07:54:09 +000010507 return PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010508}
10509
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010510PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010511 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010512\n\
10513Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010514If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010515
10516static PyObject*
10517unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
10518{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010519 Py_ssize_t i, j, line_pos, src_len, incr;
10520 Py_UCS4 ch;
10521 PyObject *u;
10522 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010523 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010524 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010525 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010526
10527 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010528 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010529
Antoine Pitrou22425222011-10-04 19:10:51 +020010530 if (PyUnicode_READY(self) == -1)
10531 return NULL;
10532
Thomas Wouters7e474022000-07-16 12:04:32 +000010533 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010534 src_len = PyUnicode_GET_LENGTH(self);
10535 i = j = line_pos = 0;
10536 kind = PyUnicode_KIND(self);
10537 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010538 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010539 for (; i < src_len; i++) {
10540 ch = PyUnicode_READ(kind, src_data, i);
10541 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010542 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010543 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010544 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010545 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010546 goto overflow;
10547 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010548 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010549 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010550 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010551 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010552 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010553 goto overflow;
10554 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010555 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010556 if (ch == '\n' || ch == '\r')
10557 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010558 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010559 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020010560 if (!found && PyUnicode_CheckExact(self)) {
10561 Py_INCREF((PyObject *) self);
10562 return (PyObject *) self;
10563 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010564
Guido van Rossumd57fd912000-03-10 22:53:23 +000010565 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010566 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010567 if (!u)
10568 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010569 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010570
Antoine Pitroue71d5742011-10-04 15:55:09 +020010571 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010572
Antoine Pitroue71d5742011-10-04 15:55:09 +020010573 for (; i < src_len; i++) {
10574 ch = PyUnicode_READ(kind, src_data, i);
10575 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010576 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010577 incr = tabsize - (line_pos % tabsize);
10578 line_pos += incr;
10579 while (incr--) {
10580 PyUnicode_WRITE(kind, dest_data, j, ' ');
10581 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010582 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010583 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010584 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010585 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010586 line_pos++;
10587 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010588 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010589 if (ch == '\n' || ch == '\r')
10590 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010591 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010592 }
10593 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020010594#ifndef DONT_MAKE_RESULT_READY
10595 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010596 Py_DECREF(u);
10597 return NULL;
10598 }
Victor Stinner17efeed2011-10-04 20:05:46 +020010599#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010600 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010601 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010602
Antoine Pitroue71d5742011-10-04 15:55:09 +020010603 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010604 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10605 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010606}
10607
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010608PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010609 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010610\n\
10611Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010612such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010613arguments start and end are interpreted as in slice notation.\n\
10614\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010615Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010616
10617static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010618unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010619{
Jesus Ceaac451502011-04-20 17:09:23 +020010620 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010621 Py_ssize_t start;
10622 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010623 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010624
Jesus Ceaac451502011-04-20 17:09:23 +020010625 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10626 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010627 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010628
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010629 if (PyUnicode_READY(self) == -1)
10630 return NULL;
10631 if (PyUnicode_READY(substring) == -1)
10632 return NULL;
10633
Victor Stinner794d5672011-10-10 03:21:36 +020010634 result = any_find_slice(1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010636 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010637
10638 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010639
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010640 if (result == -2)
10641 return NULL;
10642
Christian Heimes217cfd12007-12-02 14:31:20 +000010643 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010644}
10645
10646static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010647unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010648{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010649 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
10650 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010651 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010652 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010653}
10654
Guido van Rossumc2504932007-09-18 19:42:40 +000010655/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010010656 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000010657static Py_hash_t
Neil Schemenauerf8c37d12007-09-07 20:49:04 +000010658unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010659{
Guido van Rossumc2504932007-09-18 19:42:40 +000010660 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010010661 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010662
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010663 if (_PyUnicode_HASH(self) != -1)
10664 return _PyUnicode_HASH(self);
10665 if (PyUnicode_READY(self) == -1)
10666 return -1;
10667 len = PyUnicode_GET_LENGTH(self);
10668
10669 /* The hash function as a macro, gets expanded three times below. */
10670#define HASH(P) \
10671 x = (Py_uhash_t)*P << 7; \
10672 while (--len >= 0) \
10673 x = (1000003*x) ^ (Py_uhash_t)*P++;
10674
10675 switch (PyUnicode_KIND(self)) {
10676 case PyUnicode_1BYTE_KIND: {
10677 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
10678 HASH(c);
10679 break;
10680 }
10681 case PyUnicode_2BYTE_KIND: {
10682 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
10683 HASH(s);
10684 break;
10685 }
10686 default: {
10687 Py_UCS4 *l;
10688 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
10689 "Impossible switch case in unicode_hash");
10690 l = PyUnicode_4BYTE_DATA(self);
10691 HASH(l);
10692 break;
10693 }
10694 }
10695 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
10696
Guido van Rossumc2504932007-09-18 19:42:40 +000010697 if (x == -1)
10698 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010699 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010700 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010701}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010702#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000010703
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010704PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010705 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010706\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010707Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010708
10709static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010710unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010711{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010712 Py_ssize_t result;
Jesus Ceaac451502011-04-20 17:09:23 +020010713 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010714 Py_ssize_t start;
10715 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010716
Jesus Ceaac451502011-04-20 17:09:23 +020010717 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
10718 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010719 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010720
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010721 if (PyUnicode_READY(self) == -1)
10722 return NULL;
10723 if (PyUnicode_READY(substring) == -1)
10724 return NULL;
10725
Victor Stinner794d5672011-10-10 03:21:36 +020010726 result = any_find_slice(1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010727 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010728 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010729
10730 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010731
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010732 if (result == -2)
10733 return NULL;
10734
Guido van Rossumd57fd912000-03-10 22:53:23 +000010735 if (result < 0) {
10736 PyErr_SetString(PyExc_ValueError, "substring not found");
10737 return NULL;
10738 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010739
Christian Heimes217cfd12007-12-02 14:31:20 +000010740 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010741}
10742
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010743PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010744 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010745\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010746Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010747at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010748
10749static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010750unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010751{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010752 Py_ssize_t i, length;
10753 int kind;
10754 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010755 int cased;
10756
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010757 if (PyUnicode_READY(self) == -1)
10758 return NULL;
10759 length = PyUnicode_GET_LENGTH(self);
10760 kind = PyUnicode_KIND(self);
10761 data = PyUnicode_DATA(self);
10762
Guido van Rossumd57fd912000-03-10 22:53:23 +000010763 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010764 if (length == 1)
10765 return PyBool_FromLong(
10766 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010767
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010768 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010769 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010770 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010771
Guido van Rossumd57fd912000-03-10 22:53:23 +000010772 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010773 for (i = 0; i < length; i++) {
10774 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010775
Benjamin Peterson29060642009-01-31 22:14:21 +000010776 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
10777 return PyBool_FromLong(0);
10778 else if (!cased && Py_UNICODE_ISLOWER(ch))
10779 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010780 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010781 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010782}
10783
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010784PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010785 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010786\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010787Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010788at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010789
10790static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010791unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010792{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010793 Py_ssize_t i, length;
10794 int kind;
10795 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010796 int cased;
10797
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010798 if (PyUnicode_READY(self) == -1)
10799 return NULL;
10800 length = PyUnicode_GET_LENGTH(self);
10801 kind = PyUnicode_KIND(self);
10802 data = PyUnicode_DATA(self);
10803
Guido van Rossumd57fd912000-03-10 22:53:23 +000010804 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010805 if (length == 1)
10806 return PyBool_FromLong(
10807 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010808
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010809 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010810 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010811 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010812
Guido van Rossumd57fd912000-03-10 22:53:23 +000010813 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010814 for (i = 0; i < length; i++) {
10815 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010816
Benjamin Peterson29060642009-01-31 22:14:21 +000010817 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
10818 return PyBool_FromLong(0);
10819 else if (!cased && Py_UNICODE_ISUPPER(ch))
10820 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010821 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010822 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010823}
10824
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010825PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010826 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010827\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010828Return True if S is a titlecased string and there is at least one\n\
10829character in S, i.e. upper- and titlecase characters may only\n\
10830follow uncased characters and lowercase characters only cased ones.\n\
10831Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010832
10833static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010834unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010835{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010836 Py_ssize_t i, length;
10837 int kind;
10838 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010839 int cased, previous_is_cased;
10840
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010841 if (PyUnicode_READY(self) == -1)
10842 return NULL;
10843 length = PyUnicode_GET_LENGTH(self);
10844 kind = PyUnicode_KIND(self);
10845 data = PyUnicode_DATA(self);
10846
Guido van Rossumd57fd912000-03-10 22:53:23 +000010847 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010848 if (length == 1) {
10849 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10850 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
10851 (Py_UNICODE_ISUPPER(ch) != 0));
10852 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010853
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010854 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010855 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010856 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010857
Guido van Rossumd57fd912000-03-10 22:53:23 +000010858 cased = 0;
10859 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010860 for (i = 0; i < length; i++) {
10861 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010862
Benjamin Peterson29060642009-01-31 22:14:21 +000010863 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
10864 if (previous_is_cased)
10865 return PyBool_FromLong(0);
10866 previous_is_cased = 1;
10867 cased = 1;
10868 }
10869 else if (Py_UNICODE_ISLOWER(ch)) {
10870 if (!previous_is_cased)
10871 return PyBool_FromLong(0);
10872 previous_is_cased = 1;
10873 cased = 1;
10874 }
10875 else
10876 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010877 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010878 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010879}
10880
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010881PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010882 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010883\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010884Return True if all characters in S are whitespace\n\
10885and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010886
10887static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010888unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010889{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010890 Py_ssize_t i, length;
10891 int kind;
10892 void *data;
10893
10894 if (PyUnicode_READY(self) == -1)
10895 return NULL;
10896 length = PyUnicode_GET_LENGTH(self);
10897 kind = PyUnicode_KIND(self);
10898 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010899
Guido van Rossumd57fd912000-03-10 22:53:23 +000010900 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010901 if (length == 1)
10902 return PyBool_FromLong(
10903 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010904
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010905 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010906 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010907 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010908
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010909 for (i = 0; i < length; i++) {
10910 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010911 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000010912 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010913 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010914 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010915}
10916
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010917PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010918 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010919\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010920Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010921and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010922
10923static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010924unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010925{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010926 Py_ssize_t i, length;
10927 int kind;
10928 void *data;
10929
10930 if (PyUnicode_READY(self) == -1)
10931 return NULL;
10932 length = PyUnicode_GET_LENGTH(self);
10933 kind = PyUnicode_KIND(self);
10934 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010935
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010936 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010937 if (length == 1)
10938 return PyBool_FromLong(
10939 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010940
10941 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010942 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010943 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010944
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010945 for (i = 0; i < length; i++) {
10946 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010947 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010948 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010949 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010950}
10951
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010952PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010953 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010954\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010955Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010956and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010957
10958static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010959unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010960{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010961 int kind;
10962 void *data;
10963 Py_ssize_t len, i;
10964
10965 if (PyUnicode_READY(self) == -1)
10966 return NULL;
10967
10968 kind = PyUnicode_KIND(self);
10969 data = PyUnicode_DATA(self);
10970 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010971
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010972 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010973 if (len == 1) {
10974 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10975 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
10976 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010977
10978 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010979 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010980 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010981
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010982 for (i = 0; i < len; i++) {
10983 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010984 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000010985 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010986 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010987 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010988}
10989
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010990PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010991 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010992\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010993Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010994False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010995
10996static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010997unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010998{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010999 Py_ssize_t i, length;
11000 int kind;
11001 void *data;
11002
11003 if (PyUnicode_READY(self) == -1)
11004 return NULL;
11005 length = PyUnicode_GET_LENGTH(self);
11006 kind = PyUnicode_KIND(self);
11007 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011008
Guido van Rossumd57fd912000-03-10 22:53:23 +000011009 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011010 if (length == 1)
11011 return PyBool_FromLong(
11012 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011013
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011014 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011015 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011016 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011017
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011018 for (i = 0; i < length; i++) {
11019 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011020 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011021 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011022 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011023}
11024
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011025PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011026 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011027\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011028Return True if all characters in S are digits\n\
11029and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011030
11031static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011032unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011033{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011034 Py_ssize_t i, length;
11035 int kind;
11036 void *data;
11037
11038 if (PyUnicode_READY(self) == -1)
11039 return NULL;
11040 length = PyUnicode_GET_LENGTH(self);
11041 kind = PyUnicode_KIND(self);
11042 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011043
Guido van Rossumd57fd912000-03-10 22:53:23 +000011044 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011045 if (length == 1) {
11046 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11047 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11048 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011049
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011050 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011051 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011052 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011053
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011054 for (i = 0; i < length; i++) {
11055 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011056 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011057 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011058 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011059}
11060
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011061PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011062 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011063\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011064Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011065False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011066
11067static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011068unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011069{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011070 Py_ssize_t i, length;
11071 int kind;
11072 void *data;
11073
11074 if (PyUnicode_READY(self) == -1)
11075 return NULL;
11076 length = PyUnicode_GET_LENGTH(self);
11077 kind = PyUnicode_KIND(self);
11078 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011079
Guido van Rossumd57fd912000-03-10 22:53:23 +000011080 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011081 if (length == 1)
11082 return PyBool_FromLong(
11083 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011084
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011085 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011086 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011087 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011088
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011089 for (i = 0; i < length; i++) {
11090 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011091 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011092 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011093 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011094}
11095
Martin v. Löwis47383402007-08-15 07:32:56 +000011096int
11097PyUnicode_IsIdentifier(PyObject *self)
11098{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011099 int kind;
11100 void *data;
11101 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011102 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011103
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011104 if (PyUnicode_READY(self) == -1) {
11105 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011106 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011107 }
11108
11109 /* Special case for empty strings */
11110 if (PyUnicode_GET_LENGTH(self) == 0)
11111 return 0;
11112 kind = PyUnicode_KIND(self);
11113 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011114
11115 /* PEP 3131 says that the first character must be in
11116 XID_Start and subsequent characters in XID_Continue,
11117 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011118 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011119 letters, digits, underscore). However, given the current
11120 definition of XID_Start and XID_Continue, it is sufficient
11121 to check just for these, except that _ must be allowed
11122 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011123 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011124 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011125 return 0;
11126
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011127 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011128 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011129 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011130 return 1;
11131}
11132
11133PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011134 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011135\n\
11136Return True if S is a valid identifier according\n\
11137to the language definition.");
11138
11139static PyObject*
11140unicode_isidentifier(PyObject *self)
11141{
11142 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11143}
11144
Georg Brandl559e5d72008-06-11 18:37:52 +000011145PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011146 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011147\n\
11148Return True if all characters in S are considered\n\
11149printable in repr() or S is empty, False otherwise.");
11150
11151static PyObject*
11152unicode_isprintable(PyObject *self)
11153{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011154 Py_ssize_t i, length;
11155 int kind;
11156 void *data;
11157
11158 if (PyUnicode_READY(self) == -1)
11159 return NULL;
11160 length = PyUnicode_GET_LENGTH(self);
11161 kind = PyUnicode_KIND(self);
11162 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011163
11164 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011165 if (length == 1)
11166 return PyBool_FromLong(
11167 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011168
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011169 for (i = 0; i < length; i++) {
11170 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011171 Py_RETURN_FALSE;
11172 }
11173 }
11174 Py_RETURN_TRUE;
11175}
11176
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011177PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011178 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011179\n\
11180Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011181iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011182
11183static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011184unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011185{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011186 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011187}
11188
Martin v. Löwis18e16552006-02-15 17:27:45 +000011189static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +000011190unicode_length(PyUnicodeObject *self)
11191{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011192 if (PyUnicode_READY(self) == -1)
11193 return -1;
11194 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195}
11196
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011197PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011198 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011199\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011200Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011201done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011202
11203static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011204unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011205{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011206 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011207 Py_UCS4 fillchar = ' ';
11208
11209 if (PyUnicode_READY(self) == -1)
11210 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011211
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011212 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011213 return NULL;
11214
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011215 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011216 Py_INCREF(self);
11217 return (PyObject*) self;
11218 }
11219
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011220 return (PyObject*) pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011221}
11222
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011223PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011224 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011226Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011227
11228static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011229unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011230{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011231 return fixup(self, fixlower);
11232}
11233
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011234#define LEFTSTRIP 0
11235#define RIGHTSTRIP 1
11236#define BOTHSTRIP 2
11237
11238/* Arrays indexed by above */
11239static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11240
11241#define STRIPNAME(i) (stripformat[i]+3)
11242
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011243/* externally visible for str.strip(unicode) */
11244PyObject *
11245_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
11246{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011247 void *data;
11248 int kind;
11249 Py_ssize_t i, j, len;
11250 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011251
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011252 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11253 return NULL;
11254
11255 kind = PyUnicode_KIND(self);
11256 data = PyUnicode_DATA(self);
11257 len = PyUnicode_GET_LENGTH(self);
11258 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11259 PyUnicode_DATA(sepobj),
11260 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011261
Benjamin Peterson14339b62009-01-31 16:36:08 +000011262 i = 0;
11263 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011264 while (i < len &&
11265 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011266 i++;
11267 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011268 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011269
Benjamin Peterson14339b62009-01-31 16:36:08 +000011270 j = len;
11271 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011272 do {
11273 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011274 } while (j >= i &&
11275 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011276 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011277 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011278
Victor Stinner12bab6d2011-10-01 01:53:49 +020011279 return PyUnicode_Substring((PyObject*)self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011280}
11281
11282PyObject*
11283PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11284{
11285 unsigned char *data;
11286 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011287 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011288
Victor Stinnerde636f32011-10-01 03:55:54 +020011289 if (PyUnicode_READY(self) == -1)
11290 return NULL;
11291
11292 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11293
Victor Stinner12bab6d2011-10-01 01:53:49 +020011294 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011295 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011296 if (PyUnicode_CheckExact(self)) {
11297 Py_INCREF(self);
11298 return self;
11299 }
11300 else
11301 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011302 }
11303
Victor Stinner12bab6d2011-10-01 01:53:49 +020011304 length = end - start;
11305 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011306 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011307
Victor Stinnerde636f32011-10-01 03:55:54 +020011308 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011309 PyErr_SetString(PyExc_IndexError, "string index out of range");
11310 return NULL;
11311 }
11312
Victor Stinnerb9275c12011-10-05 14:01:42 +020011313 if (PyUnicode_IS_ASCII(self)) {
11314 kind = PyUnicode_KIND(self);
11315 data = PyUnicode_1BYTE_DATA(self);
11316 return unicode_fromascii(data + start, length);
11317 }
11318 else {
11319 kind = PyUnicode_KIND(self);
11320 data = PyUnicode_1BYTE_DATA(self);
11321 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011322 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011323 length);
11324 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011325}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011326
11327static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011328do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011329{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011330 int kind;
11331 void *data;
11332 Py_ssize_t len, i, j;
11333
11334 if (PyUnicode_READY(self) == -1)
11335 return NULL;
11336
11337 kind = PyUnicode_KIND(self);
11338 data = PyUnicode_DATA(self);
11339 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011340
Benjamin Peterson14339b62009-01-31 16:36:08 +000011341 i = 0;
11342 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011343 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011344 i++;
11345 }
11346 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011347
Benjamin Peterson14339b62009-01-31 16:36:08 +000011348 j = len;
11349 if (striptype != LEFTSTRIP) {
11350 do {
11351 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011352 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011353 j++;
11354 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011355
Victor Stinner12bab6d2011-10-01 01:53:49 +020011356 return PyUnicode_Substring((PyObject*)self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011357}
11358
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011359
11360static PyObject *
11361do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
11362{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011363 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011364
Benjamin Peterson14339b62009-01-31 16:36:08 +000011365 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11366 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011367
Benjamin Peterson14339b62009-01-31 16:36:08 +000011368 if (sep != NULL && sep != Py_None) {
11369 if (PyUnicode_Check(sep))
11370 return _PyUnicode_XStrip(self, striptype, sep);
11371 else {
11372 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011373 "%s arg must be None or str",
11374 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011375 return NULL;
11376 }
11377 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011378
Benjamin Peterson14339b62009-01-31 16:36:08 +000011379 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011380}
11381
11382
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011383PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011384 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011385\n\
11386Return a copy of the string S with leading and trailing\n\
11387whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011388If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011389
11390static PyObject *
11391unicode_strip(PyUnicodeObject *self, PyObject *args)
11392{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011393 if (PyTuple_GET_SIZE(args) == 0)
11394 return do_strip(self, BOTHSTRIP); /* Common case */
11395 else
11396 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011397}
11398
11399
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011400PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011401 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011402\n\
11403Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011404If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011405
11406static PyObject *
11407unicode_lstrip(PyUnicodeObject *self, PyObject *args)
11408{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011409 if (PyTuple_GET_SIZE(args) == 0)
11410 return do_strip(self, LEFTSTRIP); /* Common case */
11411 else
11412 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011413}
11414
11415
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011416PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011417 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011418\n\
11419Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011420If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011421
11422static PyObject *
11423unicode_rstrip(PyUnicodeObject *self, PyObject *args)
11424{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011425 if (PyTuple_GET_SIZE(args) == 0)
11426 return do_strip(self, RIGHTSTRIP); /* Common case */
11427 else
11428 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011429}
11430
11431
Guido van Rossumd57fd912000-03-10 22:53:23 +000011432static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +000011433unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011434{
11435 PyUnicodeObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011436 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437
Georg Brandl222de0f2009-04-12 12:01:50 +000011438 if (len < 1) {
11439 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011440 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011441 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011442
Tim Peters7a29bd52001-09-12 03:03:31 +000011443 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011444 /* no repeat, return original string */
11445 Py_INCREF(str);
11446 return (PyObject*) str;
11447 }
Tim Peters8f422462000-09-09 06:13:41 +000011448
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011449 if (PyUnicode_READY(str) == -1)
11450 return NULL;
11451
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011452 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011453 PyErr_SetString(PyExc_OverflowError,
11454 "repeated string is too long");
11455 return NULL;
11456 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011457 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011459 u = (PyUnicodeObject *)PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011460 if (!u)
11461 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011462 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011463
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011464 if (PyUnicode_GET_LENGTH(str) == 1) {
11465 const int kind = PyUnicode_KIND(str);
11466 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11467 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011468 if (kind == PyUnicode_1BYTE_KIND)
11469 memset(to, (unsigned char)fill_char, len);
11470 else {
11471 for (n = 0; n < len; ++n)
11472 PyUnicode_WRITE(kind, to, n, fill_char);
11473 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011474 }
11475 else {
11476 /* number of characters copied this far */
11477 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011478 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011479 char *to = (char *) PyUnicode_DATA(u);
11480 Py_MEMCPY(to, PyUnicode_DATA(str),
11481 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011482 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011483 n = (done <= nchars-done) ? done : nchars-done;
11484 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011485 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011486 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011487 }
11488
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011489 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011490 return (PyObject*) u;
11491}
11492
Alexander Belopolsky40018472011-02-26 01:02:56 +000011493PyObject *
11494PyUnicode_Replace(PyObject *obj,
11495 PyObject *subobj,
11496 PyObject *replobj,
11497 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498{
11499 PyObject *self;
11500 PyObject *str1;
11501 PyObject *str2;
11502 PyObject *result;
11503
11504 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011505 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011506 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011507 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011508 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011509 Py_DECREF(self);
11510 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011511 }
11512 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011513 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011514 Py_DECREF(self);
11515 Py_DECREF(str1);
11516 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011517 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011518 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011519 Py_DECREF(self);
11520 Py_DECREF(str1);
11521 Py_DECREF(str2);
11522 return result;
11523}
11524
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011525PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011526 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011527\n\
11528Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011529old replaced by new. If the optional argument count is\n\
11530given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011531
11532static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011533unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011534{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011535 PyObject *str1;
11536 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011537 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011538 PyObject *result;
11539
Martin v. Löwis18e16552006-02-15 17:27:45 +000011540 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011541 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011542 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011543 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011544 str1 = PyUnicode_FromObject(str1);
11545 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11546 return NULL;
11547 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011548 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011549 Py_DECREF(str1);
11550 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011551 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011552
11553 result = replace(self, str1, str2, maxcount);
11554
11555 Py_DECREF(str1);
11556 Py_DECREF(str2);
11557 return result;
11558}
11559
Alexander Belopolsky40018472011-02-26 01:02:56 +000011560static PyObject *
11561unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011562{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011563 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011564 Py_ssize_t isize;
11565 Py_ssize_t osize, squote, dquote, i, o;
11566 Py_UCS4 max, quote;
11567 int ikind, okind;
11568 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011569
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011570 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011571 return NULL;
11572
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011573 isize = PyUnicode_GET_LENGTH(unicode);
11574 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011575
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011576 /* Compute length of output, quote characters, and
11577 maximum character */
11578 osize = 2; /* quotes */
11579 max = 127;
11580 squote = dquote = 0;
11581 ikind = PyUnicode_KIND(unicode);
11582 for (i = 0; i < isize; i++) {
11583 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11584 switch (ch) {
11585 case '\'': squote++; osize++; break;
11586 case '"': dquote++; osize++; break;
11587 case '\\': case '\t': case '\r': case '\n':
11588 osize += 2; break;
11589 default:
11590 /* Fast-path ASCII */
11591 if (ch < ' ' || ch == 0x7f)
11592 osize += 4; /* \xHH */
11593 else if (ch < 0x7f)
11594 osize++;
11595 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11596 osize++;
11597 max = ch > max ? ch : max;
11598 }
11599 else if (ch < 0x100)
11600 osize += 4; /* \xHH */
11601 else if (ch < 0x10000)
11602 osize += 6; /* \uHHHH */
11603 else
11604 osize += 10; /* \uHHHHHHHH */
11605 }
11606 }
11607
11608 quote = '\'';
11609 if (squote) {
11610 if (dquote)
11611 /* Both squote and dquote present. Use squote,
11612 and escape them */
11613 osize += squote;
11614 else
11615 quote = '"';
11616 }
11617
11618 repr = PyUnicode_New(osize, max);
11619 if (repr == NULL)
11620 return NULL;
11621 okind = PyUnicode_KIND(repr);
11622 odata = PyUnicode_DATA(repr);
11623
11624 PyUnicode_WRITE(okind, odata, 0, quote);
11625 PyUnicode_WRITE(okind, odata, osize-1, quote);
11626
11627 for (i = 0, o = 1; i < isize; i++) {
11628 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011629
11630 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011631 if ((ch == quote) || (ch == '\\')) {
11632 PyUnicode_WRITE(okind, odata, o++, '\\');
11633 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011634 continue;
11635 }
11636
Benjamin Peterson29060642009-01-31 22:14:21 +000011637 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011638 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011639 PyUnicode_WRITE(okind, odata, o++, '\\');
11640 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011641 }
11642 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011643 PyUnicode_WRITE(okind, odata, o++, '\\');
11644 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011645 }
11646 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011647 PyUnicode_WRITE(okind, odata, o++, '\\');
11648 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011649 }
11650
11651 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011652 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011653 PyUnicode_WRITE(okind, odata, o++, '\\');
11654 PyUnicode_WRITE(okind, odata, o++, 'x');
11655 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
11656 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011657 }
11658
Georg Brandl559e5d72008-06-11 18:37:52 +000011659 /* Copy ASCII characters as-is */
11660 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011661 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011662 }
11663
Benjamin Peterson29060642009-01-31 22:14:21 +000011664 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000011665 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011666 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000011667 (categories Z* and C* except ASCII space)
11668 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011669 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011670 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011671 if (ch <= 0xff) {
11672 PyUnicode_WRITE(okind, odata, o++, '\\');
11673 PyUnicode_WRITE(okind, odata, o++, 'x');
11674 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
11675 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011676 }
11677 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011678 else if (ch >= 0x10000) {
11679 PyUnicode_WRITE(okind, odata, o++, '\\');
11680 PyUnicode_WRITE(okind, odata, o++, 'U');
11681 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 28) & 0xF]);
11682 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 24) & 0xF]);
11683 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 20) & 0xF]);
11684 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 16) & 0xF]);
11685 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
11686 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
11687 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
11688 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011689 }
11690 /* Map 16-bit characters to '\uxxxx' */
11691 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011692 PyUnicode_WRITE(okind, odata, o++, '\\');
11693 PyUnicode_WRITE(okind, odata, o++, 'u');
11694 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
11695 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
11696 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
11697 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011698 }
11699 }
11700 /* Copy characters as-is */
11701 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011702 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011703 }
11704 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000011705 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011706 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020011707 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000011708 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011709}
11710
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011711PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011712 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011713\n\
11714Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011715such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011716arguments start and end are interpreted as in slice notation.\n\
11717\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011718Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011719
11720static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011721unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011722{
Jesus Ceaac451502011-04-20 17:09:23 +020011723 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011724 Py_ssize_t start;
11725 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011726 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011727
Jesus Ceaac451502011-04-20 17:09:23 +020011728 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
11729 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000011730 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011731
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011732 if (PyUnicode_READY(self) == -1)
11733 return NULL;
11734 if (PyUnicode_READY(substring) == -1)
11735 return NULL;
11736
Victor Stinner794d5672011-10-10 03:21:36 +020011737 result = any_find_slice(-1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011738 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011739 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011740
11741 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011742
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011743 if (result == -2)
11744 return NULL;
11745
Christian Heimes217cfd12007-12-02 14:31:20 +000011746 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011747}
11748
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011749PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011750 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011751\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011752Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011753
11754static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011755unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011756{
Jesus Ceaac451502011-04-20 17:09:23 +020011757 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011758 Py_ssize_t start;
11759 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011760 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011761
Jesus Ceaac451502011-04-20 17:09:23 +020011762 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
11763 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000011764 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011765
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011766 if (PyUnicode_READY(self) == -1)
11767 return NULL;
11768 if (PyUnicode_READY(substring) == -1)
11769 return NULL;
11770
Victor Stinner794d5672011-10-10 03:21:36 +020011771 result = any_find_slice(-1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011772 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011773 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774
11775 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011776
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011777 if (result == -2)
11778 return NULL;
11779
Guido van Rossumd57fd912000-03-10 22:53:23 +000011780 if (result < 0) {
11781 PyErr_SetString(PyExc_ValueError, "substring not found");
11782 return NULL;
11783 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011784
Christian Heimes217cfd12007-12-02 14:31:20 +000011785 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011786}
11787
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011788PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011789 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011790\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011791Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011792done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011793
11794static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011795unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011796{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011797 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011798 Py_UCS4 fillchar = ' ';
11799
Victor Stinnere9a29352011-10-01 02:14:59 +020011800 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011801 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011802
Victor Stinnere9a29352011-10-01 02:14:59 +020011803 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011804 return NULL;
11805
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011806 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011807 Py_INCREF(self);
11808 return (PyObject*) self;
11809 }
11810
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011811 return (PyObject*) pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011812}
11813
Alexander Belopolsky40018472011-02-26 01:02:56 +000011814PyObject *
11815PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011816{
11817 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000011818
Guido van Rossumd57fd912000-03-10 22:53:23 +000011819 s = PyUnicode_FromObject(s);
11820 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000011821 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000011822 if (sep != NULL) {
11823 sep = PyUnicode_FromObject(sep);
11824 if (sep == NULL) {
11825 Py_DECREF(s);
11826 return NULL;
11827 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011828 }
11829
Victor Stinner9310abb2011-10-05 00:59:23 +020011830 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011831
11832 Py_DECREF(s);
11833 Py_XDECREF(sep);
11834 return result;
11835}
11836
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011837PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011838 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011839\n\
11840Return a list of the words in S, using sep as the\n\
11841delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000011842splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000011843whitespace string is a separator and empty strings are\n\
11844removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011845
11846static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011847unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011848{
11849 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011850 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011851
Martin v. Löwis18e16552006-02-15 17:27:45 +000011852 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011853 return NULL;
11854
11855 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000011856 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011857 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020011858 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011859 else
Benjamin Peterson29060642009-01-31 22:14:21 +000011860 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011861}
11862
Thomas Wouters477c8d52006-05-27 19:21:47 +000011863PyObject *
11864PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
11865{
11866 PyObject* str_obj;
11867 PyObject* sep_obj;
11868 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011869 int kind1, kind2, kind;
11870 void *buf1 = NULL, *buf2 = NULL;
11871 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011872
11873 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020011874 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011875 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011876 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011877 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000011878 Py_DECREF(str_obj);
11879 return NULL;
11880 }
11881
Victor Stinner14f8f022011-10-05 20:58:25 +020011882 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011883 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020011884 kind = Py_MAX(kind1, kind2);
11885 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011886 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020011887 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011888 if (!buf1)
11889 goto onError;
11890 buf2 = PyUnicode_DATA(sep_obj);
11891 if (kind2 != kind)
11892 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11893 if (!buf2)
11894 goto onError;
11895 len1 = PyUnicode_GET_LENGTH(str_obj);
11896 len2 = PyUnicode_GET_LENGTH(sep_obj);
11897
Victor Stinner14f8f022011-10-05 20:58:25 +020011898 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011899 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020011900 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
11901 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11902 else
11903 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011904 break;
11905 case PyUnicode_2BYTE_KIND:
11906 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11907 break;
11908 case PyUnicode_4BYTE_KIND:
11909 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11910 break;
11911 default:
11912 assert(0);
11913 out = 0;
11914 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011915
11916 Py_DECREF(sep_obj);
11917 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011918 if (kind1 != kind)
11919 PyMem_Free(buf1);
11920 if (kind2 != kind)
11921 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011922
11923 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011924 onError:
11925 Py_DECREF(sep_obj);
11926 Py_DECREF(str_obj);
11927 if (kind1 != kind && buf1)
11928 PyMem_Free(buf1);
11929 if (kind2 != kind && buf2)
11930 PyMem_Free(buf2);
11931 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011932}
11933
11934
11935PyObject *
11936PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
11937{
11938 PyObject* str_obj;
11939 PyObject* sep_obj;
11940 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011941 int kind1, kind2, kind;
11942 void *buf1 = NULL, *buf2 = NULL;
11943 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011944
11945 str_obj = PyUnicode_FromObject(str_in);
11946 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000011947 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011948 sep_obj = PyUnicode_FromObject(sep_in);
11949 if (!sep_obj) {
11950 Py_DECREF(str_obj);
11951 return NULL;
11952 }
11953
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011954 kind1 = PyUnicode_KIND(str_in);
11955 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020011956 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011957 buf1 = PyUnicode_DATA(str_in);
11958 if (kind1 != kind)
11959 buf1 = _PyUnicode_AsKind(str_in, kind);
11960 if (!buf1)
11961 goto onError;
11962 buf2 = PyUnicode_DATA(sep_obj);
11963 if (kind2 != kind)
11964 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11965 if (!buf2)
11966 goto onError;
11967 len1 = PyUnicode_GET_LENGTH(str_obj);
11968 len2 = PyUnicode_GET_LENGTH(sep_obj);
11969
11970 switch(PyUnicode_KIND(str_in)) {
11971 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020011972 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
11973 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11974 else
11975 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011976 break;
11977 case PyUnicode_2BYTE_KIND:
11978 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11979 break;
11980 case PyUnicode_4BYTE_KIND:
11981 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11982 break;
11983 default:
11984 assert(0);
11985 out = 0;
11986 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011987
11988 Py_DECREF(sep_obj);
11989 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011990 if (kind1 != kind)
11991 PyMem_Free(buf1);
11992 if (kind2 != kind)
11993 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011994
11995 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011996 onError:
11997 Py_DECREF(sep_obj);
11998 Py_DECREF(str_obj);
11999 if (kind1 != kind && buf1)
12000 PyMem_Free(buf1);
12001 if (kind2 != kind && buf2)
12002 PyMem_Free(buf2);
12003 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012004}
12005
12006PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012007 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012008\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012009Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012010the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012011found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012012
12013static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012014unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012015{
Victor Stinner9310abb2011-10-05 00:59:23 +020012016 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012017}
12018
12019PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012020 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012021\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012022Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012023the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012024separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012025
12026static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012027unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012028{
Victor Stinner9310abb2011-10-05 00:59:23 +020012029 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012030}
12031
Alexander Belopolsky40018472011-02-26 01:02:56 +000012032PyObject *
12033PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012034{
12035 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012036
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012037 s = PyUnicode_FromObject(s);
12038 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012039 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012040 if (sep != NULL) {
12041 sep = PyUnicode_FromObject(sep);
12042 if (sep == NULL) {
12043 Py_DECREF(s);
12044 return NULL;
12045 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012046 }
12047
Victor Stinner9310abb2011-10-05 00:59:23 +020012048 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012049
12050 Py_DECREF(s);
12051 Py_XDECREF(sep);
12052 return result;
12053}
12054
12055PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012056 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012057\n\
12058Return a list of the words in S, using sep as the\n\
12059delimiter string, starting at the end of the string and\n\
12060working to the front. If maxsplit is given, at most maxsplit\n\
12061splits are done. If sep is not specified, any whitespace string\n\
12062is a separator.");
12063
12064static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012065unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012066{
12067 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012068 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012069
Martin v. Löwis18e16552006-02-15 17:27:45 +000012070 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012071 return NULL;
12072
12073 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012074 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012075 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012076 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012077 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012078 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012079}
12080
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012081PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012082 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012083\n\
12084Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012085Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012086is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012087
12088static PyObject*
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012089unicode_splitlines(PyUnicodeObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012090{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012091 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012092 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012093
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012094 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12095 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012096 return NULL;
12097
Guido van Rossum86662912000-04-11 15:38:46 +000012098 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012099}
12100
12101static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012102PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012103{
Walter Dörwald346737f2007-05-31 10:44:43 +000012104 if (PyUnicode_CheckExact(self)) {
12105 Py_INCREF(self);
12106 return self;
12107 } else
12108 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012109 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012110}
12111
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012112PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012113 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012114\n\
12115Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012116and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012117
12118static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012119unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012120{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012121 return fixup(self, fixswapcase);
12122}
12123
Georg Brandlceee0772007-11-27 23:48:05 +000012124PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012125 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012126\n\
12127Return a translation table usable for str.translate().\n\
12128If there is only one argument, it must be a dictionary mapping Unicode\n\
12129ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012130Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012131If there are two arguments, they must be strings of equal length, and\n\
12132in the resulting dictionary, each character in x will be mapped to the\n\
12133character at the same position in y. If there is a third argument, it\n\
12134must be a string, whose characters will be mapped to None in the result.");
12135
12136static PyObject*
12137unicode_maketrans(PyUnicodeObject *null, PyObject *args)
12138{
12139 PyObject *x, *y = NULL, *z = NULL;
12140 PyObject *new = NULL, *key, *value;
12141 Py_ssize_t i = 0;
12142 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012143
Georg Brandlceee0772007-11-27 23:48:05 +000012144 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12145 return NULL;
12146 new = PyDict_New();
12147 if (!new)
12148 return NULL;
12149 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012150 int x_kind, y_kind, z_kind;
12151 void *x_data, *y_data, *z_data;
12152
Georg Brandlceee0772007-11-27 23:48:05 +000012153 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012154 if (!PyUnicode_Check(x)) {
12155 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12156 "be a string if there is a second argument");
12157 goto err;
12158 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012159 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012160 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12161 "arguments must have equal length");
12162 goto err;
12163 }
12164 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012165 x_kind = PyUnicode_KIND(x);
12166 y_kind = PyUnicode_KIND(y);
12167 x_data = PyUnicode_DATA(x);
12168 y_data = PyUnicode_DATA(y);
12169 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12170 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12171 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012172 if (!key || !value)
12173 goto err;
12174 res = PyDict_SetItem(new, key, value);
12175 Py_DECREF(key);
12176 Py_DECREF(value);
12177 if (res < 0)
12178 goto err;
12179 }
12180 /* create entries for deleting chars in z */
12181 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012182 z_kind = PyUnicode_KIND(z);
12183 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012184 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012185 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012186 if (!key)
12187 goto err;
12188 res = PyDict_SetItem(new, key, Py_None);
12189 Py_DECREF(key);
12190 if (res < 0)
12191 goto err;
12192 }
12193 }
12194 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012195 int kind;
12196 void *data;
12197
Georg Brandlceee0772007-11-27 23:48:05 +000012198 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012199 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012200 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12201 "to maketrans it must be a dict");
12202 goto err;
12203 }
12204 /* copy entries into the new dict, converting string keys to int keys */
12205 while (PyDict_Next(x, &i, &key, &value)) {
12206 if (PyUnicode_Check(key)) {
12207 /* convert string keys to integer keys */
12208 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012209 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012210 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12211 "table must be of length 1");
12212 goto err;
12213 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012214 kind = PyUnicode_KIND(key);
12215 data = PyUnicode_DATA(key);
12216 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012217 if (!newkey)
12218 goto err;
12219 res = PyDict_SetItem(new, newkey, value);
12220 Py_DECREF(newkey);
12221 if (res < 0)
12222 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012223 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012224 /* just keep integer keys */
12225 if (PyDict_SetItem(new, key, value) < 0)
12226 goto err;
12227 } else {
12228 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12229 "be strings or integers");
12230 goto err;
12231 }
12232 }
12233 }
12234 return new;
12235 err:
12236 Py_DECREF(new);
12237 return NULL;
12238}
12239
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012240PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012241 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012242\n\
12243Return a copy of the string S, where all characters have been mapped\n\
12244through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012245Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012246Unmapped characters are left untouched. Characters mapped to None\n\
12247are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012248
12249static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012250unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012251{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012252 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012253}
12254
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012255PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012256 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012257\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012258Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012259
12260static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012261unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012262{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012263 return fixup(self, fixupper);
12264}
12265
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012266PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012267 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012268\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012269Pad a numeric string S with zeros on the left, to fill a field\n\
12270of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012271
12272static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012273unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012274{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012275 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012276 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012277 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012278 int kind;
12279 void *data;
12280 Py_UCS4 chr;
12281
12282 if (PyUnicode_READY(self) == -1)
12283 return NULL;
12284
Martin v. Löwis18e16552006-02-15 17:27:45 +000012285 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012286 return NULL;
12287
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012288 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012289 if (PyUnicode_CheckExact(self)) {
12290 Py_INCREF(self);
12291 return (PyObject*) self;
12292 }
12293 else
Victor Stinner2219e0a2011-10-01 01:16:59 +020012294 return PyUnicode_Copy((PyObject*)self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012295 }
12296
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012297 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012298
12299 u = pad(self, fill, 0, '0');
12300
Walter Dörwald068325e2002-04-15 13:36:47 +000012301 if (u == NULL)
12302 return NULL;
12303
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012304 kind = PyUnicode_KIND(u);
12305 data = PyUnicode_DATA(u);
12306 chr = PyUnicode_READ(kind, data, fill);
12307
12308 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012309 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012310 PyUnicode_WRITE(kind, data, 0, chr);
12311 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012312 }
12313
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012314 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012315 return (PyObject*) u;
12316}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012317
12318#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012319static PyObject *
12320unicode__decimal2ascii(PyObject *self)
12321{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012322 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012323}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012324#endif
12325
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012326PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012327 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012328\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012329Return True if S starts with the specified prefix, False otherwise.\n\
12330With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012331With optional end, stop comparing S at that position.\n\
12332prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012333
12334static PyObject *
12335unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012336 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012337{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012338 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012339 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012340 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012341 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012342 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012343
Jesus Ceaac451502011-04-20 17:09:23 +020012344 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012345 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012346 if (PyTuple_Check(subobj)) {
12347 Py_ssize_t i;
12348 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
12349 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012350 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012351 if (substring == NULL)
12352 return NULL;
12353 result = tailmatch(self, substring, start, end, -1);
12354 Py_DECREF(substring);
12355 if (result) {
12356 Py_RETURN_TRUE;
12357 }
12358 }
12359 /* nothing matched */
12360 Py_RETURN_FALSE;
12361 }
12362 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012363 if (substring == NULL) {
12364 if (PyErr_ExceptionMatches(PyExc_TypeError))
12365 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12366 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012367 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012368 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012369 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012370 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012371 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012372}
12373
12374
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012375PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012376 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012377\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012378Return True if S ends with the specified suffix, False otherwise.\n\
12379With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012380With optional end, stop comparing S at that position.\n\
12381suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012382
12383static PyObject *
12384unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012385 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012386{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012387 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012388 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012389 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012390 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012391 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012392
Jesus Ceaac451502011-04-20 17:09:23 +020012393 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012394 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012395 if (PyTuple_Check(subobj)) {
12396 Py_ssize_t i;
12397 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
12398 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012399 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012400 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012401 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012402 result = tailmatch(self, substring, start, end, +1);
12403 Py_DECREF(substring);
12404 if (result) {
12405 Py_RETURN_TRUE;
12406 }
12407 }
12408 Py_RETURN_FALSE;
12409 }
12410 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012411 if (substring == NULL) {
12412 if (PyErr_ExceptionMatches(PyExc_TypeError))
12413 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12414 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012415 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012416 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012417 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012418 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012419 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012420}
12421
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012422#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012423
12424PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012425 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012426\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012427Return a formatted version of S, using substitutions from args and kwargs.\n\
12428The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012429
Eric Smith27bbca62010-11-04 17:06:58 +000012430PyDoc_STRVAR(format_map__doc__,
12431 "S.format_map(mapping) -> str\n\
12432\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012433Return a formatted version of S, using substitutions from mapping.\n\
12434The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012435
Eric Smith4a7d76d2008-05-30 18:10:19 +000012436static PyObject *
12437unicode__format__(PyObject* self, PyObject* args)
12438{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012439 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012440
12441 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12442 return NULL;
12443
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012444 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012445 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012446 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012447}
12448
Eric Smith8c663262007-08-25 02:26:07 +000012449PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012450 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012451\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012452Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012453
12454static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012455unicode__sizeof__(PyUnicodeObject *v)
12456{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012457 Py_ssize_t size;
12458
12459 /* If it's a compact object, account for base structure +
12460 character data. */
12461 if (PyUnicode_IS_COMPACT_ASCII(v))
12462 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12463 else if (PyUnicode_IS_COMPACT(v))
12464 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012465 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012466 else {
12467 /* If it is a two-block object, account for base object, and
12468 for character block if present. */
12469 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012470 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012471 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012472 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012473 }
12474 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012475 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012476 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012477 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012478 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012479 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012480
12481 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012482}
12483
12484PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012485 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012486
12487static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012488unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012489{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012490 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012491 if (!copy)
12492 return NULL;
12493 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012494}
12495
Guido van Rossumd57fd912000-03-10 22:53:23 +000012496static PyMethodDef unicode_methods[] = {
12497
12498 /* Order is according to common usage: often used methods should
12499 appear first, since lookup is done sequentially. */
12500
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012501 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012502 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12503 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012504 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012505 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12506 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12507 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12508 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12509 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12510 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12511 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012512 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012513 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12514 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12515 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012516 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012517 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12518 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12519 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012520 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012521 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012522 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012523 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012524 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12525 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12526 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12527 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12528 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12529 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12530 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12531 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12532 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12533 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12534 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12535 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12536 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12537 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012538 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012539 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012540 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012541 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012542 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012543 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012544 {"maketrans", (PyCFunction) unicode_maketrans,
12545 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012546 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012547#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012548 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012549#endif
12550
12551#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012552 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012553 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012554#endif
12555
Benjamin Peterson14339b62009-01-31 16:36:08 +000012556 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012557 {NULL, NULL}
12558};
12559
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012560static PyObject *
12561unicode_mod(PyObject *v, PyObject *w)
12562{
Brian Curtindfc80e32011-08-10 20:28:54 -050012563 if (!PyUnicode_Check(v))
12564 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012565 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012566}
12567
12568static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012569 0, /*nb_add*/
12570 0, /*nb_subtract*/
12571 0, /*nb_multiply*/
12572 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012573};
12574
Guido van Rossumd57fd912000-03-10 22:53:23 +000012575static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012576 (lenfunc) unicode_length, /* sq_length */
12577 PyUnicode_Concat, /* sq_concat */
12578 (ssizeargfunc) unicode_repeat, /* sq_repeat */
12579 (ssizeargfunc) unicode_getitem, /* sq_item */
12580 0, /* sq_slice */
12581 0, /* sq_ass_item */
12582 0, /* sq_ass_slice */
12583 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012584};
12585
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012586static PyObject*
12587unicode_subscript(PyUnicodeObject* self, PyObject* item)
12588{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012589 if (PyUnicode_READY(self) == -1)
12590 return NULL;
12591
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000012592 if (PyIndex_Check(item)) {
12593 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012594 if (i == -1 && PyErr_Occurred())
12595 return NULL;
12596 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012597 i += PyUnicode_GET_LENGTH(self);
Victor Stinner2fe5ced2011-10-02 00:25:40 +020012598 return unicode_getitem((PyObject*)self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012599 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000012600 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012601 PyObject *result;
12602 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012603 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012604 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012605
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012606 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000012607 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012608 return NULL;
12609 }
12610
12611 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012612 return PyUnicode_New(0, 0);
12613 } else if (start == 0 && step == 1 &&
12614 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000012615 PyUnicode_CheckExact(self)) {
12616 Py_INCREF(self);
12617 return (PyObject *)self;
12618 } else if (step == 1) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012619 return PyUnicode_Substring((PyObject*)self,
12620 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012621 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012622 /* General case */
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012623 max_char = 0;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012624 src_kind = PyUnicode_KIND(self);
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012625 kind_limit = kind_maxchar_limit(src_kind);
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012626 src_data = PyUnicode_DATA(self);
12627 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
12628 ch = PyUnicode_READ(src_kind, src_data, cur);
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012629 if (ch > max_char) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012630 max_char = ch;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012631 if (max_char >= kind_limit)
12632 break;
12633 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012634 }
12635 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012636 if (result == NULL)
12637 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012638 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012639 dest_data = PyUnicode_DATA(result);
12640
12641 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012642 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
12643 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012644 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012645 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012646 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012647 } else {
12648 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
12649 return NULL;
12650 }
12651}
12652
12653static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012654 (lenfunc)unicode_length, /* mp_length */
12655 (binaryfunc)unicode_subscript, /* mp_subscript */
12656 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012657};
12658
Guido van Rossumd57fd912000-03-10 22:53:23 +000012659
Guido van Rossumd57fd912000-03-10 22:53:23 +000012660/* Helpers for PyUnicode_Format() */
12661
12662static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000012663getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012664{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012665 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012666 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012667 (*p_argidx)++;
12668 if (arglen < 0)
12669 return args;
12670 else
12671 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012672 }
12673 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012674 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012675 return NULL;
12676}
12677
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012678/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012679
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012680static PyObject *
12681formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012682{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012683 char *p;
12684 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012685 double x;
Tim Petersced69f82003-09-16 20:30:58 +000012686
Guido van Rossumd57fd912000-03-10 22:53:23 +000012687 x = PyFloat_AsDouble(v);
12688 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012689 return NULL;
12690
Guido van Rossumd57fd912000-03-10 22:53:23 +000012691 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012692 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000012693
Eric Smith0923d1d2009-04-16 20:16:10 +000012694 p = PyOS_double_to_string(x, type, prec,
12695 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012696 if (p == NULL)
12697 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012698 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000012699 PyMem_Free(p);
12700 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012701}
12702
Tim Peters38fd5b62000-09-21 05:43:11 +000012703static PyObject*
12704formatlong(PyObject *val, int flags, int prec, int type)
12705{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012706 char *buf;
12707 int len;
12708 PyObject *str; /* temporary string object. */
12709 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000012710
Benjamin Peterson14339b62009-01-31 16:36:08 +000012711 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
12712 if (!str)
12713 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012714 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012715 Py_DECREF(str);
12716 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000012717}
12718
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012719static Py_UCS4
12720formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012721{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000012722 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012723 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012724 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012725 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000012726 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012727 goto onError;
12728 }
12729 else {
12730 /* Integer input truncated to a character */
12731 long x;
12732 x = PyLong_AsLong(v);
12733 if (x == -1 && PyErr_Occurred())
12734 goto onError;
12735
12736 if (x < 0 || x > 0x10ffff) {
12737 PyErr_SetString(PyExc_OverflowError,
12738 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012739 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000012740 }
12741
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012742 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012743 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000012744
Benjamin Peterson29060642009-01-31 22:14:21 +000012745 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012746 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012747 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012748 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012749}
12750
Antoine Pitrou978b9d22011-10-07 12:35:48 +020012751static int
12752repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
12753{
12754 int r;
12755 assert(count > 0);
12756 assert(PyUnicode_Check(obj));
12757 if (count > 5) {
12758 PyObject *repeated = unicode_repeat((PyUnicodeObject *) obj, count);
12759 if (repeated == NULL)
12760 return -1;
12761 r = _PyAccu_Accumulate(acc, repeated);
12762 Py_DECREF(repeated);
12763 return r;
12764 }
12765 else {
12766 do {
12767 if (_PyAccu_Accumulate(acc, obj))
12768 return -1;
12769 } while (--count);
12770 return 0;
12771 }
12772}
12773
Alexander Belopolsky40018472011-02-26 01:02:56 +000012774PyObject *
12775PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012776{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012777 void *fmt;
12778 int fmtkind;
12779 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012780 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012781 int r;
12782 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012783 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012784 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012785 PyObject *temp = NULL;
12786 PyObject *second = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012787 PyUnicodeObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012788 _PyAccu acc;
12789 static PyObject *plus, *minus, *blank, *zero, *percent;
12790
12791 if (!plus && !(plus = get_latin1_char('+')))
12792 return NULL;
12793 if (!minus && !(minus = get_latin1_char('-')))
12794 return NULL;
12795 if (!blank && !(blank = get_latin1_char(' ')))
12796 return NULL;
12797 if (!zero && !(zero = get_latin1_char('0')))
12798 return NULL;
12799 if (!percent && !(percent = get_latin1_char('%')))
12800 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000012801
Guido van Rossumd57fd912000-03-10 22:53:23 +000012802 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012803 PyErr_BadInternalCall();
12804 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012805 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012806 uformat = (PyUnicodeObject*)PyUnicode_FromObject(format);
12807 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012808 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012809 if (_PyAccu_Init(&acc))
12810 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012811 fmt = PyUnicode_DATA(uformat);
12812 fmtkind = PyUnicode_KIND(uformat);
12813 fmtcnt = PyUnicode_GET_LENGTH(uformat);
12814 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012815
Guido van Rossumd57fd912000-03-10 22:53:23 +000012816 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012817 arglen = PyTuple_Size(args);
12818 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012819 }
12820 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012821 arglen = -1;
12822 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012823 }
Christian Heimes90aa7642007-12-19 02:45:37 +000012824 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000012825 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000012826 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012827
12828 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012829 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012830 PyObject *nonfmt;
12831 Py_ssize_t nonfmtpos;
12832 nonfmtpos = fmtpos++;
12833 while (fmtcnt >= 0 &&
12834 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
12835 fmtpos++;
12836 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012837 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012838 nonfmt = PyUnicode_Substring((PyObject *) uformat, nonfmtpos, fmtpos);
12839 if (nonfmt == NULL)
12840 goto onError;
12841 r = _PyAccu_Accumulate(&acc, nonfmt);
12842 Py_DECREF(nonfmt);
12843 if (r)
12844 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012845 }
12846 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012847 /* Got a format specifier */
12848 int flags = 0;
12849 Py_ssize_t width = -1;
12850 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012851 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012852 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000012853 int isnumok;
12854 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012855 void *pbuf = NULL;
12856 Py_ssize_t pindex, len;
12857 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012858
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012859 fmtpos++;
12860 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
12861 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000012862 Py_ssize_t keylen;
12863 PyObject *key;
12864 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000012865
Benjamin Peterson29060642009-01-31 22:14:21 +000012866 if (dict == NULL) {
12867 PyErr_SetString(PyExc_TypeError,
12868 "format requires a mapping");
12869 goto onError;
12870 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012871 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000012872 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012873 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000012874 /* Skip over balanced parentheses */
12875 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012876 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000012877 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012878 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000012879 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012880 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000012881 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012882 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000012883 if (fmtcnt < 0 || pcount > 0) {
12884 PyErr_SetString(PyExc_ValueError,
12885 "incomplete format key");
12886 goto onError;
12887 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020012888 key = PyUnicode_Substring((PyObject*)uformat,
12889 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000012890 if (key == NULL)
12891 goto onError;
12892 if (args_owned) {
12893 Py_DECREF(args);
12894 args_owned = 0;
12895 }
12896 args = PyObject_GetItem(dict, key);
12897 Py_DECREF(key);
12898 if (args == NULL) {
12899 goto onError;
12900 }
12901 args_owned = 1;
12902 arglen = -1;
12903 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012904 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012905 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012906 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012907 case '-': flags |= F_LJUST; continue;
12908 case '+': flags |= F_SIGN; continue;
12909 case ' ': flags |= F_BLANK; continue;
12910 case '#': flags |= F_ALT; continue;
12911 case '0': flags |= F_ZERO; continue;
12912 }
12913 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012914 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012915 if (c == '*') {
12916 v = getnextarg(args, arglen, &argidx);
12917 if (v == NULL)
12918 goto onError;
12919 if (!PyLong_Check(v)) {
12920 PyErr_SetString(PyExc_TypeError,
12921 "* wants int");
12922 goto onError;
12923 }
12924 width = PyLong_AsLong(v);
12925 if (width == -1 && PyErr_Occurred())
12926 goto onError;
12927 if (width < 0) {
12928 flags |= F_LJUST;
12929 width = -width;
12930 }
12931 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012932 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012933 }
12934 else if (c >= '0' && c <= '9') {
12935 width = c - '0';
12936 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012937 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012938 if (c < '0' || c > '9')
12939 break;
12940 if ((width*10) / 10 != width) {
12941 PyErr_SetString(PyExc_ValueError,
12942 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000012943 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000012944 }
12945 width = width*10 + (c - '0');
12946 }
12947 }
12948 if (c == '.') {
12949 prec = 0;
12950 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012951 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012952 if (c == '*') {
12953 v = getnextarg(args, arglen, &argidx);
12954 if (v == NULL)
12955 goto onError;
12956 if (!PyLong_Check(v)) {
12957 PyErr_SetString(PyExc_TypeError,
12958 "* wants int");
12959 goto onError;
12960 }
12961 prec = PyLong_AsLong(v);
12962 if (prec == -1 && PyErr_Occurred())
12963 goto onError;
12964 if (prec < 0)
12965 prec = 0;
12966 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012967 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012968 }
12969 else if (c >= '0' && c <= '9') {
12970 prec = c - '0';
12971 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012972 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012973 if (c < '0' || c > '9')
12974 break;
12975 if ((prec*10) / 10 != prec) {
12976 PyErr_SetString(PyExc_ValueError,
12977 "prec too big");
12978 goto onError;
12979 }
12980 prec = prec*10 + (c - '0');
12981 }
12982 }
12983 } /* prec */
12984 if (fmtcnt >= 0) {
12985 if (c == 'h' || c == 'l' || c == 'L') {
12986 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012987 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012988 }
12989 }
12990 if (fmtcnt < 0) {
12991 PyErr_SetString(PyExc_ValueError,
12992 "incomplete format");
12993 goto onError;
12994 }
12995 if (c != '%') {
12996 v = getnextarg(args, arglen, &argidx);
12997 if (v == NULL)
12998 goto onError;
12999 }
13000 sign = 0;
13001 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013002 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013003 switch (c) {
13004
13005 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013006 _PyAccu_Accumulate(&acc, percent);
13007 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013008
13009 case 's':
13010 case 'r':
13011 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013012 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013013 temp = v;
13014 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013015 }
13016 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013017 if (c == 's')
13018 temp = PyObject_Str(v);
13019 else if (c == 'r')
13020 temp = PyObject_Repr(v);
13021 else
13022 temp = PyObject_ASCII(v);
13023 if (temp == NULL)
13024 goto onError;
13025 if (PyUnicode_Check(temp))
13026 /* nothing to do */;
13027 else {
13028 Py_DECREF(temp);
13029 PyErr_SetString(PyExc_TypeError,
13030 "%s argument has non-string str()");
13031 goto onError;
13032 }
13033 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013034 if (PyUnicode_READY(temp) == -1) {
13035 Py_CLEAR(temp);
13036 goto onError;
13037 }
13038 pbuf = PyUnicode_DATA(temp);
13039 kind = PyUnicode_KIND(temp);
13040 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013041 if (prec >= 0 && len > prec)
13042 len = prec;
13043 break;
13044
13045 case 'i':
13046 case 'd':
13047 case 'u':
13048 case 'o':
13049 case 'x':
13050 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013051 isnumok = 0;
13052 if (PyNumber_Check(v)) {
13053 PyObject *iobj=NULL;
13054
13055 if (PyLong_Check(v)) {
13056 iobj = v;
13057 Py_INCREF(iobj);
13058 }
13059 else {
13060 iobj = PyNumber_Long(v);
13061 }
13062 if (iobj!=NULL) {
13063 if (PyLong_Check(iobj)) {
13064 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013065 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013066 Py_DECREF(iobj);
13067 if (!temp)
13068 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013069 if (PyUnicode_READY(temp) == -1) {
13070 Py_CLEAR(temp);
13071 goto onError;
13072 }
13073 pbuf = PyUnicode_DATA(temp);
13074 kind = PyUnicode_KIND(temp);
13075 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013076 sign = 1;
13077 }
13078 else {
13079 Py_DECREF(iobj);
13080 }
13081 }
13082 }
13083 if (!isnumok) {
13084 PyErr_Format(PyExc_TypeError,
13085 "%%%c format: a number is required, "
13086 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13087 goto onError;
13088 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013089 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013090 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013091 fillobj = zero;
13092 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013093 break;
13094
13095 case 'e':
13096 case 'E':
13097 case 'f':
13098 case 'F':
13099 case 'g':
13100 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013101 temp = formatfloat(v, flags, prec, c);
13102 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013103 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013104 if (PyUnicode_READY(temp) == -1) {
13105 Py_CLEAR(temp);
13106 goto onError;
13107 }
13108 pbuf = PyUnicode_DATA(temp);
13109 kind = PyUnicode_KIND(temp);
13110 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013111 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013112 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013113 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013114 fillobj = zero;
13115 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013116 break;
13117
13118 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013119 {
13120 Py_UCS4 ch = formatchar(v);
13121 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013122 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013123 temp = _PyUnicode_FromUCS4(&ch, 1);
13124 if (temp == NULL)
13125 goto onError;
13126 pbuf = PyUnicode_DATA(temp);
13127 kind = PyUnicode_KIND(temp);
13128 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013129 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013130 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013131
13132 default:
13133 PyErr_Format(PyExc_ValueError,
13134 "unsupported format character '%c' (0x%x) "
13135 "at index %zd",
13136 (31<=c && c<=126) ? (char)c : '?',
13137 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013138 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013139 goto onError;
13140 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013141 /* pbuf is initialized here. */
13142 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013143 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013144 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13145 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013146 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013147 pindex++;
13148 }
13149 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13150 signobj = plus;
13151 len--;
13152 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013153 }
13154 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013155 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013156 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013157 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013158 else
13159 sign = 0;
13160 }
13161 if (width < len)
13162 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013163 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013164 if (fill != ' ') {
13165 assert(signobj != NULL);
13166 if (_PyAccu_Accumulate(&acc, signobj))
13167 goto onError;
13168 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013169 if (width > len)
13170 width--;
13171 }
13172 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013173 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013174 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013175 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013176 second = get_latin1_char(
13177 PyUnicode_READ(kind, pbuf, pindex + 1));
13178 pindex += 2;
13179 if (second == NULL ||
13180 _PyAccu_Accumulate(&acc, zero) ||
13181 _PyAccu_Accumulate(&acc, second))
13182 goto onError;
13183 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013184 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013185 width -= 2;
13186 if (width < 0)
13187 width = 0;
13188 len -= 2;
13189 }
13190 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013191 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013192 if (repeat_accumulate(&acc, fillobj, width - len))
13193 goto onError;
13194 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013195 }
13196 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013197 if (sign) {
13198 assert(signobj != NULL);
13199 if (_PyAccu_Accumulate(&acc, signobj))
13200 goto onError;
13201 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013202 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013203 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13204 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013205 second = get_latin1_char(
13206 PyUnicode_READ(kind, pbuf, pindex + 1));
13207 pindex += 2;
13208 if (second == NULL ||
13209 _PyAccu_Accumulate(&acc, zero) ||
13210 _PyAccu_Accumulate(&acc, second))
13211 goto onError;
13212 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013213 }
13214 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013215 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013216 if (temp != NULL) {
13217 assert(pbuf == PyUnicode_DATA(temp));
13218 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013219 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013220 else {
13221 const char *p = (const char *) pbuf;
13222 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013223 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013224 v = PyUnicode_FromKindAndData(kind, p, len);
13225 }
13226 if (v == NULL)
13227 goto onError;
13228 r = _PyAccu_Accumulate(&acc, v);
13229 Py_DECREF(v);
13230 if (r)
13231 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013232 if (width > len && repeat_accumulate(&acc, blank, width - len))
13233 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013234 if (dict && (argidx < arglen) && c != '%') {
13235 PyErr_SetString(PyExc_TypeError,
13236 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013237 goto onError;
13238 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013239 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013240 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013241 } /* until end */
13242 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013243 PyErr_SetString(PyExc_TypeError,
13244 "not all arguments converted during string formatting");
13245 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013246 }
13247
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013248 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013249 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013250 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013251 }
13252 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013253 Py_XDECREF(temp);
13254 Py_XDECREF(second);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013255 return (PyObject *)result;
13256
Benjamin Peterson29060642009-01-31 22:14:21 +000013257 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013258 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013259 Py_XDECREF(temp);
13260 Py_XDECREF(second);
13261 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013262 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013263 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013264 }
13265 return NULL;
13266}
13267
Jeremy Hylton938ace62002-07-17 16:30:39 +000013268static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013269unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13270
Tim Peters6d6c1a32001-08-02 04:15:00 +000013271static PyObject *
13272unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13273{
Benjamin Peterson29060642009-01-31 22:14:21 +000013274 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013275 static char *kwlist[] = {"object", "encoding", "errors", 0};
13276 char *encoding = NULL;
13277 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013278
Benjamin Peterson14339b62009-01-31 16:36:08 +000013279 if (type != &PyUnicode_Type)
13280 return unicode_subtype_new(type, args, kwds);
13281 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013282 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013283 return NULL;
13284 if (x == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013285 return (PyObject *)PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013286 if (encoding == NULL && errors == NULL)
13287 return PyObject_Str(x);
13288 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013289 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013290}
13291
Guido van Rossume023fe02001-08-30 03:12:59 +000013292static PyObject *
13293unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13294{
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013295 PyUnicodeObject *unicode, *self;
13296 Py_ssize_t length, char_size;
13297 int share_wstr, share_utf8;
13298 unsigned int kind;
13299 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013300
Benjamin Peterson14339b62009-01-31 16:36:08 +000013301 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013302
13303 unicode = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
13304 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013305 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013306 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013307 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013308 return NULL;
13309
13310 self = (PyUnicodeObject *) type->tp_alloc(type, 0);
13311 if (self == NULL) {
13312 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013313 return NULL;
13314 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013315 kind = PyUnicode_KIND(unicode);
13316 length = PyUnicode_GET_LENGTH(unicode);
13317
13318 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013319#ifdef Py_DEBUG
13320 _PyUnicode_HASH(self) = -1;
13321#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013322 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013323#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013324 _PyUnicode_STATE(self).interned = 0;
13325 _PyUnicode_STATE(self).kind = kind;
13326 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013327 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013328 _PyUnicode_STATE(self).ready = 1;
13329 _PyUnicode_WSTR(self) = NULL;
13330 _PyUnicode_UTF8_LENGTH(self) = 0;
13331 _PyUnicode_UTF8(self) = NULL;
13332 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013333 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013334
13335 share_utf8 = 0;
13336 share_wstr = 0;
13337 if (kind == PyUnicode_1BYTE_KIND) {
13338 char_size = 1;
13339 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13340 share_utf8 = 1;
13341 }
13342 else if (kind == PyUnicode_2BYTE_KIND) {
13343 char_size = 2;
13344 if (sizeof(wchar_t) == 2)
13345 share_wstr = 1;
13346 }
13347 else {
13348 assert(kind == PyUnicode_4BYTE_KIND);
13349 char_size = 4;
13350 if (sizeof(wchar_t) == 4)
13351 share_wstr = 1;
13352 }
13353
13354 /* Ensure we won't overflow the length. */
13355 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13356 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013357 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013358 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013359 data = PyObject_MALLOC((length + 1) * char_size);
13360 if (data == NULL) {
13361 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013362 goto onError;
13363 }
13364
Victor Stinnerc3c74152011-10-02 20:39:55 +020013365 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013366 if (share_utf8) {
13367 _PyUnicode_UTF8_LENGTH(self) = length;
13368 _PyUnicode_UTF8(self) = data;
13369 }
13370 if (share_wstr) {
13371 _PyUnicode_WSTR_LENGTH(self) = length;
13372 _PyUnicode_WSTR(self) = (wchar_t *)data;
13373 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013374
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013375 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013376 kind * (length + 1));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013377 Py_DECREF(unicode);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013378 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013379#ifdef Py_DEBUG
13380 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13381#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013382 return (PyObject *)self;
13383
13384onError:
13385 Py_DECREF(unicode);
13386 Py_DECREF(self);
13387 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013388}
13389
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013390PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013391 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013392\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013393Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013394encoding defaults to the current default string encoding.\n\
13395errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013396
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013397static PyObject *unicode_iter(PyObject *seq);
13398
Guido van Rossumd57fd912000-03-10 22:53:23 +000013399PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013400 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013401 "str", /* tp_name */
13402 sizeof(PyUnicodeObject), /* tp_size */
13403 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013404 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013405 (destructor)unicode_dealloc, /* tp_dealloc */
13406 0, /* tp_print */
13407 0, /* tp_getattr */
13408 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013409 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013410 unicode_repr, /* tp_repr */
13411 &unicode_as_number, /* tp_as_number */
13412 &unicode_as_sequence, /* tp_as_sequence */
13413 &unicode_as_mapping, /* tp_as_mapping */
13414 (hashfunc) unicode_hash, /* tp_hash*/
13415 0, /* tp_call*/
13416 (reprfunc) unicode_str, /* tp_str */
13417 PyObject_GenericGetAttr, /* tp_getattro */
13418 0, /* tp_setattro */
13419 0, /* tp_as_buffer */
13420 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013421 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013422 unicode_doc, /* tp_doc */
13423 0, /* tp_traverse */
13424 0, /* tp_clear */
13425 PyUnicode_RichCompare, /* tp_richcompare */
13426 0, /* tp_weaklistoffset */
13427 unicode_iter, /* tp_iter */
13428 0, /* tp_iternext */
13429 unicode_methods, /* tp_methods */
13430 0, /* tp_members */
13431 0, /* tp_getset */
13432 &PyBaseObject_Type, /* tp_base */
13433 0, /* tp_dict */
13434 0, /* tp_descr_get */
13435 0, /* tp_descr_set */
13436 0, /* tp_dictoffset */
13437 0, /* tp_init */
13438 0, /* tp_alloc */
13439 unicode_new, /* tp_new */
13440 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013441};
13442
13443/* Initialize the Unicode implementation */
13444
Thomas Wouters78890102000-07-22 19:25:51 +000013445void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013446{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013447 int i;
13448
Thomas Wouters477c8d52006-05-27 19:21:47 +000013449 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013450 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013451 0x000A, /* LINE FEED */
13452 0x000D, /* CARRIAGE RETURN */
13453 0x001C, /* FILE SEPARATOR */
13454 0x001D, /* GROUP SEPARATOR */
13455 0x001E, /* RECORD SEPARATOR */
13456 0x0085, /* NEXT LINE */
13457 0x2028, /* LINE SEPARATOR */
13458 0x2029, /* PARAGRAPH SEPARATOR */
13459 };
13460
Fred Drakee4315f52000-05-09 19:53:39 +000013461 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013462 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013463 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013464 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013465 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013466
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013467 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013468 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013469 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013470 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013471
13472 /* initialize the linebreak bloom filter */
13473 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013474 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013475 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013476
13477 PyType_Ready(&EncodingMapType);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013478}
13479
13480/* Finalize the Unicode implementation */
13481
Christian Heimesa156e092008-02-16 07:38:31 +000013482int
13483PyUnicode_ClearFreeList(void)
13484{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013485 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013486}
13487
Guido van Rossumd57fd912000-03-10 22:53:23 +000013488void
Thomas Wouters78890102000-07-22 19:25:51 +000013489_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013490{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013491 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013492
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013493 Py_XDECREF(unicode_empty);
13494 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013495
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013496 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013497 if (unicode_latin1[i]) {
13498 Py_DECREF(unicode_latin1[i]);
13499 unicode_latin1[i] = NULL;
13500 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013501 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020013502 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000013503 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013504}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013505
Walter Dörwald16807132007-05-25 13:52:07 +000013506void
13507PyUnicode_InternInPlace(PyObject **p)
13508{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013509 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
13510 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013511#ifdef Py_DEBUG
13512 assert(s != NULL);
13513 assert(_PyUnicode_CHECK(s));
13514#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013515 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013516 return;
13517#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013518 /* If it's a subclass, we don't really know what putting
13519 it in the interned dict might do. */
13520 if (!PyUnicode_CheckExact(s))
13521 return;
13522 if (PyUnicode_CHECK_INTERNED(s))
13523 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013524 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013525 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013526 return;
13527 }
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013528 s = (PyUnicodeObject *)(*p);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013529 if (interned == NULL) {
13530 interned = PyDict_New();
13531 if (interned == NULL) {
13532 PyErr_Clear(); /* Don't leave an exception */
13533 return;
13534 }
13535 }
13536 /* It might be that the GetItem call fails even
13537 though the key is present in the dictionary,
13538 namely when this happens during a stack overflow. */
13539 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000013540 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013541 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013542
Benjamin Peterson29060642009-01-31 22:14:21 +000013543 if (t) {
13544 Py_INCREF(t);
13545 Py_DECREF(*p);
13546 *p = t;
13547 return;
13548 }
Walter Dörwald16807132007-05-25 13:52:07 +000013549
Benjamin Peterson14339b62009-01-31 16:36:08 +000013550 PyThreadState_GET()->recursion_critical = 1;
13551 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
13552 PyErr_Clear();
13553 PyThreadState_GET()->recursion_critical = 0;
13554 return;
13555 }
13556 PyThreadState_GET()->recursion_critical = 0;
13557 /* The two references in interned are not counted by refcnt.
13558 The deallocator will take care of this */
13559 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013560 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013561}
13562
13563void
13564PyUnicode_InternImmortal(PyObject **p)
13565{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013566 PyUnicodeObject *u = (PyUnicodeObject *)*p;
13567
Benjamin Peterson14339b62009-01-31 16:36:08 +000013568 PyUnicode_InternInPlace(p);
13569 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013570 _PyUnicode_STATE(u).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013571 Py_INCREF(*p);
13572 }
Walter Dörwald16807132007-05-25 13:52:07 +000013573}
13574
13575PyObject *
13576PyUnicode_InternFromString(const char *cp)
13577{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013578 PyObject *s = PyUnicode_FromString(cp);
13579 if (s == NULL)
13580 return NULL;
13581 PyUnicode_InternInPlace(&s);
13582 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000013583}
13584
Alexander Belopolsky40018472011-02-26 01:02:56 +000013585void
13586_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000013587{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013588 PyObject *keys;
13589 PyUnicodeObject *s;
13590 Py_ssize_t i, n;
13591 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000013592
Benjamin Peterson14339b62009-01-31 16:36:08 +000013593 if (interned == NULL || !PyDict_Check(interned))
13594 return;
13595 keys = PyDict_Keys(interned);
13596 if (keys == NULL || !PyList_Check(keys)) {
13597 PyErr_Clear();
13598 return;
13599 }
Walter Dörwald16807132007-05-25 13:52:07 +000013600
Benjamin Peterson14339b62009-01-31 16:36:08 +000013601 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
13602 detector, interned unicode strings are not forcibly deallocated;
13603 rather, we give them their stolen references back, and then clear
13604 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000013605
Benjamin Peterson14339b62009-01-31 16:36:08 +000013606 n = PyList_GET_SIZE(keys);
13607 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000013608 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013609 for (i = 0; i < n; i++) {
13610 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013611 if (PyUnicode_READY(s) == -1) {
13612 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013613 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013614 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013615 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013616 case SSTATE_NOT_INTERNED:
13617 /* XXX Shouldn't happen */
13618 break;
13619 case SSTATE_INTERNED_IMMORTAL:
13620 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013621 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013622 break;
13623 case SSTATE_INTERNED_MORTAL:
13624 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013625 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013626 break;
13627 default:
13628 Py_FatalError("Inconsistent interned string state.");
13629 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013630 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013631 }
13632 fprintf(stderr, "total size of all interned strings: "
13633 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
13634 "mortal/immortal\n", mortal_size, immortal_size);
13635 Py_DECREF(keys);
13636 PyDict_Clear(interned);
13637 Py_DECREF(interned);
13638 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000013639}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013640
13641
13642/********************* Unicode Iterator **************************/
13643
13644typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013645 PyObject_HEAD
13646 Py_ssize_t it_index;
13647 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013648} unicodeiterobject;
13649
13650static void
13651unicodeiter_dealloc(unicodeiterobject *it)
13652{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013653 _PyObject_GC_UNTRACK(it);
13654 Py_XDECREF(it->it_seq);
13655 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013656}
13657
13658static int
13659unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
13660{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013661 Py_VISIT(it->it_seq);
13662 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013663}
13664
13665static PyObject *
13666unicodeiter_next(unicodeiterobject *it)
13667{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013668 PyUnicodeObject *seq;
13669 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013670
Benjamin Peterson14339b62009-01-31 16:36:08 +000013671 assert(it != NULL);
13672 seq = it->it_seq;
13673 if (seq == NULL)
13674 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013675 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013676
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013677 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
13678 int kind = PyUnicode_KIND(seq);
13679 void *data = PyUnicode_DATA(seq);
13680 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
13681 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013682 if (item != NULL)
13683 ++it->it_index;
13684 return item;
13685 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013686
Benjamin Peterson14339b62009-01-31 16:36:08 +000013687 Py_DECREF(seq);
13688 it->it_seq = NULL;
13689 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013690}
13691
13692static PyObject *
13693unicodeiter_len(unicodeiterobject *it)
13694{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013695 Py_ssize_t len = 0;
13696 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013697 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013698 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013699}
13700
13701PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
13702
13703static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013704 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000013705 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000013706 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013707};
13708
13709PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013710 PyVarObject_HEAD_INIT(&PyType_Type, 0)
13711 "str_iterator", /* tp_name */
13712 sizeof(unicodeiterobject), /* tp_basicsize */
13713 0, /* tp_itemsize */
13714 /* methods */
13715 (destructor)unicodeiter_dealloc, /* tp_dealloc */
13716 0, /* tp_print */
13717 0, /* tp_getattr */
13718 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013719 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013720 0, /* tp_repr */
13721 0, /* tp_as_number */
13722 0, /* tp_as_sequence */
13723 0, /* tp_as_mapping */
13724 0, /* tp_hash */
13725 0, /* tp_call */
13726 0, /* tp_str */
13727 PyObject_GenericGetAttr, /* tp_getattro */
13728 0, /* tp_setattro */
13729 0, /* tp_as_buffer */
13730 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
13731 0, /* tp_doc */
13732 (traverseproc)unicodeiter_traverse, /* tp_traverse */
13733 0, /* tp_clear */
13734 0, /* tp_richcompare */
13735 0, /* tp_weaklistoffset */
13736 PyObject_SelfIter, /* tp_iter */
13737 (iternextfunc)unicodeiter_next, /* tp_iternext */
13738 unicodeiter_methods, /* tp_methods */
13739 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013740};
13741
13742static PyObject *
13743unicode_iter(PyObject *seq)
13744{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013745 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013746
Benjamin Peterson14339b62009-01-31 16:36:08 +000013747 if (!PyUnicode_Check(seq)) {
13748 PyErr_BadInternalCall();
13749 return NULL;
13750 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013751 if (PyUnicode_READY(seq) == -1)
13752 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013753 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
13754 if (it == NULL)
13755 return NULL;
13756 it->it_index = 0;
13757 Py_INCREF(seq);
13758 it->it_seq = (PyUnicodeObject *)seq;
13759 _PyObject_GC_TRACK(it);
13760 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013761}
13762
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013763#define UNIOP(x) Py_UNICODE_##x
13764#define UNIOP_t Py_UNICODE
13765#include "uniops.h"
13766#undef UNIOP
13767#undef UNIOP_t
13768#define UNIOP(x) Py_UCS4_##x
13769#define UNIOP_t Py_UCS4
13770#include "uniops.h"
13771#undef UNIOP
13772#undef UNIOP_t
Victor Stinner331ea922010-08-10 16:37:20 +000013773
Victor Stinner71133ff2010-09-01 23:43:53 +000013774Py_UNICODE*
Victor Stinner46408602010-09-03 16:18:00 +000013775PyUnicode_AsUnicodeCopy(PyObject *object)
Victor Stinner71133ff2010-09-01 23:43:53 +000013776{
13777 PyUnicodeObject *unicode = (PyUnicodeObject *)object;
Victor Stinner577db2c2011-10-11 22:12:48 +020013778 Py_UNICODE *u, *copy;
Victor Stinner71133ff2010-09-01 23:43:53 +000013779 Py_ssize_t size;
13780
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013781 if (!PyUnicode_Check(unicode)) {
13782 PyErr_BadArgument();
13783 return NULL;
13784 }
Victor Stinner577db2c2011-10-11 22:12:48 +020013785 u = PyUnicode_AsUnicode(object);
13786 if (u == NULL)
13787 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000013788 /* Ensure we won't overflow the size. */
13789 if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
13790 PyErr_NoMemory();
13791 return NULL;
13792 }
13793 size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
13794 size *= sizeof(Py_UNICODE);
13795 copy = PyMem_Malloc(size);
13796 if (copy == NULL) {
13797 PyErr_NoMemory();
13798 return NULL;
13799 }
Victor Stinner577db2c2011-10-11 22:12:48 +020013800 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000013801 return copy;
13802}
Martin v. Löwis5b222132007-06-10 09:51:05 +000013803
Georg Brandl66c221e2010-10-14 07:04:07 +000013804/* A _string module, to export formatter_parser and formatter_field_name_split
13805 to the string.Formatter class implemented in Python. */
13806
13807static PyMethodDef _string_methods[] = {
13808 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
13809 METH_O, PyDoc_STR("split the argument as a field name")},
13810 {"formatter_parser", (PyCFunction) formatter_parser,
13811 METH_O, PyDoc_STR("parse the argument as a format string")},
13812 {NULL, NULL}
13813};
13814
13815static struct PyModuleDef _string_module = {
13816 PyModuleDef_HEAD_INIT,
13817 "_string",
13818 PyDoc_STR("string helper module"),
13819 0,
13820 _string_methods,
13821 NULL,
13822 NULL,
13823 NULL,
13824 NULL
13825};
13826
13827PyMODINIT_FUNC
13828PyInit__string(void)
13829{
13830 return PyModule_Create(&_string_module);
13831}
13832
13833
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013834#ifdef __cplusplus
13835}
13836#endif