blob: e84cb3ce6dc2fb1502cda9ca2a5f438c2f314a39 [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)
Victor Stinner4e101002011-10-11 23:27:52 +02001720 return get_latin1_char((unsigned 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;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001760 if (max_char < 256)
1761 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1762 PyUnicode_1BYTE_DATA(res));
1763 else if (max_char < 0x10000)
1764 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1765 PyUnicode_2BYTE_DATA(res));
1766 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001767 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
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 Stinner983b1432011-10-12 00:54:35 +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 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02001981 if (kind == PyUnicode_1BYTE_KIND) {
1982 Py_UCS1 *start = (Py_UCS1 *) data;
1983 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001984 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02001985 else if (kind == PyUnicode_2BYTE_KIND) {
1986 Py_UCS2 *start = (Py_UCS2 *) data;
1987 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
1988 }
1989 else {
1990 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001991 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02001992 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001993 if (copy_null)
1994 target[len] = 0;
1995 return target;
1996}
1997
1998Py_UCS4*
1999PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2000 int copy_null)
2001{
2002 if (target == NULL || targetsize < 1) {
2003 PyErr_BadInternalCall();
2004 return NULL;
2005 }
2006 return as_ucs4(string, target, targetsize, copy_null);
2007}
2008
2009Py_UCS4*
2010PyUnicode_AsUCS4Copy(PyObject *string)
2011{
2012 return as_ucs4(string, NULL, 0, 1);
2013}
2014
2015#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002016
Alexander Belopolsky40018472011-02-26 01:02:56 +00002017PyObject *
2018PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002019{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002020 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00002021 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002022 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00002023 PyErr_BadInternalCall();
2024 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002025 }
2026
Martin v. Löwis790465f2008-04-05 20:41:37 +00002027 if (size == -1) {
2028 size = wcslen(w);
2029 }
2030
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002031 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002032}
2033
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002034#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002035
Walter Dörwald346737f2007-05-31 10:44:43 +00002036static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002037makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2038 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002039{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002040 *fmt++ = '%';
2041 if (width) {
2042 if (zeropad)
2043 *fmt++ = '0';
2044 fmt += sprintf(fmt, "%d", width);
2045 }
2046 if (precision)
2047 fmt += sprintf(fmt, ".%d", precision);
2048 if (longflag)
2049 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002050 else if (longlongflag) {
2051 /* longlongflag should only ever be nonzero on machines with
2052 HAVE_LONG_LONG defined */
2053#ifdef HAVE_LONG_LONG
2054 char *f = PY_FORMAT_LONG_LONG;
2055 while (*f)
2056 *fmt++ = *f++;
2057#else
2058 /* we shouldn't ever get here */
2059 assert(0);
2060 *fmt++ = 'l';
2061#endif
2062 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002063 else if (size_tflag) {
2064 char *f = PY_FORMAT_SIZE_T;
2065 while (*f)
2066 *fmt++ = *f++;
2067 }
2068 *fmt++ = c;
2069 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002070}
2071
Victor Stinner96865452011-03-01 23:44:09 +00002072/* helper for PyUnicode_FromFormatV() */
2073
2074static const char*
2075parse_format_flags(const char *f,
2076 int *p_width, int *p_precision,
2077 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2078{
2079 int width, precision, longflag, longlongflag, size_tflag;
2080
2081 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2082 f++;
2083 width = 0;
2084 while (Py_ISDIGIT((unsigned)*f))
2085 width = (width*10) + *f++ - '0';
2086 precision = 0;
2087 if (*f == '.') {
2088 f++;
2089 while (Py_ISDIGIT((unsigned)*f))
2090 precision = (precision*10) + *f++ - '0';
2091 if (*f == '%') {
2092 /* "%.3%s" => f points to "3" */
2093 f--;
2094 }
2095 }
2096 if (*f == '\0') {
2097 /* bogus format "%.1" => go backward, f points to "1" */
2098 f--;
2099 }
2100 if (p_width != NULL)
2101 *p_width = width;
2102 if (p_precision != NULL)
2103 *p_precision = precision;
2104
2105 /* Handle %ld, %lu, %lld and %llu. */
2106 longflag = 0;
2107 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002108 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002109
2110 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002111 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002112 longflag = 1;
2113 ++f;
2114 }
2115#ifdef HAVE_LONG_LONG
2116 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002117 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002118 longlongflag = 1;
2119 f += 2;
2120 }
2121#endif
2122 }
2123 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002124 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002125 size_tflag = 1;
2126 ++f;
2127 }
2128 if (p_longflag != NULL)
2129 *p_longflag = longflag;
2130 if (p_longlongflag != NULL)
2131 *p_longlongflag = longlongflag;
2132 if (p_size_tflag != NULL)
2133 *p_size_tflag = size_tflag;
2134 return f;
2135}
2136
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002137/* maximum number of characters required for output of %ld. 21 characters
2138 allows for 64-bit integers (in decimal) and an optional sign. */
2139#define MAX_LONG_CHARS 21
2140/* maximum number of characters required for output of %lld.
2141 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2142 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2143#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2144
Walter Dörwaldd2034312007-05-18 16:29:38 +00002145PyObject *
2146PyUnicode_FromFormatV(const char *format, va_list vargs)
2147{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002148 va_list count;
2149 Py_ssize_t callcount = 0;
2150 PyObject **callresults = NULL;
2151 PyObject **callresult = NULL;
2152 Py_ssize_t n = 0;
2153 int width = 0;
2154 int precision = 0;
2155 int zeropad;
2156 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002157 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002158 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002159 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002160 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2161 Py_UCS4 argmaxchar;
2162 Py_ssize_t numbersize = 0;
2163 char *numberresults = NULL;
2164 char *numberresult = NULL;
2165 Py_ssize_t i;
2166 int kind;
2167 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002168
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002169 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002170 /* step 1: count the number of %S/%R/%A/%s format specifications
2171 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2172 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002173 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002174 * also estimate a upper bound for all the number formats in the string,
2175 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002176 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002177 for (f = format; *f; f++) {
2178 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002179 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002180 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2181 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2182 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2183 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002184
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002185 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002186#ifdef HAVE_LONG_LONG
2187 if (longlongflag) {
2188 if (width < MAX_LONG_LONG_CHARS)
2189 width = MAX_LONG_LONG_CHARS;
2190 }
2191 else
2192#endif
2193 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2194 including sign. Decimal takes the most space. This
2195 isn't enough for octal. If a width is specified we
2196 need more (which we allocate later). */
2197 if (width < MAX_LONG_CHARS)
2198 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002199
2200 /* account for the size + '\0' to separate numbers
2201 inside of the numberresults buffer */
2202 numbersize += (width + 1);
2203 }
2204 }
2205 else if ((unsigned char)*f > 127) {
2206 PyErr_Format(PyExc_ValueError,
2207 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2208 "string, got a non-ASCII byte: 0x%02x",
2209 (unsigned char)*f);
2210 return NULL;
2211 }
2212 }
2213 /* step 2: allocate memory for the results of
2214 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2215 if (callcount) {
2216 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2217 if (!callresults) {
2218 PyErr_NoMemory();
2219 return NULL;
2220 }
2221 callresult = callresults;
2222 }
2223 /* step 2.5: allocate memory for the results of formating numbers */
2224 if (numbersize) {
2225 numberresults = PyObject_Malloc(numbersize);
2226 if (!numberresults) {
2227 PyErr_NoMemory();
2228 goto fail;
2229 }
2230 numberresult = numberresults;
2231 }
2232
2233 /* step 3: format numbers and figure out how large a buffer we need */
2234 for (f = format; *f; f++) {
2235 if (*f == '%') {
2236 const char* p;
2237 int longflag;
2238 int longlongflag;
2239 int size_tflag;
2240 int numprinted;
2241
2242 p = f;
2243 zeropad = (f[1] == '0');
2244 f = parse_format_flags(f, &width, &precision,
2245 &longflag, &longlongflag, &size_tflag);
2246 switch (*f) {
2247 case 'c':
2248 {
2249 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002250 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002251 n++;
2252 break;
2253 }
2254 case '%':
2255 n++;
2256 break;
2257 case 'i':
2258 case 'd':
2259 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2260 width, precision, *f);
2261 if (longflag)
2262 numprinted = sprintf(numberresult, fmt,
2263 va_arg(count, long));
2264#ifdef HAVE_LONG_LONG
2265 else if (longlongflag)
2266 numprinted = sprintf(numberresult, fmt,
2267 va_arg(count, PY_LONG_LONG));
2268#endif
2269 else if (size_tflag)
2270 numprinted = sprintf(numberresult, fmt,
2271 va_arg(count, Py_ssize_t));
2272 else
2273 numprinted = sprintf(numberresult, fmt,
2274 va_arg(count, int));
2275 n += numprinted;
2276 /* advance by +1 to skip over the '\0' */
2277 numberresult += (numprinted + 1);
2278 assert(*(numberresult - 1) == '\0');
2279 assert(*(numberresult - 2) != '\0');
2280 assert(numprinted >= 0);
2281 assert(numberresult <= numberresults + numbersize);
2282 break;
2283 case 'u':
2284 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2285 width, precision, 'u');
2286 if (longflag)
2287 numprinted = sprintf(numberresult, fmt,
2288 va_arg(count, unsigned long));
2289#ifdef HAVE_LONG_LONG
2290 else if (longlongflag)
2291 numprinted = sprintf(numberresult, fmt,
2292 va_arg(count, unsigned PY_LONG_LONG));
2293#endif
2294 else if (size_tflag)
2295 numprinted = sprintf(numberresult, fmt,
2296 va_arg(count, size_t));
2297 else
2298 numprinted = sprintf(numberresult, fmt,
2299 va_arg(count, unsigned int));
2300 n += numprinted;
2301 numberresult += (numprinted + 1);
2302 assert(*(numberresult - 1) == '\0');
2303 assert(*(numberresult - 2) != '\0');
2304 assert(numprinted >= 0);
2305 assert(numberresult <= numberresults + numbersize);
2306 break;
2307 case 'x':
2308 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2309 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2310 n += numprinted;
2311 numberresult += (numprinted + 1);
2312 assert(*(numberresult - 1) == '\0');
2313 assert(*(numberresult - 2) != '\0');
2314 assert(numprinted >= 0);
2315 assert(numberresult <= numberresults + numbersize);
2316 break;
2317 case 'p':
2318 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2319 /* %p is ill-defined: ensure leading 0x. */
2320 if (numberresult[1] == 'X')
2321 numberresult[1] = 'x';
2322 else if (numberresult[1] != 'x') {
2323 memmove(numberresult + 2, numberresult,
2324 strlen(numberresult) + 1);
2325 numberresult[0] = '0';
2326 numberresult[1] = 'x';
2327 numprinted += 2;
2328 }
2329 n += numprinted;
2330 numberresult += (numprinted + 1);
2331 assert(*(numberresult - 1) == '\0');
2332 assert(*(numberresult - 2) != '\0');
2333 assert(numprinted >= 0);
2334 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002335 break;
2336 case 's':
2337 {
2338 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002339 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002340 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2341 if (!str)
2342 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002343 /* since PyUnicode_DecodeUTF8 returns already flexible
2344 unicode objects, there is no need to call ready on them */
2345 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002346 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002347 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002348 /* Remember the str and switch to the next slot */
2349 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002350 break;
2351 }
2352 case 'U':
2353 {
2354 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002355 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002356 if (PyUnicode_READY(obj) == -1)
2357 goto fail;
2358 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002359 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002360 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002361 break;
2362 }
2363 case 'V':
2364 {
2365 PyObject *obj = va_arg(count, PyObject *);
2366 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002367 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002368 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002369 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002370 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002371 if (PyUnicode_READY(obj) == -1)
2372 goto fail;
2373 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002374 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002375 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002376 *callresult++ = NULL;
2377 }
2378 else {
2379 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2380 if (!str_obj)
2381 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002382 if (PyUnicode_READY(str_obj)) {
2383 Py_DECREF(str_obj);
2384 goto fail;
2385 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002386 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002387 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002388 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002389 *callresult++ = str_obj;
2390 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002391 break;
2392 }
2393 case 'S':
2394 {
2395 PyObject *obj = va_arg(count, PyObject *);
2396 PyObject *str;
2397 assert(obj);
2398 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002399 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002400 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002401 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002402 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002403 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002404 /* Remember the str and switch to the next slot */
2405 *callresult++ = str;
2406 break;
2407 }
2408 case 'R':
2409 {
2410 PyObject *obj = va_arg(count, PyObject *);
2411 PyObject *repr;
2412 assert(obj);
2413 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002414 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002415 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002416 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002417 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002418 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002419 /* Remember the repr and switch to the next slot */
2420 *callresult++ = repr;
2421 break;
2422 }
2423 case 'A':
2424 {
2425 PyObject *obj = va_arg(count, PyObject *);
2426 PyObject *ascii;
2427 assert(obj);
2428 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002429 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002430 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002431 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002432 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002433 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002434 /* Remember the repr and switch to the next slot */
2435 *callresult++ = ascii;
2436 break;
2437 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002438 default:
2439 /* if we stumble upon an unknown
2440 formatting code, copy the rest of
2441 the format string to the output
2442 string. (we cannot just skip the
2443 code, since there's no way to know
2444 what's in the argument list) */
2445 n += strlen(p);
2446 goto expand;
2447 }
2448 } else
2449 n++;
2450 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002451 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002452 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002453 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002454 we don't have to resize the string.
2455 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002456 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002457 if (!string)
2458 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002459 kind = PyUnicode_KIND(string);
2460 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002461 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002462 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002463
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002464 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002465 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002466 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002467
2468 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002469 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2470 /* checking for == because the last argument could be a empty
2471 string, which causes i to point to end, the assert at the end of
2472 the loop */
2473 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002474
Benjamin Peterson14339b62009-01-31 16:36:08 +00002475 switch (*f) {
2476 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002477 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002478 const int ordinal = va_arg(vargs, int);
2479 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002480 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002481 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002482 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002483 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002484 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002485 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002486 case 'p':
2487 /* unused, since we already have the result */
2488 if (*f == 'p')
2489 (void) va_arg(vargs, void *);
2490 else
2491 (void) va_arg(vargs, int);
2492 /* extract the result from numberresults and append. */
2493 for (; *numberresult; ++i, ++numberresult)
2494 PyUnicode_WRITE(kind, data, i, *numberresult);
2495 /* skip over the separating '\0' */
2496 assert(*numberresult == '\0');
2497 numberresult++;
2498 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002499 break;
2500 case 's':
2501 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002502 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002503 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002504 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002505 size = PyUnicode_GET_LENGTH(*callresult);
2506 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002507 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002508 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002509 /* We're done with the unicode()/repr() => forget it */
2510 Py_DECREF(*callresult);
2511 /* switch to next unicode()/repr() result */
2512 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002513 break;
2514 }
2515 case 'U':
2516 {
2517 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002518 Py_ssize_t size;
2519 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2520 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002521 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002522 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002523 break;
2524 }
2525 case 'V':
2526 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002527 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002528 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002529 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002530 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002531 size = PyUnicode_GET_LENGTH(obj);
2532 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002533 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002534 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002535 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002536 size = PyUnicode_GET_LENGTH(*callresult);
2537 assert(PyUnicode_KIND(*callresult) <=
2538 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002539 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002540 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002541 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002542 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002543 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002544 break;
2545 }
2546 case 'S':
2547 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002548 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002549 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002550 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002551 /* unused, since we already have the result */
2552 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002553 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002554 copy_characters(string, i, *callresult, 0, size);
2555 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002556 /* We're done with the unicode()/repr() => forget it */
2557 Py_DECREF(*callresult);
2558 /* switch to next unicode()/repr() result */
2559 ++callresult;
2560 break;
2561 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002562 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002563 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002564 break;
2565 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002566 for (; *p; ++p, ++i)
2567 PyUnicode_WRITE(kind, data, i, *p);
2568 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002569 goto end;
2570 }
Victor Stinner1205f272010-09-11 00:54:47 +00002571 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002572 else {
2573 assert(i < PyUnicode_GET_LENGTH(string));
2574 PyUnicode_WRITE(kind, data, i++, *f);
2575 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002576 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002577 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002578
Benjamin Peterson29060642009-01-31 22:14:21 +00002579 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002580 if (callresults)
2581 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002582 if (numberresults)
2583 PyObject_Free(numberresults);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002584 assert(_PyUnicode_CheckConsistency(string, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002585 return (PyObject *)string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002586 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002587 if (callresults) {
2588 PyObject **callresult2 = callresults;
2589 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002590 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002591 ++callresult2;
2592 }
2593 PyObject_Free(callresults);
2594 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002595 if (numberresults)
2596 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002597 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002598}
2599
Walter Dörwaldd2034312007-05-18 16:29:38 +00002600PyObject *
2601PyUnicode_FromFormat(const char *format, ...)
2602{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002603 PyObject* ret;
2604 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002605
2606#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002607 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002608#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002609 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002610#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002611 ret = PyUnicode_FromFormatV(format, vargs);
2612 va_end(vargs);
2613 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002614}
2615
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002616#ifdef HAVE_WCHAR_H
2617
Victor Stinner5593d8a2010-10-02 11:11:27 +00002618/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2619 convert a Unicode object to a wide character string.
2620
Victor Stinnerd88d9832011-09-06 02:00:05 +02002621 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002622 character) required to convert the unicode object. Ignore size argument.
2623
Victor Stinnerd88d9832011-09-06 02:00:05 +02002624 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002625 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002626 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002627static Py_ssize_t
Victor Stinner137c34c2010-09-29 10:25:54 +00002628unicode_aswidechar(PyUnicodeObject *unicode,
2629 wchar_t *w,
2630 Py_ssize_t size)
2631{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002632 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002633 const wchar_t *wstr;
2634
2635 wstr = PyUnicode_AsUnicodeAndSize((PyObject *)unicode, &res);
2636 if (wstr == NULL)
2637 return -1;
2638
Victor Stinner5593d8a2010-10-02 11:11:27 +00002639 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002640 if (size > res)
2641 size = res + 1;
2642 else
2643 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002644 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002645 return res;
2646 }
2647 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002648 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002649}
2650
2651Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002652PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002653 wchar_t *w,
2654 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002655{
2656 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002657 PyErr_BadInternalCall();
2658 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002659 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002660 return unicode_aswidechar((PyUnicodeObject*)unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002661}
2662
Victor Stinner137c34c2010-09-29 10:25:54 +00002663wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002664PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002665 Py_ssize_t *size)
2666{
2667 wchar_t* buffer;
2668 Py_ssize_t buflen;
2669
2670 if (unicode == NULL) {
2671 PyErr_BadInternalCall();
2672 return NULL;
2673 }
2674
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002675 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002676 if (buflen == -1)
2677 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002678 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002679 PyErr_NoMemory();
2680 return NULL;
2681 }
2682
Victor Stinner137c34c2010-09-29 10:25:54 +00002683 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2684 if (buffer == NULL) {
2685 PyErr_NoMemory();
2686 return NULL;
2687 }
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002688 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002689 if (buflen == -1)
2690 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002691 if (size != NULL)
2692 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002693 return buffer;
2694}
2695
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002696#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002697
Alexander Belopolsky40018472011-02-26 01:02:56 +00002698PyObject *
2699PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002700{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002701 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002702 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002703 PyErr_SetString(PyExc_ValueError,
2704 "chr() arg not in range(0x110000)");
2705 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002706 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002707
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002708 if (ordinal < 256)
2709 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002710
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002711 v = PyUnicode_New(1, ordinal);
2712 if (v == NULL)
2713 return NULL;
2714 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002715 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002716 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002717}
2718
Alexander Belopolsky40018472011-02-26 01:02:56 +00002719PyObject *
2720PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002721{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002722 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002723 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002724 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002725 if (PyUnicode_READY(obj))
2726 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002727 Py_INCREF(obj);
2728 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002729 }
2730 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002731 /* For a Unicode subtype that's not a Unicode object,
2732 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002733 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002734 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002735 PyErr_Format(PyExc_TypeError,
2736 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002737 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002738 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002739}
2740
Alexander Belopolsky40018472011-02-26 01:02:56 +00002741PyObject *
2742PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002743 const char *encoding,
2744 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002745{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002746 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002747 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002748
Guido van Rossumd57fd912000-03-10 22:53:23 +00002749 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002750 PyErr_BadInternalCall();
2751 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002752 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002753
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002754 /* Decoding bytes objects is the most common case and should be fast */
2755 if (PyBytes_Check(obj)) {
2756 if (PyBytes_GET_SIZE(obj) == 0) {
2757 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002758 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002759 }
2760 else {
2761 v = PyUnicode_Decode(
2762 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2763 encoding, errors);
2764 }
2765 return v;
2766 }
2767
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002768 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002769 PyErr_SetString(PyExc_TypeError,
2770 "decoding str is not supported");
2771 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002772 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002773
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002774 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2775 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2776 PyErr_Format(PyExc_TypeError,
2777 "coercing to str: need bytes, bytearray "
2778 "or buffer-like object, %.80s found",
2779 Py_TYPE(obj)->tp_name);
2780 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002781 }
Tim Petersced69f82003-09-16 20:30:58 +00002782
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002783 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002784 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002785 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002786 }
Tim Petersced69f82003-09-16 20:30:58 +00002787 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002788 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002789
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002790 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002791 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002792}
2793
Victor Stinner600d3be2010-06-10 12:00:55 +00002794/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002795 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2796 1 on success. */
2797static int
2798normalize_encoding(const char *encoding,
2799 char *lower,
2800 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002801{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002802 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002803 char *l;
2804 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002805
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002806 e = encoding;
2807 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002808 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002809 while (*e) {
2810 if (l == l_end)
2811 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002812 if (Py_ISUPPER(*e)) {
2813 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002814 }
2815 else if (*e == '_') {
2816 *l++ = '-';
2817 e++;
2818 }
2819 else {
2820 *l++ = *e++;
2821 }
2822 }
2823 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002824 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002825}
2826
Alexander Belopolsky40018472011-02-26 01:02:56 +00002827PyObject *
2828PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002829 Py_ssize_t size,
2830 const char *encoding,
2831 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002832{
2833 PyObject *buffer = NULL, *unicode;
2834 Py_buffer info;
2835 char lower[11]; /* Enough for any encoding shortcut */
2836
2837 if (encoding == NULL)
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002838 return PyUnicode_DecodeUTF8(s, size, errors);
Fred Drakee4315f52000-05-09 19:53:39 +00002839
2840 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002841 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002842 if ((strcmp(lower, "utf-8") == 0) ||
2843 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002844 return PyUnicode_DecodeUTF8(s, size, errors);
2845 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002846 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002847 (strcmp(lower, "iso-8859-1") == 0))
2848 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002849#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002850 else if (strcmp(lower, "mbcs") == 0)
2851 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002852#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002853 else if (strcmp(lower, "ascii") == 0)
2854 return PyUnicode_DecodeASCII(s, size, errors);
2855 else if (strcmp(lower, "utf-16") == 0)
2856 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2857 else if (strcmp(lower, "utf-32") == 0)
2858 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2859 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002860
2861 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002862 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002863 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002864 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002865 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002866 if (buffer == NULL)
2867 goto onError;
2868 unicode = PyCodec_Decode(buffer, encoding, errors);
2869 if (unicode == NULL)
2870 goto onError;
2871 if (!PyUnicode_Check(unicode)) {
2872 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002873 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002874 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002875 Py_DECREF(unicode);
2876 goto onError;
2877 }
2878 Py_DECREF(buffer);
Victor Stinner17efeed2011-10-04 20:05:46 +02002879#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002880 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002881 Py_DECREF(unicode);
2882 return NULL;
2883 }
Victor Stinner17efeed2011-10-04 20:05:46 +02002884#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002885 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00002886 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002887
Benjamin Peterson29060642009-01-31 22:14:21 +00002888 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002889 Py_XDECREF(buffer);
2890 return NULL;
2891}
2892
Alexander Belopolsky40018472011-02-26 01:02:56 +00002893PyObject *
2894PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002895 const char *encoding,
2896 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002897{
2898 PyObject *v;
2899
2900 if (!PyUnicode_Check(unicode)) {
2901 PyErr_BadArgument();
2902 goto onError;
2903 }
2904
2905 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002906 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002907
2908 /* Decode via the codec registry */
2909 v = PyCodec_Decode(unicode, encoding, errors);
2910 if (v == NULL)
2911 goto onError;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002912 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002913 return v;
2914
Benjamin Peterson29060642009-01-31 22:14:21 +00002915 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002916 return NULL;
2917}
2918
Alexander Belopolsky40018472011-02-26 01:02:56 +00002919PyObject *
2920PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002921 const char *encoding,
2922 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002923{
2924 PyObject *v;
2925
2926 if (!PyUnicode_Check(unicode)) {
2927 PyErr_BadArgument();
2928 goto onError;
2929 }
2930
2931 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002932 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002933
2934 /* Decode via the codec registry */
2935 v = PyCodec_Decode(unicode, encoding, errors);
2936 if (v == NULL)
2937 goto onError;
2938 if (!PyUnicode_Check(v)) {
2939 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002940 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002941 Py_TYPE(v)->tp_name);
2942 Py_DECREF(v);
2943 goto onError;
2944 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002945 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002946 return v;
2947
Benjamin Peterson29060642009-01-31 22:14:21 +00002948 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002949 return NULL;
2950}
2951
Alexander Belopolsky40018472011-02-26 01:02:56 +00002952PyObject *
2953PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002954 Py_ssize_t size,
2955 const char *encoding,
2956 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002957{
2958 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002959
Guido van Rossumd57fd912000-03-10 22:53:23 +00002960 unicode = PyUnicode_FromUnicode(s, size);
2961 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002962 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002963 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
2964 Py_DECREF(unicode);
2965 return v;
2966}
2967
Alexander Belopolsky40018472011-02-26 01:02:56 +00002968PyObject *
2969PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002970 const char *encoding,
2971 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002972{
2973 PyObject *v;
2974
2975 if (!PyUnicode_Check(unicode)) {
2976 PyErr_BadArgument();
2977 goto onError;
2978 }
2979
2980 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002981 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002982
2983 /* Encode via the codec registry */
2984 v = PyCodec_Encode(unicode, encoding, errors);
2985 if (v == NULL)
2986 goto onError;
2987 return v;
2988
Benjamin Peterson29060642009-01-31 22:14:21 +00002989 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002990 return NULL;
2991}
2992
Victor Stinnerad158722010-10-27 00:25:46 +00002993PyObject *
2994PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00002995{
Victor Stinner99b95382011-07-04 14:23:54 +02002996#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00002997 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
2998 PyUnicode_GET_SIZE(unicode),
2999 NULL);
3000#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003001 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003002#else
Victor Stinner793b5312011-04-27 00:24:21 +02003003 PyInterpreterState *interp = PyThreadState_GET()->interp;
3004 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3005 cannot use it to encode and decode filenames before it is loaded. Load
3006 the Python codec requires to encode at least its own filename. Use the C
3007 version of the locale codec until the codec registry is initialized and
3008 the Python codec is loaded.
3009
3010 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3011 cannot only rely on it: check also interp->fscodec_initialized for
3012 subinterpreters. */
3013 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003014 return PyUnicode_AsEncodedString(unicode,
3015 Py_FileSystemDefaultEncoding,
3016 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003017 }
3018 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003019 /* locale encoding with surrogateescape */
3020 wchar_t *wchar;
3021 char *bytes;
3022 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003023 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003024
3025 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3026 if (wchar == NULL)
3027 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003028 bytes = _Py_wchar2char(wchar, &error_pos);
3029 if (bytes == NULL) {
3030 if (error_pos != (size_t)-1) {
3031 char *errmsg = strerror(errno);
3032 PyObject *exc = NULL;
3033 if (errmsg == NULL)
3034 errmsg = "Py_wchar2char() failed";
3035 raise_encode_exception(&exc,
3036 "filesystemencoding",
3037 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
3038 error_pos, error_pos+1,
3039 errmsg);
3040 Py_XDECREF(exc);
3041 }
3042 else
3043 PyErr_NoMemory();
3044 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003045 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003046 }
3047 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003048
3049 bytes_obj = PyBytes_FromString(bytes);
3050 PyMem_Free(bytes);
3051 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003052 }
Victor Stinnerad158722010-10-27 00:25:46 +00003053#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003054}
3055
Alexander Belopolsky40018472011-02-26 01:02:56 +00003056PyObject *
3057PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003058 const char *encoding,
3059 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003060{
3061 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003062 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003063
Guido van Rossumd57fd912000-03-10 22:53:23 +00003064 if (!PyUnicode_Check(unicode)) {
3065 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003066 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003067 }
Fred Drakee4315f52000-05-09 19:53:39 +00003068
Victor Stinner2f283c22011-03-02 01:21:46 +00003069 if (encoding == NULL) {
3070 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003071 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003072 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003073 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner2f283c22011-03-02 01:21:46 +00003074 }
Fred Drakee4315f52000-05-09 19:53:39 +00003075
3076 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003077 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003078 if ((strcmp(lower, "utf-8") == 0) ||
3079 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003080 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003081 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003082 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003083 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003084 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003085 }
Victor Stinner37296e82010-06-10 13:36:23 +00003086 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003087 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003088 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003089 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003090#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003091 else if (strcmp(lower, "mbcs") == 0)
3092 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3093 PyUnicode_GET_SIZE(unicode),
3094 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003095#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003096 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003097 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003098 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003099
3100 /* Encode via the codec registry */
3101 v = PyCodec_Encode(unicode, encoding, errors);
3102 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003103 return NULL;
3104
3105 /* The normal path */
3106 if (PyBytes_Check(v))
3107 return v;
3108
3109 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003110 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003111 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003112 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003113
3114 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3115 "encoder %s returned bytearray instead of bytes",
3116 encoding);
3117 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003118 Py_DECREF(v);
3119 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003120 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003121
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003122 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3123 Py_DECREF(v);
3124 return b;
3125 }
3126
3127 PyErr_Format(PyExc_TypeError,
3128 "encoder did not return a bytes object (type=%.400s)",
3129 Py_TYPE(v)->tp_name);
3130 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003131 return NULL;
3132}
3133
Alexander Belopolsky40018472011-02-26 01:02:56 +00003134PyObject *
3135PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003136 const char *encoding,
3137 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003138{
3139 PyObject *v;
3140
3141 if (!PyUnicode_Check(unicode)) {
3142 PyErr_BadArgument();
3143 goto onError;
3144 }
3145
3146 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003147 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003148
3149 /* Encode via the codec registry */
3150 v = PyCodec_Encode(unicode, encoding, errors);
3151 if (v == NULL)
3152 goto onError;
3153 if (!PyUnicode_Check(v)) {
3154 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003155 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003156 Py_TYPE(v)->tp_name);
3157 Py_DECREF(v);
3158 goto onError;
3159 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003160 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003161
Benjamin Peterson29060642009-01-31 22:14:21 +00003162 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003163 return NULL;
3164}
3165
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003166PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003167PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003168 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003169 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3170}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003171
Christian Heimes5894ba72007-11-04 11:43:14 +00003172PyObject*
3173PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3174{
Victor Stinner99b95382011-07-04 14:23:54 +02003175#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003176 return PyUnicode_DecodeMBCS(s, size, NULL);
3177#elif defined(__APPLE__)
3178 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3179#else
Victor Stinner793b5312011-04-27 00:24:21 +02003180 PyInterpreterState *interp = PyThreadState_GET()->interp;
3181 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3182 cannot use it to encode and decode filenames before it is loaded. Load
3183 the Python codec requires to encode at least its own filename. Use the C
3184 version of the locale codec until the codec registry is initialized and
3185 the Python codec is loaded.
3186
3187 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3188 cannot only rely on it: check also interp->fscodec_initialized for
3189 subinterpreters. */
3190 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003191 return PyUnicode_Decode(s, size,
3192 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003193 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003194 }
3195 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003196 /* locale encoding with surrogateescape */
3197 wchar_t *wchar;
3198 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003199 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003200
3201 if (s[size] != '\0' || size != strlen(s)) {
3202 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3203 return NULL;
3204 }
3205
Victor Stinner168e1172010-10-16 23:16:16 +00003206 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003207 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003208 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003209
Victor Stinner168e1172010-10-16 23:16:16 +00003210 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003211 PyMem_Free(wchar);
3212 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003213 }
Victor Stinnerad158722010-10-27 00:25:46 +00003214#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003215}
3216
Martin v. Löwis011e8422009-05-05 04:43:17 +00003217
3218int
3219PyUnicode_FSConverter(PyObject* arg, void* addr)
3220{
3221 PyObject *output = NULL;
3222 Py_ssize_t size;
3223 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003224 if (arg == NULL) {
3225 Py_DECREF(*(PyObject**)addr);
3226 return 1;
3227 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003228 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003229 output = arg;
3230 Py_INCREF(output);
3231 }
3232 else {
3233 arg = PyUnicode_FromObject(arg);
3234 if (!arg)
3235 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003236 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003237 Py_DECREF(arg);
3238 if (!output)
3239 return 0;
3240 if (!PyBytes_Check(output)) {
3241 Py_DECREF(output);
3242 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3243 return 0;
3244 }
3245 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003246 size = PyBytes_GET_SIZE(output);
3247 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003248 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003249 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003250 Py_DECREF(output);
3251 return 0;
3252 }
3253 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003254 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003255}
3256
3257
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003258int
3259PyUnicode_FSDecoder(PyObject* arg, void* addr)
3260{
3261 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003262 if (arg == NULL) {
3263 Py_DECREF(*(PyObject**)addr);
3264 return 1;
3265 }
3266 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003267 if (PyUnicode_READY(arg))
3268 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003269 output = arg;
3270 Py_INCREF(output);
3271 }
3272 else {
3273 arg = PyBytes_FromObject(arg);
3274 if (!arg)
3275 return 0;
3276 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3277 PyBytes_GET_SIZE(arg));
3278 Py_DECREF(arg);
3279 if (!output)
3280 return 0;
3281 if (!PyUnicode_Check(output)) {
3282 Py_DECREF(output);
3283 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3284 return 0;
3285 }
3286 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003287 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
3288 PyUnicode_GET_LENGTH(output), 0, 1)) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003289 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3290 Py_DECREF(output);
3291 return 0;
3292 }
3293 *(PyObject**)addr = output;
3294 return Py_CLEANUP_SUPPORTED;
3295}
3296
3297
Martin v. Löwis5b222132007-06-10 09:51:05 +00003298char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003299PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003300{
Christian Heimesf3863112007-11-22 07:46:41 +00003301 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003302 PyUnicodeObject *u = (PyUnicodeObject *)unicode;
3303
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003304 if (!PyUnicode_Check(unicode)) {
3305 PyErr_BadArgument();
3306 return NULL;
3307 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003308 if (PyUnicode_READY(u) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003309 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003310
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003311 if (PyUnicode_UTF8(unicode) == NULL) {
3312 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003313 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3314 if (bytes == NULL)
3315 return NULL;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003316 _PyUnicode_UTF8(u) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3317 if (_PyUnicode_UTF8(u) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003318 Py_DECREF(bytes);
3319 return NULL;
3320 }
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003321 _PyUnicode_UTF8_LENGTH(u) = PyBytes_GET_SIZE(bytes);
3322 Py_MEMCPY(_PyUnicode_UTF8(u), PyBytes_AS_STRING(bytes), _PyUnicode_UTF8_LENGTH(u) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003323 Py_DECREF(bytes);
3324 }
3325
3326 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003327 *psize = PyUnicode_UTF8_LENGTH(unicode);
3328 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003329}
3330
3331char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003332PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003333{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003334 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3335}
3336
3337#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003338static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003339#endif
3340
3341
3342Py_UNICODE *
3343PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3344{
3345 PyUnicodeObject *u;
3346 const unsigned char *one_byte;
3347#if SIZEOF_WCHAR_T == 4
3348 const Py_UCS2 *two_bytes;
3349#else
3350 const Py_UCS4 *four_bytes;
3351 const Py_UCS4 *ucs4_end;
3352 Py_ssize_t num_surrogates;
3353#endif
3354 wchar_t *w;
3355 wchar_t *wchar_end;
3356
3357 if (!PyUnicode_Check(unicode)) {
3358 PyErr_BadArgument();
3359 return NULL;
3360 }
3361 u = (PyUnicodeObject*)unicode;
3362 if (_PyUnicode_WSTR(u) == NULL) {
3363 /* Non-ASCII compact unicode object */
3364 assert(_PyUnicode_KIND(u) != 0);
3365 assert(PyUnicode_IS_READY(u));
3366
3367#ifdef Py_DEBUG
3368 ++unicode_as_unicode_calls;
3369#endif
3370
3371 if (PyUnicode_KIND(u) == PyUnicode_4BYTE_KIND) {
3372#if SIZEOF_WCHAR_T == 2
3373 four_bytes = PyUnicode_4BYTE_DATA(u);
3374 ucs4_end = four_bytes + _PyUnicode_LENGTH(u);
3375 num_surrogates = 0;
3376
3377 for (; four_bytes < ucs4_end; ++four_bytes) {
3378 if (*four_bytes > 0xFFFF)
3379 ++num_surrogates;
3380 }
3381
3382 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(
3383 sizeof(wchar_t) * (_PyUnicode_LENGTH(u) + 1 + num_surrogates));
3384 if (!_PyUnicode_WSTR(u)) {
3385 PyErr_NoMemory();
3386 return NULL;
3387 }
3388 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u) + num_surrogates;
3389
3390 w = _PyUnicode_WSTR(u);
3391 wchar_end = w + _PyUnicode_WSTR_LENGTH(u);
3392 four_bytes = PyUnicode_4BYTE_DATA(u);
3393 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3394 if (*four_bytes > 0xFFFF) {
3395 /* encode surrogate pair in this case */
3396 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3397 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3398 }
3399 else
3400 *w = *four_bytes;
3401
3402 if (w > wchar_end) {
3403 assert(0 && "Miscalculated string end");
3404 }
3405 }
3406 *w = 0;
3407#else
3408 /* sizeof(wchar_t) == 4 */
3409 Py_FatalError("Impossible unicode object state, wstr and str "
3410 "should share memory already.");
3411 return NULL;
3412#endif
3413 }
3414 else {
3415 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3416 (_PyUnicode_LENGTH(u) + 1));
3417 if (!_PyUnicode_WSTR(u)) {
3418 PyErr_NoMemory();
3419 return NULL;
3420 }
3421 if (!PyUnicode_IS_COMPACT_ASCII(u))
3422 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u);
3423 w = _PyUnicode_WSTR(u);
3424 wchar_end = w + _PyUnicode_LENGTH(u);
3425
3426 if (PyUnicode_KIND(u) == PyUnicode_1BYTE_KIND) {
3427 one_byte = PyUnicode_1BYTE_DATA(u);
3428 for (; w < wchar_end; ++one_byte, ++w)
3429 *w = *one_byte;
3430 /* null-terminate the wstr */
3431 *w = 0;
3432 }
3433 else if (PyUnicode_KIND(u) == PyUnicode_2BYTE_KIND) {
3434#if SIZEOF_WCHAR_T == 4
3435 two_bytes = PyUnicode_2BYTE_DATA(u);
3436 for (; w < wchar_end; ++two_bytes, ++w)
3437 *w = *two_bytes;
3438 /* null-terminate the wstr */
3439 *w = 0;
3440#else
3441 /* sizeof(wchar_t) == 2 */
3442 PyObject_FREE(_PyUnicode_WSTR(u));
3443 _PyUnicode_WSTR(u) = NULL;
3444 Py_FatalError("Impossible unicode object state, wstr "
3445 "and str should share memory already.");
3446 return NULL;
3447#endif
3448 }
3449 else {
3450 assert(0 && "This should never happen.");
3451 }
3452 }
3453 }
3454 if (size != NULL)
3455 *size = PyUnicode_WSTR_LENGTH(u);
3456 return _PyUnicode_WSTR(u);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003457}
3458
Alexander Belopolsky40018472011-02-26 01:02:56 +00003459Py_UNICODE *
3460PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003461{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003462 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003463}
3464
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003465
Alexander Belopolsky40018472011-02-26 01:02:56 +00003466Py_ssize_t
3467PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003468{
3469 if (!PyUnicode_Check(unicode)) {
3470 PyErr_BadArgument();
3471 goto onError;
3472 }
3473 return PyUnicode_GET_SIZE(unicode);
3474
Benjamin Peterson29060642009-01-31 22:14:21 +00003475 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003476 return -1;
3477}
3478
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003479Py_ssize_t
3480PyUnicode_GetLength(PyObject *unicode)
3481{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003482 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003483 PyErr_BadArgument();
3484 return -1;
3485 }
3486
3487 return PyUnicode_GET_LENGTH(unicode);
3488}
3489
3490Py_UCS4
3491PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3492{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003493 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3494 PyErr_BadArgument();
3495 return (Py_UCS4)-1;
3496 }
3497 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3498 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003499 return (Py_UCS4)-1;
3500 }
3501 return PyUnicode_READ_CHAR(unicode, index);
3502}
3503
3504int
3505PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3506{
3507 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003508 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003509 return -1;
3510 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003511 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3512 PyErr_SetString(PyExc_IndexError, "string index out of range");
3513 return -1;
3514 }
3515 if (_PyUnicode_Dirty(unicode))
3516 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003517 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3518 index, ch);
3519 return 0;
3520}
3521
Alexander Belopolsky40018472011-02-26 01:02:56 +00003522const char *
3523PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003524{
Victor Stinner42cb4622010-09-01 19:39:01 +00003525 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003526}
3527
Victor Stinner554f3f02010-06-16 23:33:54 +00003528/* create or adjust a UnicodeDecodeError */
3529static void
3530make_decode_exception(PyObject **exceptionObject,
3531 const char *encoding,
3532 const char *input, Py_ssize_t length,
3533 Py_ssize_t startpos, Py_ssize_t endpos,
3534 const char *reason)
3535{
3536 if (*exceptionObject == NULL) {
3537 *exceptionObject = PyUnicodeDecodeError_Create(
3538 encoding, input, length, startpos, endpos, reason);
3539 }
3540 else {
3541 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3542 goto onError;
3543 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3544 goto onError;
3545 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3546 goto onError;
3547 }
3548 return;
3549
3550onError:
3551 Py_DECREF(*exceptionObject);
3552 *exceptionObject = NULL;
3553}
3554
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003555/* error handling callback helper:
3556 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003557 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003558 and adjust various state variables.
3559 return 0 on success, -1 on error
3560*/
3561
Alexander Belopolsky40018472011-02-26 01:02:56 +00003562static int
3563unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003564 const char *encoding, const char *reason,
3565 const char **input, const char **inend, Py_ssize_t *startinpos,
3566 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3567 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003568{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003569 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003570
3571 PyObject *restuple = NULL;
3572 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003573 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003574 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003575 Py_ssize_t requiredsize;
3576 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003577 const Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003578 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003579 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003580 int res = -1;
3581
3582 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003583 *errorHandler = PyCodec_LookupError(errors);
3584 if (*errorHandler == NULL)
3585 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003586 }
3587
Victor Stinner554f3f02010-06-16 23:33:54 +00003588 make_decode_exception(exceptionObject,
3589 encoding,
3590 *input, *inend - *input,
3591 *startinpos, *endinpos,
3592 reason);
3593 if (*exceptionObject == NULL)
3594 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003595
3596 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3597 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003598 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003599 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003600 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003601 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003602 }
3603 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003604 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003605
3606 /* Copy back the bytes variables, which might have been modified by the
3607 callback */
3608 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3609 if (!inputobj)
3610 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003611 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003612 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003613 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003614 *input = PyBytes_AS_STRING(inputobj);
3615 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003616 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003617 /* we can DECREF safely, as the exception has another reference,
3618 so the object won't go away. */
3619 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003620
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003621 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003622 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003623 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003624 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3625 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003626 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003627
3628 /* need more space? (at least enough for what we
3629 have+the replacement+the rest of the string (starting
3630 at the new input position), so we won't have to check space
3631 when there are no errors in the rest of the string) */
3632 repptr = PyUnicode_AS_UNICODE(repunicode);
3633 repsize = PyUnicode_GET_SIZE(repunicode);
3634 requiredsize = *outpos + repsize + insize-newpos;
3635 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003636 if (requiredsize<2*outsize)
3637 requiredsize = 2*outsize;
Victor Stinnerfe226c02011-10-03 03:52:20 +02003638 if (PyUnicode_Resize((PyObject**)output, requiredsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003639 goto onError;
3640 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003641 }
3642 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003643 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003644 Py_UNICODE_COPY(*outptr, repptr, repsize);
3645 *outptr += repsize;
3646 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003647
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003648 /* we made it! */
3649 res = 0;
3650
Benjamin Peterson29060642009-01-31 22:14:21 +00003651 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003652 Py_XDECREF(restuple);
3653 return res;
3654}
3655
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003656/* --- UTF-7 Codec -------------------------------------------------------- */
3657
Antoine Pitrou244651a2009-05-04 18:56:13 +00003658/* See RFC2152 for details. We encode conservatively and decode liberally. */
3659
3660/* Three simple macros defining base-64. */
3661
3662/* Is c a base-64 character? */
3663
3664#define IS_BASE64(c) \
3665 (((c) >= 'A' && (c) <= 'Z') || \
3666 ((c) >= 'a' && (c) <= 'z') || \
3667 ((c) >= '0' && (c) <= '9') || \
3668 (c) == '+' || (c) == '/')
3669
3670/* given that c is a base-64 character, what is its base-64 value? */
3671
3672#define FROM_BASE64(c) \
3673 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3674 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3675 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3676 (c) == '+' ? 62 : 63)
3677
3678/* What is the base-64 character of the bottom 6 bits of n? */
3679
3680#define TO_BASE64(n) \
3681 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3682
3683/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3684 * decoded as itself. We are permissive on decoding; the only ASCII
3685 * byte not decoding to itself is the + which begins a base64
3686 * string. */
3687
3688#define DECODE_DIRECT(c) \
3689 ((c) <= 127 && (c) != '+')
3690
3691/* The UTF-7 encoder treats ASCII characters differently according to
3692 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3693 * the above). See RFC2152. This array identifies these different
3694 * sets:
3695 * 0 : "Set D"
3696 * alphanumeric and '(),-./:?
3697 * 1 : "Set O"
3698 * !"#$%&*;<=>@[]^_`{|}
3699 * 2 : "whitespace"
3700 * ht nl cr sp
3701 * 3 : special (must be base64 encoded)
3702 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3703 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003704
Tim Petersced69f82003-09-16 20:30:58 +00003705static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003706char utf7_category[128] = {
3707/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3708 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3709/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3710 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3711/* sp ! " # $ % & ' ( ) * + , - . / */
3712 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3713/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3714 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3715/* @ A B C D E F G H I J K L M N O */
3716 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3717/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3718 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3719/* ` a b c d e f g h i j k l m n o */
3720 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3721/* p q r s t u v w x y z { | } ~ del */
3722 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003723};
3724
Antoine Pitrou244651a2009-05-04 18:56:13 +00003725/* ENCODE_DIRECT: this character should be encoded as itself. The
3726 * answer depends on whether we are encoding set O as itself, and also
3727 * on whether we are encoding whitespace as itself. RFC2152 makes it
3728 * clear that the answers to these questions vary between
3729 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003730
Antoine Pitrou244651a2009-05-04 18:56:13 +00003731#define ENCODE_DIRECT(c, directO, directWS) \
3732 ((c) < 128 && (c) > 0 && \
3733 ((utf7_category[(c)] == 0) || \
3734 (directWS && (utf7_category[(c)] == 2)) || \
3735 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003736
Alexander Belopolsky40018472011-02-26 01:02:56 +00003737PyObject *
3738PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003739 Py_ssize_t size,
3740 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003741{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003742 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3743}
3744
Antoine Pitrou244651a2009-05-04 18:56:13 +00003745/* The decoder. The only state we preserve is our read position,
3746 * i.e. how many characters we have consumed. So if we end in the
3747 * middle of a shift sequence we have to back off the read position
3748 * and the output to the beginning of the sequence, otherwise we lose
3749 * all the shift state (seen bits, number of bits seen, high
3750 * surrogate). */
3751
Alexander Belopolsky40018472011-02-26 01:02:56 +00003752PyObject *
3753PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003754 Py_ssize_t size,
3755 const char *errors,
3756 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003757{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003758 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003759 Py_ssize_t startinpos;
3760 Py_ssize_t endinpos;
3761 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003762 const char *e;
3763 PyUnicodeObject *unicode;
3764 Py_UNICODE *p;
3765 const char *errmsg = "";
3766 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003767 Py_UNICODE *shiftOutStart;
3768 unsigned int base64bits = 0;
3769 unsigned long base64buffer = 0;
3770 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003771 PyObject *errorHandler = NULL;
3772 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003773
3774 unicode = _PyUnicode_New(size);
3775 if (!unicode)
3776 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003777 if (size == 0) {
3778 if (consumed)
3779 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003780 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003781 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003782
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003783 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitrou244651a2009-05-04 18:56:13 +00003784 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003785 e = s + size;
3786
3787 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003788 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003789 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003790 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003791
Antoine Pitrou244651a2009-05-04 18:56:13 +00003792 if (inShift) { /* in a base-64 section */
3793 if (IS_BASE64(ch)) { /* consume a base-64 character */
3794 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3795 base64bits += 6;
3796 s++;
3797 if (base64bits >= 16) {
3798 /* we have enough bits for a UTF-16 value */
3799 Py_UNICODE outCh = (Py_UNICODE)
3800 (base64buffer >> (base64bits-16));
3801 base64bits -= 16;
3802 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3803 if (surrogate) {
3804 /* expecting a second surrogate */
3805 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3806#ifdef Py_UNICODE_WIDE
3807 *p++ = (((surrogate & 0x3FF)<<10)
3808 | (outCh & 0x3FF)) + 0x10000;
3809#else
3810 *p++ = surrogate;
3811 *p++ = outCh;
3812#endif
3813 surrogate = 0;
3814 }
3815 else {
3816 surrogate = 0;
3817 errmsg = "second surrogate missing";
3818 goto utf7Error;
3819 }
3820 }
3821 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3822 /* first surrogate */
3823 surrogate = outCh;
3824 }
3825 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3826 errmsg = "unexpected second surrogate";
3827 goto utf7Error;
3828 }
3829 else {
3830 *p++ = outCh;
3831 }
3832 }
3833 }
3834 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003835 inShift = 0;
3836 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003837 if (surrogate) {
3838 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003839 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003840 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003841 if (base64bits > 0) { /* left-over bits */
3842 if (base64bits >= 6) {
3843 /* We've seen at least one base-64 character */
3844 errmsg = "partial character in shift sequence";
3845 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003846 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003847 else {
3848 /* Some bits remain; they should be zero */
3849 if (base64buffer != 0) {
3850 errmsg = "non-zero padding bits in shift sequence";
3851 goto utf7Error;
3852 }
3853 }
3854 }
3855 if (ch != '-') {
3856 /* '-' is absorbed; other terminating
3857 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003858 *p++ = ch;
3859 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003860 }
3861 }
3862 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003863 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003864 s++; /* consume '+' */
3865 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003866 s++;
3867 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00003868 }
3869 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003870 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003871 shiftOutStart = p;
3872 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003873 }
3874 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003875 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003876 *p++ = ch;
3877 s++;
3878 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003879 else {
3880 startinpos = s-starts;
3881 s++;
3882 errmsg = "unexpected special character";
3883 goto utf7Error;
3884 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003885 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003886utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003887 outpos = p-PyUnicode_AS_UNICODE(unicode);
3888 endinpos = s-starts;
3889 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003890 errors, &errorHandler,
3891 "utf7", errmsg,
3892 &starts, &e, &startinpos, &endinpos, &exc, &s,
3893 &unicode, &outpos, &p))
3894 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003895 }
3896
Antoine Pitrou244651a2009-05-04 18:56:13 +00003897 /* end of string */
3898
3899 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3900 /* if we're in an inconsistent state, that's an error */
3901 if (surrogate ||
3902 (base64bits >= 6) ||
3903 (base64bits > 0 && base64buffer != 0)) {
3904 outpos = p-PyUnicode_AS_UNICODE(unicode);
3905 endinpos = size;
3906 if (unicode_decode_call_errorhandler(
3907 errors, &errorHandler,
3908 "utf7", "unterminated shift sequence",
3909 &starts, &e, &startinpos, &endinpos, &exc, &s,
3910 &unicode, &outpos, &p))
3911 goto onError;
3912 if (s < e)
3913 goto restart;
3914 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003915 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003916
3917 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003918 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003919 if (inShift) {
3920 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003921 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003922 }
3923 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003924 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003925 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003926 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003927
Victor Stinnerfe226c02011-10-03 03:52:20 +02003928 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003929 goto onError;
3930
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003931 Py_XDECREF(errorHandler);
3932 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02003933#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02003934 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003935 Py_DECREF(unicode);
3936 return NULL;
3937 }
Victor Stinner17efeed2011-10-04 20:05:46 +02003938#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003939 assert(_PyUnicode_CheckConsistency(unicode, 1));
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003940 return (PyObject *)unicode;
3941
Benjamin Peterson29060642009-01-31 22:14:21 +00003942 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003943 Py_XDECREF(errorHandler);
3944 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003945 Py_DECREF(unicode);
3946 return NULL;
3947}
3948
3949
Alexander Belopolsky40018472011-02-26 01:02:56 +00003950PyObject *
3951PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003952 Py_ssize_t size,
3953 int base64SetO,
3954 int base64WhiteSpace,
3955 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003956{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003957 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003958 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003959 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003960 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003961 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003962 unsigned int base64bits = 0;
3963 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003964 char * out;
3965 char * start;
3966
3967 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003968 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003969
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003970 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003971 return PyErr_NoMemory();
3972
Antoine Pitrou244651a2009-05-04 18:56:13 +00003973 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003974 if (v == NULL)
3975 return NULL;
3976
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003977 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003978 for (;i < size; ++i) {
3979 Py_UNICODE ch = s[i];
3980
Antoine Pitrou244651a2009-05-04 18:56:13 +00003981 if (inShift) {
3982 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
3983 /* shifting out */
3984 if (base64bits) { /* output remaining bits */
3985 *out++ = TO_BASE64(base64buffer << (6-base64bits));
3986 base64buffer = 0;
3987 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003988 }
3989 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003990 /* Characters not in the BASE64 set implicitly unshift the sequence
3991 so no '-' is required, except if the character is itself a '-' */
3992 if (IS_BASE64(ch) || ch == '-') {
3993 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003994 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003995 *out++ = (char) ch;
3996 }
3997 else {
3998 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00003999 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004000 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004001 else { /* not in a shift sequence */
4002 if (ch == '+') {
4003 *out++ = '+';
4004 *out++ = '-';
4005 }
4006 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4007 *out++ = (char) ch;
4008 }
4009 else {
4010 *out++ = '+';
4011 inShift = 1;
4012 goto encode_char;
4013 }
4014 }
4015 continue;
4016encode_char:
4017#ifdef Py_UNICODE_WIDE
4018 if (ch >= 0x10000) {
4019 /* code first surrogate */
4020 base64bits += 16;
4021 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4022 while (base64bits >= 6) {
4023 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4024 base64bits -= 6;
4025 }
4026 /* prepare second surrogate */
4027 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4028 }
4029#endif
4030 base64bits += 16;
4031 base64buffer = (base64buffer << 16) | ch;
4032 while (base64bits >= 6) {
4033 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4034 base64bits -= 6;
4035 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004036 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004037 if (base64bits)
4038 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4039 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004040 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004041 if (_PyBytes_Resize(&v, out - start) < 0)
4042 return NULL;
4043 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004044}
4045
Antoine Pitrou244651a2009-05-04 18:56:13 +00004046#undef IS_BASE64
4047#undef FROM_BASE64
4048#undef TO_BASE64
4049#undef DECODE_DIRECT
4050#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004051
Guido van Rossumd57fd912000-03-10 22:53:23 +00004052/* --- UTF-8 Codec -------------------------------------------------------- */
4053
Tim Petersced69f82003-09-16 20:30:58 +00004054static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004055char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004056 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4057 illegal prefix. See RFC 3629 for details */
4058 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4059 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004060 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004061 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4062 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4063 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4064 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004065 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4066 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 +00004067 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4068 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004069 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4070 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4071 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4072 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4073 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 +00004074};
4075
Alexander Belopolsky40018472011-02-26 01:02:56 +00004076PyObject *
4077PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004078 Py_ssize_t size,
4079 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004080{
Walter Dörwald69652032004-09-07 20:24:22 +00004081 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4082}
4083
Antoine Pitrouab868312009-01-10 15:40:25 +00004084/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4085#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4086
4087/* Mask to quickly check whether a C 'long' contains a
4088 non-ASCII, UTF8-encoded char. */
4089#if (SIZEOF_LONG == 8)
4090# define ASCII_CHAR_MASK 0x8080808080808080L
4091#elif (SIZEOF_LONG == 4)
4092# define ASCII_CHAR_MASK 0x80808080L
4093#else
4094# error C 'long' size should be either 4 or 8!
4095#endif
4096
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004097/* Scans a UTF-8 string and returns the maximum character to be expected,
4098 the size of the decoded unicode string and if any major errors were
4099 encountered.
4100
4101 This function does check basic UTF-8 sanity, it does however NOT CHECK
4102 if the string contains surrogates, and if all continuation bytes are
4103 within the correct ranges, these checks are performed in
4104 PyUnicode_DecodeUTF8Stateful.
4105
4106 If it sets has_errors to 1, it means the value of unicode_size and max_char
4107 will be bogus and you should not rely on useful information in them.
4108 */
4109static Py_UCS4
4110utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
4111 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
4112 int *has_errors)
4113{
4114 Py_ssize_t n;
4115 Py_ssize_t char_count = 0;
4116 Py_UCS4 max_char = 127, new_max;
4117 Py_UCS4 upper_bound;
4118 const unsigned char *p = (const unsigned char *)s;
4119 const unsigned char *end = p + string_size;
4120 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
4121 int err = 0;
4122
4123 for (; p < end && !err; ++p, ++char_count) {
4124 /* Only check value if it's not a ASCII char... */
4125 if (*p < 0x80) {
4126 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4127 an explanation. */
4128 if (!((size_t) p & LONG_PTR_MASK)) {
4129 /* Help register allocation */
4130 register const unsigned char *_p = p;
4131 while (_p < aligned_end) {
4132 unsigned long value = *(unsigned long *) _p;
4133 if (value & ASCII_CHAR_MASK)
4134 break;
4135 _p += SIZEOF_LONG;
4136 char_count += SIZEOF_LONG;
4137 }
4138 p = _p;
4139 if (p == end)
4140 break;
4141 }
4142 }
4143 if (*p >= 0x80) {
4144 n = utf8_code_length[*p];
4145 new_max = max_char;
4146 switch (n) {
4147 /* invalid start byte */
4148 case 0:
4149 err = 1;
4150 break;
4151 case 2:
4152 /* Code points between 0x00FF and 0x07FF inclusive.
4153 Approximate the upper bound of the code point,
4154 if this flips over 255 we can be sure it will be more
4155 than 255 and the string will need 2 bytes per code coint,
4156 if it stays under or equal to 255, we can be sure 1 byte
4157 is enough.
4158 ((*p & 0b00011111) << 6) | 0b00111111 */
4159 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
4160 if (max_char < upper_bound)
4161 new_max = upper_bound;
4162 /* Ensure we track at least that we left ASCII space. */
4163 if (new_max < 128)
4164 new_max = 128;
4165 break;
4166 case 3:
4167 /* Between 0x0FFF and 0xFFFF inclusive, so values are
4168 always > 255 and <= 65535 and will always need 2 bytes. */
4169 if (max_char < 65535)
4170 new_max = 65535;
4171 break;
4172 case 4:
4173 /* Code point will be above 0xFFFF for sure in this case. */
4174 new_max = 65537;
4175 break;
4176 /* Internal error, this should be caught by the first if */
4177 case 1:
4178 default:
4179 assert(0 && "Impossible case in utf8_max_char_and_size");
4180 err = 1;
4181 }
4182 /* Instead of number of overall bytes for this code point,
Georg Brandl7597add2011-10-05 16:36:47 +02004183 n contains the number of following bytes: */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004184 --n;
4185 /* Check if the follow up chars are all valid continuation bytes */
4186 if (n >= 1) {
4187 const unsigned char *cont;
4188 if ((p + n) >= end) {
4189 if (consumed == 0)
4190 /* incomplete data, non-incremental decoding */
4191 err = 1;
4192 break;
4193 }
4194 for (cont = p + 1; cont < (p + n); ++cont) {
4195 if ((*cont & 0xc0) != 0x80) {
4196 err = 1;
4197 break;
4198 }
4199 }
4200 p += n;
4201 }
4202 else
4203 err = 1;
4204 max_char = new_max;
4205 }
4206 }
4207
4208 if (unicode_size)
4209 *unicode_size = char_count;
4210 if (has_errors)
4211 *has_errors = err;
4212 return max_char;
4213}
4214
4215/* Similar to PyUnicode_WRITE but can also write into wstr field
4216 of the legacy unicode representation */
4217#define WRITE_FLEXIBLE_OR_WSTR(kind, buf, index, value) \
4218 do { \
4219 const int k_ = (kind); \
4220 if (k_ == PyUnicode_WCHAR_KIND) \
4221 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
4222 else if (k_ == PyUnicode_1BYTE_KIND) \
4223 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
4224 else if (k_ == PyUnicode_2BYTE_KIND) \
4225 ((Py_UCS2 *)(buf))[(index)] = (Py_UCS2)(value); \
4226 else \
4227 ((Py_UCS4 *)(buf))[(index)] = (Py_UCS4)(value); \
4228 } while (0)
4229
Alexander Belopolsky40018472011-02-26 01:02:56 +00004230PyObject *
4231PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004232 Py_ssize_t size,
4233 const char *errors,
4234 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004235{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004236 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004237 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004238 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004239 Py_ssize_t startinpos;
4240 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004241 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004242 PyUnicodeObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004243 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004244 PyObject *errorHandler = NULL;
4245 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004246 Py_UCS4 maxchar = 0;
4247 Py_ssize_t unicode_size;
4248 Py_ssize_t i;
4249 int kind;
4250 void *data;
4251 int has_errors;
4252 Py_UNICODE *error_outptr;
4253#if SIZEOF_WCHAR_T == 2
4254 Py_ssize_t wchar_offset = 0;
4255#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004256
Walter Dörwald69652032004-09-07 20:24:22 +00004257 if (size == 0) {
4258 if (consumed)
4259 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004260 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004261 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004262 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
4263 consumed, &has_errors);
4264 if (has_errors) {
4265 unicode = _PyUnicode_New(size);
4266 if (!unicode)
4267 return NULL;
4268 kind = PyUnicode_WCHAR_KIND;
4269 data = PyUnicode_AS_UNICODE(unicode);
4270 assert(data != NULL);
4271 }
4272 else {
4273 unicode = (PyUnicodeObject *)PyUnicode_New(unicode_size, maxchar);
4274 if (!unicode)
4275 return NULL;
4276 /* When the string is ASCII only, just use memcpy and return.
4277 unicode_size may be != size if there is an incomplete UTF-8
4278 sequence at the end of the ASCII block. */
4279 if (maxchar < 128 && size == unicode_size) {
4280 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4281 return (PyObject *)unicode;
4282 }
4283 kind = PyUnicode_KIND(unicode);
4284 data = PyUnicode_DATA(unicode);
4285 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004286 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004287 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004288 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004289 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004290
4291 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004292 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004293
4294 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004295 /* Fast path for runs of ASCII characters. Given that common UTF-8
4296 input will consist of an overwhelming majority of ASCII
4297 characters, we try to optimize for this case by checking
4298 as many characters as a C 'long' can contain.
4299 First, check if we can do an aligned read, as most CPUs have
4300 a penalty for unaligned reads.
4301 */
4302 if (!((size_t) s & LONG_PTR_MASK)) {
4303 /* Help register allocation */
4304 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004305 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004306 while (_s < aligned_end) {
4307 /* Read a whole long at a time (either 4 or 8 bytes),
4308 and do a fast unrolled copy if it only contains ASCII
4309 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004310 unsigned long value = *(unsigned long *) _s;
4311 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004312 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004313 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+0, _s[0]);
4314 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+1, _s[1]);
4315 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+2, _s[2]);
4316 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004317#if (SIZEOF_LONG == 8)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004318 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+4, _s[4]);
4319 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+5, _s[5]);
4320 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+6, _s[6]);
4321 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004322#endif
4323 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004324 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004325 }
4326 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004327 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004328 if (s == e)
4329 break;
4330 ch = (unsigned char)*s;
4331 }
4332 }
4333
4334 if (ch < 0x80) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004335 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004336 s++;
4337 continue;
4338 }
4339
4340 n = utf8_code_length[ch];
4341
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004342 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004343 if (consumed)
4344 break;
4345 else {
4346 errmsg = "unexpected end of data";
4347 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004348 endinpos = startinpos+1;
4349 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4350 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004351 goto utf8Error;
4352 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004353 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004354
4355 switch (n) {
4356
4357 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004358 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004359 startinpos = s-starts;
4360 endinpos = startinpos+1;
4361 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004362
4363 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004364 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004365 startinpos = s-starts;
4366 endinpos = startinpos+1;
4367 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004368
4369 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004370 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004371 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004372 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004373 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004374 goto utf8Error;
4375 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004376 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004377 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004378 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004379 break;
4380
4381 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004382 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4383 will result in surrogates in range d800-dfff. Surrogates are
4384 not valid UTF-8 so they are rejected.
4385 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4386 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004387 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004388 (s[2] & 0xc0) != 0x80 ||
4389 ((unsigned char)s[0] == 0xE0 &&
4390 (unsigned char)s[1] < 0xA0) ||
4391 ((unsigned char)s[0] == 0xED &&
4392 (unsigned char)s[1] > 0x9F)) {
4393 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004394 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004395 endinpos = startinpos + 1;
4396
4397 /* if s[1] first two bits are 1 and 0, then the invalid
4398 continuation byte is s[2], so increment endinpos by 1,
4399 if not, s[1] is invalid and endinpos doesn't need to
4400 be incremented. */
4401 if ((s[1] & 0xC0) == 0x80)
4402 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004403 goto utf8Error;
4404 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004405 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004406 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004407 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004408 break;
4409
4410 case 4:
4411 if ((s[1] & 0xc0) != 0x80 ||
4412 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004413 (s[3] & 0xc0) != 0x80 ||
4414 ((unsigned char)s[0] == 0xF0 &&
4415 (unsigned char)s[1] < 0x90) ||
4416 ((unsigned char)s[0] == 0xF4 &&
4417 (unsigned char)s[1] > 0x8F)) {
4418 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004419 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004420 endinpos = startinpos + 1;
4421 if ((s[1] & 0xC0) == 0x80) {
4422 endinpos++;
4423 if ((s[2] & 0xC0) == 0x80)
4424 endinpos++;
4425 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004426 goto utf8Error;
4427 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004428 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004429 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4430 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4431
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004432 /* If the string is flexible or we have native UCS-4, write
4433 directly.. */
4434 if (sizeof(Py_UNICODE) > 2 || kind != PyUnicode_WCHAR_KIND)
4435 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Tim Petersced69f82003-09-16 20:30:58 +00004436
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004437 else {
4438 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00004439
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004440 /* translate from 10000..10FFFF to 0..FFFF */
4441 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00004442
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004443 /* high surrogate = top 10 bits added to D800 */
4444 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4445 (Py_UNICODE)(0xD800 + (ch >> 10)));
4446
4447 /* low surrogate = bottom 10 bits added to DC00 */
4448 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4449 (Py_UNICODE)(0xDC00 + (ch & 0x03FF)));
4450 }
4451#if SIZEOF_WCHAR_T == 2
4452 wchar_offset++;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004453#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004454 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004455 }
4456 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004457 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004458
Benjamin Peterson29060642009-01-31 22:14:21 +00004459 utf8Error:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004460 /* If this is not yet a resizable string, make it one.. */
4461 if (kind != PyUnicode_WCHAR_KIND) {
4462 const Py_UNICODE *u;
4463 PyUnicodeObject *new_unicode = _PyUnicode_New(size);
4464 if (!new_unicode)
4465 goto onError;
4466 u = PyUnicode_AsUnicode((PyObject *)unicode);
4467 if (!u)
4468 goto onError;
4469#if SIZEOF_WCHAR_T == 2
4470 i += wchar_offset;
4471#endif
4472 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(new_unicode), u, i);
4473 Py_DECREF(unicode);
4474 unicode = new_unicode;
4475 kind = 0;
4476 data = PyUnicode_AS_UNICODE(new_unicode);
4477 assert(data != NULL);
4478 }
4479 error_outptr = PyUnicode_AS_UNICODE(unicode) + i;
Benjamin Peterson29060642009-01-31 22:14:21 +00004480 if (unicode_decode_call_errorhandler(
4481 errors, &errorHandler,
4482 "utf8", errmsg,
4483 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004484 &unicode, &i, &error_outptr))
Benjamin Peterson29060642009-01-31 22:14:21 +00004485 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004486 /* Update data because unicode_decode_call_errorhandler might have
4487 re-created or resized the unicode object. */
4488 data = PyUnicode_AS_UNICODE(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004489 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004490 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004491 /* Ensure the unicode_size calculation above was correct: */
4492 assert(kind == PyUnicode_WCHAR_KIND || i == unicode_size);
4493
Walter Dörwald69652032004-09-07 20:24:22 +00004494 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004495 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004496
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004497 /* Adjust length and ready string when it contained errors and
4498 is of the old resizable kind. */
4499 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004500 if (PyUnicode_Resize((PyObject**)&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004501 goto onError;
4502 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004503
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004504 Py_XDECREF(errorHandler);
4505 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004506#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004507 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004508 Py_DECREF(unicode);
4509 return NULL;
4510 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004511#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004512 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00004513 return (PyObject *)unicode;
4514
Benjamin Peterson29060642009-01-31 22:14:21 +00004515 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004516 Py_XDECREF(errorHandler);
4517 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004518 Py_DECREF(unicode);
4519 return NULL;
4520}
4521
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004522#undef WRITE_FLEXIBLE_OR_WSTR
Antoine Pitrouab868312009-01-10 15:40:25 +00004523
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004524#ifdef __APPLE__
4525
4526/* Simplified UTF-8 decoder using surrogateescape error handler,
4527 used to decode the command line arguments on Mac OS X. */
4528
4529wchar_t*
4530_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4531{
4532 int n;
4533 const char *e;
4534 wchar_t *unicode, *p;
4535
4536 /* Note: size will always be longer than the resulting Unicode
4537 character count */
4538 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4539 PyErr_NoMemory();
4540 return NULL;
4541 }
4542 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4543 if (!unicode)
4544 return NULL;
4545
4546 /* Unpack UTF-8 encoded data */
4547 p = unicode;
4548 e = s + size;
4549 while (s < e) {
4550 Py_UCS4 ch = (unsigned char)*s;
4551
4552 if (ch < 0x80) {
4553 *p++ = (wchar_t)ch;
4554 s++;
4555 continue;
4556 }
4557
4558 n = utf8_code_length[ch];
4559 if (s + n > e) {
4560 goto surrogateescape;
4561 }
4562
4563 switch (n) {
4564 case 0:
4565 case 1:
4566 goto surrogateescape;
4567
4568 case 2:
4569 if ((s[1] & 0xc0) != 0x80)
4570 goto surrogateescape;
4571 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4572 assert ((ch > 0x007F) && (ch <= 0x07FF));
4573 *p++ = (wchar_t)ch;
4574 break;
4575
4576 case 3:
4577 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4578 will result in surrogates in range d800-dfff. Surrogates are
4579 not valid UTF-8 so they are rejected.
4580 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4581 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4582 if ((s[1] & 0xc0) != 0x80 ||
4583 (s[2] & 0xc0) != 0x80 ||
4584 ((unsigned char)s[0] == 0xE0 &&
4585 (unsigned char)s[1] < 0xA0) ||
4586 ((unsigned char)s[0] == 0xED &&
4587 (unsigned char)s[1] > 0x9F)) {
4588
4589 goto surrogateescape;
4590 }
4591 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4592 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004593 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004594 break;
4595
4596 case 4:
4597 if ((s[1] & 0xc0) != 0x80 ||
4598 (s[2] & 0xc0) != 0x80 ||
4599 (s[3] & 0xc0) != 0x80 ||
4600 ((unsigned char)s[0] == 0xF0 &&
4601 (unsigned char)s[1] < 0x90) ||
4602 ((unsigned char)s[0] == 0xF4 &&
4603 (unsigned char)s[1] > 0x8F)) {
4604 goto surrogateescape;
4605 }
4606 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4607 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4608 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4609
4610#if SIZEOF_WCHAR_T == 4
4611 *p++ = (wchar_t)ch;
4612#else
4613 /* compute and append the two surrogates: */
4614
4615 /* translate from 10000..10FFFF to 0..FFFF */
4616 ch -= 0x10000;
4617
4618 /* high surrogate = top 10 bits added to D800 */
4619 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4620
4621 /* low surrogate = bottom 10 bits added to DC00 */
4622 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4623#endif
4624 break;
4625 }
4626 s += n;
4627 continue;
4628
4629 surrogateescape:
4630 *p++ = 0xDC00 + ch;
4631 s++;
4632 }
4633 *p = L'\0';
4634 return unicode;
4635}
4636
4637#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004638
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004639/* Primary internal function which creates utf8 encoded bytes objects.
4640
4641 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004642 and allocate exactly as much space needed at the end. Else allocate the
4643 maximum possible needed (4 result bytes per Unicode character), and return
4644 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004645*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004646PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004647_PyUnicode_AsUTF8String(PyObject *obj, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004648{
Tim Peters602f7402002-04-27 18:03:26 +00004649#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004650
Guido van Rossum98297ee2007-11-06 21:34:58 +00004651 Py_ssize_t i; /* index into s of next input byte */
4652 PyObject *result; /* result string object */
4653 char *p; /* next free byte in output buffer */
4654 Py_ssize_t nallocated; /* number of result bytes allocated */
4655 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004656 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004657 PyObject *errorHandler = NULL;
4658 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004659 int kind;
4660 void *data;
4661 Py_ssize_t size;
4662 PyUnicodeObject *unicode = (PyUnicodeObject *)obj;
4663#if SIZEOF_WCHAR_T == 2
4664 Py_ssize_t wchar_offset = 0;
4665#endif
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004666
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004667 if (!PyUnicode_Check(unicode)) {
4668 PyErr_BadArgument();
4669 return NULL;
4670 }
4671
4672 if (PyUnicode_READY(unicode) == -1)
4673 return NULL;
4674
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004675 if (PyUnicode_UTF8(unicode))
4676 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4677 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004678
4679 kind = PyUnicode_KIND(unicode);
4680 data = PyUnicode_DATA(unicode);
4681 size = PyUnicode_GET_LENGTH(unicode);
4682
Tim Peters602f7402002-04-27 18:03:26 +00004683 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004684
Tim Peters602f7402002-04-27 18:03:26 +00004685 if (size <= MAX_SHORT_UNICHARS) {
4686 /* Write into the stack buffer; nallocated can't overflow.
4687 * At the end, we'll allocate exactly as much heap space as it
4688 * turns out we need.
4689 */
4690 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004691 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004692 p = stackbuf;
4693 }
4694 else {
4695 /* Overallocate on the heap, and give the excess back at the end. */
4696 nallocated = size * 4;
4697 if (nallocated / 4 != size) /* overflow! */
4698 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004699 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004700 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004701 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004702 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004703 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004704
Tim Peters602f7402002-04-27 18:03:26 +00004705 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004706 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004707
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004708 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004709 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004710 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004711
Guido van Rossumd57fd912000-03-10 22:53:23 +00004712 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004713 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004714 *p++ = (char)(0xc0 | (ch >> 6));
4715 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004716 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004717 Py_ssize_t newpos;
4718 PyObject *rep;
4719 Py_ssize_t repsize, k, startpos;
4720 startpos = i-1;
4721#if SIZEOF_WCHAR_T == 2
4722 startpos += wchar_offset;
Victor Stinner445a6232010-04-22 20:01:57 +00004723#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004724 rep = unicode_encode_call_errorhandler(
4725 errors, &errorHandler, "utf-8", "surrogates not allowed",
4726 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
4727 &exc, startpos, startpos+1, &newpos);
4728 if (!rep)
4729 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004730
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004731 if (PyBytes_Check(rep))
4732 repsize = PyBytes_GET_SIZE(rep);
4733 else
4734 repsize = PyUnicode_GET_SIZE(rep);
4735
4736 if (repsize > 4) {
4737 Py_ssize_t offset;
4738
4739 if (result == NULL)
4740 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004741 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004742 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004743
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004744 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4745 /* integer overflow */
4746 PyErr_NoMemory();
4747 goto error;
4748 }
4749 nallocated += repsize - 4;
4750 if (result != NULL) {
4751 if (_PyBytes_Resize(&result, nallocated) < 0)
4752 goto error;
4753 } else {
4754 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004755 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004756 goto error;
4757 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4758 }
4759 p = PyBytes_AS_STRING(result) + offset;
4760 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004761
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004762 if (PyBytes_Check(rep)) {
4763 char *prep = PyBytes_AS_STRING(rep);
4764 for(k = repsize; k > 0; k--)
4765 *p++ = *prep++;
4766 } else /* rep is unicode */ {
4767 const Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
4768 Py_UNICODE c;
4769
4770 for(k=0; k<repsize; k++) {
4771 c = prep[k];
4772 if (0x80 <= c) {
4773 raise_encode_exception(&exc, "utf-8",
4774 PyUnicode_AS_UNICODE(unicode),
4775 size, i-1, i,
4776 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004777 goto error;
4778 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004779 *p++ = (char)prep[k];
Victor Stinner31be90b2010-04-22 19:38:16 +00004780 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004781 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004782 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004783 } else if (ch < 0x10000) {
4784 *p++ = (char)(0xe0 | (ch >> 12));
4785 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4786 *p++ = (char)(0x80 | (ch & 0x3f));
4787 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004788 /* Encode UCS4 Unicode ordinals */
4789 *p++ = (char)(0xf0 | (ch >> 18));
4790 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4791 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4792 *p++ = (char)(0x80 | (ch & 0x3f));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004793#if SIZEOF_WCHAR_T == 2
4794 wchar_offset++;
4795#endif
Tim Peters602f7402002-04-27 18:03:26 +00004796 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004797 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004798
Guido van Rossum98297ee2007-11-06 21:34:58 +00004799 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004800 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004801 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004802 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004803 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004804 }
4805 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004806 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004807 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004808 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004809 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004810 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004811
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004812 Py_XDECREF(errorHandler);
4813 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004814 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004815 error:
4816 Py_XDECREF(errorHandler);
4817 Py_XDECREF(exc);
4818 Py_XDECREF(result);
4819 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004820
Tim Peters602f7402002-04-27 18:03:26 +00004821#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004822}
4823
Alexander Belopolsky40018472011-02-26 01:02:56 +00004824PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004825PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4826 Py_ssize_t size,
4827 const char *errors)
4828{
4829 PyObject *v, *unicode;
4830
4831 unicode = PyUnicode_FromUnicode(s, size);
4832 if (unicode == NULL)
4833 return NULL;
4834 v = _PyUnicode_AsUTF8String(unicode, errors);
4835 Py_DECREF(unicode);
4836 return v;
4837}
4838
4839PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004840PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004841{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004842 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004843}
4844
Walter Dörwald41980ca2007-08-16 21:55:45 +00004845/* --- UTF-32 Codec ------------------------------------------------------- */
4846
4847PyObject *
4848PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004849 Py_ssize_t size,
4850 const char *errors,
4851 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004852{
4853 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4854}
4855
4856PyObject *
4857PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004858 Py_ssize_t size,
4859 const char *errors,
4860 int *byteorder,
4861 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004862{
4863 const char *starts = s;
4864 Py_ssize_t startinpos;
4865 Py_ssize_t endinpos;
4866 Py_ssize_t outpos;
4867 PyUnicodeObject *unicode;
4868 Py_UNICODE *p;
4869#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004870 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004871 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004872#else
4873 const int pairs = 0;
4874#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00004875 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004876 int bo = 0; /* assume native ordering by default */
4877 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004878 /* Offsets from q for retrieving bytes in the right order. */
4879#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4880 int iorder[] = {0, 1, 2, 3};
4881#else
4882 int iorder[] = {3, 2, 1, 0};
4883#endif
4884 PyObject *errorHandler = NULL;
4885 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004886
Walter Dörwald41980ca2007-08-16 21:55:45 +00004887 q = (unsigned char *)s;
4888 e = q + size;
4889
4890 if (byteorder)
4891 bo = *byteorder;
4892
4893 /* Check for BOM marks (U+FEFF) in the input and adjust current
4894 byte order setting accordingly. In native mode, the leading BOM
4895 mark is skipped, in all other modes, it is copied to the output
4896 stream as-is (giving a ZWNBSP character). */
4897 if (bo == 0) {
4898 if (size >= 4) {
4899 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004900 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004901#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004902 if (bom == 0x0000FEFF) {
4903 q += 4;
4904 bo = -1;
4905 }
4906 else if (bom == 0xFFFE0000) {
4907 q += 4;
4908 bo = 1;
4909 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004910#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004911 if (bom == 0x0000FEFF) {
4912 q += 4;
4913 bo = 1;
4914 }
4915 else if (bom == 0xFFFE0000) {
4916 q += 4;
4917 bo = -1;
4918 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004919#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004920 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004921 }
4922
4923 if (bo == -1) {
4924 /* force LE */
4925 iorder[0] = 0;
4926 iorder[1] = 1;
4927 iorder[2] = 2;
4928 iorder[3] = 3;
4929 }
4930 else if (bo == 1) {
4931 /* force BE */
4932 iorder[0] = 3;
4933 iorder[1] = 2;
4934 iorder[2] = 1;
4935 iorder[3] = 0;
4936 }
4937
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004938 /* On narrow builds we split characters outside the BMP into two
4939 codepoints => count how much extra space we need. */
4940#ifndef Py_UNICODE_WIDE
4941 for (qq = q; qq < e; qq += 4)
4942 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
4943 pairs++;
4944#endif
4945
4946 /* This might be one to much, because of a BOM */
4947 unicode = _PyUnicode_New((size+3)/4+pairs);
4948 if (!unicode)
4949 return NULL;
4950 if (size == 0)
4951 return (PyObject *)unicode;
4952
4953 /* Unpack UTF-32 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004954 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004955
Walter Dörwald41980ca2007-08-16 21:55:45 +00004956 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004957 Py_UCS4 ch;
4958 /* remaining bytes at the end? (size should be divisible by 4) */
4959 if (e-q<4) {
4960 if (consumed)
4961 break;
4962 errmsg = "truncated data";
4963 startinpos = ((const char *)q)-starts;
4964 endinpos = ((const char *)e)-starts;
4965 goto utf32Error;
4966 /* The remaining input chars are ignored if the callback
4967 chooses to skip the input */
4968 }
4969 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
4970 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004971
Benjamin Peterson29060642009-01-31 22:14:21 +00004972 if (ch >= 0x110000)
4973 {
4974 errmsg = "codepoint not in range(0x110000)";
4975 startinpos = ((const char *)q)-starts;
4976 endinpos = startinpos+4;
4977 goto utf32Error;
4978 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004979#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004980 if (ch >= 0x10000)
4981 {
4982 *p++ = 0xD800 | ((ch-0x10000) >> 10);
4983 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
4984 }
4985 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00004986#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004987 *p++ = ch;
4988 q += 4;
4989 continue;
4990 utf32Error:
4991 outpos = p-PyUnicode_AS_UNICODE(unicode);
4992 if (unicode_decode_call_errorhandler(
4993 errors, &errorHandler,
4994 "utf32", errmsg,
4995 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
4996 &unicode, &outpos, &p))
4997 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004998 }
4999
5000 if (byteorder)
5001 *byteorder = bo;
5002
5003 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005004 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005005
5006 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02005007 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005008 goto onError;
5009
5010 Py_XDECREF(errorHandler);
5011 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005012#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005013 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005014 Py_DECREF(unicode);
5015 return NULL;
5016 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005017#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005018 assert(_PyUnicode_CheckConsistency(unicode, 1));
Walter Dörwald41980ca2007-08-16 21:55:45 +00005019 return (PyObject *)unicode;
5020
Benjamin Peterson29060642009-01-31 22:14:21 +00005021 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005022 Py_DECREF(unicode);
5023 Py_XDECREF(errorHandler);
5024 Py_XDECREF(exc);
5025 return NULL;
5026}
5027
5028PyObject *
5029PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005030 Py_ssize_t size,
5031 const char *errors,
5032 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005033{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005034 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005035 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005036 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005037#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005038 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005039#else
5040 const int pairs = 0;
5041#endif
5042 /* Offsets from p for storing byte pairs in the right order. */
5043#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5044 int iorder[] = {0, 1, 2, 3};
5045#else
5046 int iorder[] = {3, 2, 1, 0};
5047#endif
5048
Benjamin Peterson29060642009-01-31 22:14:21 +00005049#define STORECHAR(CH) \
5050 do { \
5051 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5052 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5053 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5054 p[iorder[0]] = (CH) & 0xff; \
5055 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005056 } while(0)
5057
5058 /* In narrow builds we can output surrogate pairs as one codepoint,
5059 so we need less space. */
5060#ifndef Py_UNICODE_WIDE
5061 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005062 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
5063 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
5064 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005065#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005066 nsize = (size - pairs + (byteorder == 0));
5067 bytesize = nsize * 4;
5068 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005069 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005070 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005071 if (v == NULL)
5072 return NULL;
5073
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005074 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005075 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005076 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005077 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005078 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005079
5080 if (byteorder == -1) {
5081 /* force LE */
5082 iorder[0] = 0;
5083 iorder[1] = 1;
5084 iorder[2] = 2;
5085 iorder[3] = 3;
5086 }
5087 else if (byteorder == 1) {
5088 /* force BE */
5089 iorder[0] = 3;
5090 iorder[1] = 2;
5091 iorder[2] = 1;
5092 iorder[3] = 0;
5093 }
5094
5095 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005096 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005097#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005098 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
5099 Py_UCS4 ch2 = *s;
5100 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
5101 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
5102 s++;
5103 size--;
5104 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005105 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005106#endif
5107 STORECHAR(ch);
5108 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005109
5110 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005111 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005112#undef STORECHAR
5113}
5114
Alexander Belopolsky40018472011-02-26 01:02:56 +00005115PyObject *
5116PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005117{
5118 if (!PyUnicode_Check(unicode)) {
5119 PyErr_BadArgument();
5120 return NULL;
5121 }
5122 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005123 PyUnicode_GET_SIZE(unicode),
5124 NULL,
5125 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005126}
5127
Guido van Rossumd57fd912000-03-10 22:53:23 +00005128/* --- UTF-16 Codec ------------------------------------------------------- */
5129
Tim Peters772747b2001-08-09 22:21:55 +00005130PyObject *
5131PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005132 Py_ssize_t size,
5133 const char *errors,
5134 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005135{
Walter Dörwald69652032004-09-07 20:24:22 +00005136 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5137}
5138
Antoine Pitrouab868312009-01-10 15:40:25 +00005139/* Two masks for fast checking of whether a C 'long' may contain
5140 UTF16-encoded surrogate characters. This is an efficient heuristic,
5141 assuming that non-surrogate characters with a code point >= 0x8000 are
5142 rare in most input.
5143 FAST_CHAR_MASK is used when the input is in native byte ordering,
5144 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005145*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005146#if (SIZEOF_LONG == 8)
5147# define FAST_CHAR_MASK 0x8000800080008000L
5148# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5149#elif (SIZEOF_LONG == 4)
5150# define FAST_CHAR_MASK 0x80008000L
5151# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5152#else
5153# error C 'long' size should be either 4 or 8!
5154#endif
5155
Walter Dörwald69652032004-09-07 20:24:22 +00005156PyObject *
5157PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005158 Py_ssize_t size,
5159 const char *errors,
5160 int *byteorder,
5161 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005162{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005163 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005164 Py_ssize_t startinpos;
5165 Py_ssize_t endinpos;
5166 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005167 PyUnicodeObject *unicode;
5168 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00005169 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005170 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005171 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005172 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005173 /* Offsets from q for retrieving byte pairs in the right order. */
5174#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5175 int ihi = 1, ilo = 0;
5176#else
5177 int ihi = 0, ilo = 1;
5178#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005179 PyObject *errorHandler = NULL;
5180 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005181
5182 /* Note: size will always be longer than the resulting Unicode
5183 character count */
5184 unicode = _PyUnicode_New(size);
5185 if (!unicode)
5186 return NULL;
5187 if (size == 0)
5188 return (PyObject *)unicode;
5189
5190 /* Unpack UTF-16 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005191 p = PyUnicode_AS_UNICODE(unicode);
Tim Peters772747b2001-08-09 22:21:55 +00005192 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005193 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005194
5195 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005196 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005197
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005198 /* Check for BOM marks (U+FEFF) in the input and adjust current
5199 byte order setting accordingly. In native mode, the leading BOM
5200 mark is skipped, in all other modes, it is copied to the output
5201 stream as-is (giving a ZWNBSP character). */
5202 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005203 if (size >= 2) {
5204 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005205#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005206 if (bom == 0xFEFF) {
5207 q += 2;
5208 bo = -1;
5209 }
5210 else if (bom == 0xFFFE) {
5211 q += 2;
5212 bo = 1;
5213 }
Tim Petersced69f82003-09-16 20:30:58 +00005214#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005215 if (bom == 0xFEFF) {
5216 q += 2;
5217 bo = 1;
5218 }
5219 else if (bom == 0xFFFE) {
5220 q += 2;
5221 bo = -1;
5222 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005223#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005224 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005225 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005226
Tim Peters772747b2001-08-09 22:21:55 +00005227 if (bo == -1) {
5228 /* force LE */
5229 ihi = 1;
5230 ilo = 0;
5231 }
5232 else if (bo == 1) {
5233 /* force BE */
5234 ihi = 0;
5235 ilo = 1;
5236 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005237#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5238 native_ordering = ilo < ihi;
5239#else
5240 native_ordering = ilo > ihi;
5241#endif
Tim Peters772747b2001-08-09 22:21:55 +00005242
Antoine Pitrouab868312009-01-10 15:40:25 +00005243 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005244 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005245 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005246 /* First check for possible aligned read of a C 'long'. Unaligned
5247 reads are more expensive, better to defer to another iteration. */
5248 if (!((size_t) q & LONG_PTR_MASK)) {
5249 /* Fast path for runs of non-surrogate chars. */
5250 register const unsigned char *_q = q;
5251 Py_UNICODE *_p = p;
5252 if (native_ordering) {
5253 /* Native ordering is simple: as long as the input cannot
5254 possibly contain a surrogate char, do an unrolled copy
5255 of several 16-bit code points to the target object.
5256 The non-surrogate check is done on several input bytes
5257 at a time (as many as a C 'long' can contain). */
5258 while (_q < aligned_end) {
5259 unsigned long data = * (unsigned long *) _q;
5260 if (data & FAST_CHAR_MASK)
5261 break;
5262 _p[0] = ((unsigned short *) _q)[0];
5263 _p[1] = ((unsigned short *) _q)[1];
5264#if (SIZEOF_LONG == 8)
5265 _p[2] = ((unsigned short *) _q)[2];
5266 _p[3] = ((unsigned short *) _q)[3];
5267#endif
5268 _q += SIZEOF_LONG;
5269 _p += SIZEOF_LONG / 2;
5270 }
5271 }
5272 else {
5273 /* Byteswapped ordering is similar, but we must decompose
5274 the copy bytewise, and take care of zero'ing out the
5275 upper bytes if the target object is in 32-bit units
5276 (that is, in UCS-4 builds). */
5277 while (_q < aligned_end) {
5278 unsigned long data = * (unsigned long *) _q;
5279 if (data & SWAPPED_FAST_CHAR_MASK)
5280 break;
5281 /* Zero upper bytes in UCS-4 builds */
5282#if (Py_UNICODE_SIZE > 2)
5283 _p[0] = 0;
5284 _p[1] = 0;
5285#if (SIZEOF_LONG == 8)
5286 _p[2] = 0;
5287 _p[3] = 0;
5288#endif
5289#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005290 /* Issue #4916; UCS-4 builds on big endian machines must
5291 fill the two last bytes of each 4-byte unit. */
5292#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
5293# define OFF 2
5294#else
5295# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00005296#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005297 ((unsigned char *) _p)[OFF + 1] = _q[0];
5298 ((unsigned char *) _p)[OFF + 0] = _q[1];
5299 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
5300 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
5301#if (SIZEOF_LONG == 8)
5302 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
5303 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
5304 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
5305 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
5306#endif
5307#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00005308 _q += SIZEOF_LONG;
5309 _p += SIZEOF_LONG / 2;
5310 }
5311 }
5312 p = _p;
5313 q = _q;
5314 if (q >= e)
5315 break;
5316 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005317 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005318
Benjamin Peterson14339b62009-01-31 16:36:08 +00005319 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005320
5321 if (ch < 0xD800 || ch > 0xDFFF) {
5322 *p++ = ch;
5323 continue;
5324 }
5325
5326 /* UTF-16 code pair: */
5327 if (q > e) {
5328 errmsg = "unexpected end of data";
5329 startinpos = (((const char *)q) - 2) - starts;
5330 endinpos = ((const char *)e) + 1 - starts;
5331 goto utf16Error;
5332 }
5333 if (0xD800 <= ch && ch <= 0xDBFF) {
5334 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
5335 q += 2;
5336 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00005337#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005338 *p++ = ch;
5339 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005340#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005341 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005342#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005343 continue;
5344 }
5345 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005346 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005347 startinpos = (((const char *)q)-4)-starts;
5348 endinpos = startinpos+2;
5349 goto utf16Error;
5350 }
5351
Benjamin Peterson14339b62009-01-31 16:36:08 +00005352 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005353 errmsg = "illegal encoding";
5354 startinpos = (((const char *)q)-2)-starts;
5355 endinpos = startinpos+2;
5356 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005357
Benjamin Peterson29060642009-01-31 22:14:21 +00005358 utf16Error:
5359 outpos = p - PyUnicode_AS_UNICODE(unicode);
5360 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005361 errors,
5362 &errorHandler,
5363 "utf16", errmsg,
5364 &starts,
5365 (const char **)&e,
5366 &startinpos,
5367 &endinpos,
5368 &exc,
5369 (const char **)&q,
5370 &unicode,
5371 &outpos,
5372 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00005373 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005374 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005375 /* remaining byte at the end? (size should be even) */
5376 if (e == q) {
5377 if (!consumed) {
5378 errmsg = "truncated data";
5379 startinpos = ((const char *)q) - starts;
5380 endinpos = ((const char *)e) + 1 - starts;
5381 outpos = p - PyUnicode_AS_UNICODE(unicode);
5382 if (unicode_decode_call_errorhandler(
5383 errors,
5384 &errorHandler,
5385 "utf16", errmsg,
5386 &starts,
5387 (const char **)&e,
5388 &startinpos,
5389 &endinpos,
5390 &exc,
5391 (const char **)&q,
5392 &unicode,
5393 &outpos,
5394 &p))
5395 goto onError;
5396 /* The remaining input chars are ignored if the callback
5397 chooses to skip the input */
5398 }
5399 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005400
5401 if (byteorder)
5402 *byteorder = bo;
5403
Walter Dörwald69652032004-09-07 20:24:22 +00005404 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005405 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005406
Guido van Rossumd57fd912000-03-10 22:53:23 +00005407 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02005408 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005409 goto onError;
5410
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005411 Py_XDECREF(errorHandler);
5412 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005413#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005414 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005415 Py_DECREF(unicode);
5416 return NULL;
5417 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005418#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005419 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00005420 return (PyObject *)unicode;
5421
Benjamin Peterson29060642009-01-31 22:14:21 +00005422 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005423 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005424 Py_XDECREF(errorHandler);
5425 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005426 return NULL;
5427}
5428
Antoine Pitrouab868312009-01-10 15:40:25 +00005429#undef FAST_CHAR_MASK
5430#undef SWAPPED_FAST_CHAR_MASK
5431
Tim Peters772747b2001-08-09 22:21:55 +00005432PyObject *
5433PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005434 Py_ssize_t size,
5435 const char *errors,
5436 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005437{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005438 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005439 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005440 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005441#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005442 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005443#else
5444 const int pairs = 0;
5445#endif
Tim Peters772747b2001-08-09 22:21:55 +00005446 /* Offsets from p for storing byte pairs in the right order. */
5447#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5448 int ihi = 1, ilo = 0;
5449#else
5450 int ihi = 0, ilo = 1;
5451#endif
5452
Benjamin Peterson29060642009-01-31 22:14:21 +00005453#define STORECHAR(CH) \
5454 do { \
5455 p[ihi] = ((CH) >> 8) & 0xff; \
5456 p[ilo] = (CH) & 0xff; \
5457 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005458 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005459
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005460#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005461 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005462 if (s[i] >= 0x10000)
5463 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005464#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005465 /* 2 * (size + pairs + (byteorder == 0)) */
5466 if (size > PY_SSIZE_T_MAX ||
5467 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005468 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005469 nsize = size + pairs + (byteorder == 0);
5470 bytesize = nsize * 2;
5471 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005472 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005473 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005474 if (v == NULL)
5475 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005476
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005477 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005478 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005479 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005480 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005481 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005482
5483 if (byteorder == -1) {
5484 /* force LE */
5485 ihi = 1;
5486 ilo = 0;
5487 }
5488 else if (byteorder == 1) {
5489 /* force BE */
5490 ihi = 0;
5491 ilo = 1;
5492 }
5493
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005494 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005495 Py_UNICODE ch = *s++;
5496 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005497#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005498 if (ch >= 0x10000) {
5499 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5500 ch = 0xD800 | ((ch-0x10000) >> 10);
5501 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005502#endif
Tim Peters772747b2001-08-09 22:21:55 +00005503 STORECHAR(ch);
5504 if (ch2)
5505 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005506 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005507
5508 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005509 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005510#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005511}
5512
Alexander Belopolsky40018472011-02-26 01:02:56 +00005513PyObject *
5514PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005515{
5516 if (!PyUnicode_Check(unicode)) {
5517 PyErr_BadArgument();
5518 return NULL;
5519 }
5520 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005521 PyUnicode_GET_SIZE(unicode),
5522 NULL,
5523 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005524}
5525
5526/* --- Unicode Escape Codec ----------------------------------------------- */
5527
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005528/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5529 if all the escapes in the string make it still a valid ASCII string.
5530 Returns -1 if any escapes were found which cause the string to
5531 pop out of ASCII range. Otherwise returns the length of the
5532 required buffer to hold the string.
5533 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005534static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005535length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5536{
5537 const unsigned char *p = (const unsigned char *)s;
5538 const unsigned char *end = p + size;
5539 Py_ssize_t length = 0;
5540
5541 if (size < 0)
5542 return -1;
5543
5544 for (; p < end; ++p) {
5545 if (*p > 127) {
5546 /* Non-ASCII */
5547 return -1;
5548 }
5549 else if (*p != '\\') {
5550 /* Normal character */
5551 ++length;
5552 }
5553 else {
5554 /* Backslash-escape, check next char */
5555 ++p;
5556 /* Escape sequence reaches till end of string or
5557 non-ASCII follow-up. */
5558 if (p >= end || *p > 127)
5559 return -1;
5560 switch (*p) {
5561 case '\n':
5562 /* backslash + \n result in zero characters */
5563 break;
5564 case '\\': case '\'': case '\"':
5565 case 'b': case 'f': case 't':
5566 case 'n': case 'r': case 'v': case 'a':
5567 ++length;
5568 break;
5569 case '0': case '1': case '2': case '3':
5570 case '4': case '5': case '6': case '7':
5571 case 'x': case 'u': case 'U': case 'N':
5572 /* these do not guarantee ASCII characters */
5573 return -1;
5574 default:
5575 /* count the backslash + the other character */
5576 length += 2;
5577 }
5578 }
5579 }
5580 return length;
5581}
5582
5583/* Similar to PyUnicode_WRITE but either write into wstr field
5584 or treat string as ASCII. */
5585#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5586 do { \
5587 if ((kind) != PyUnicode_WCHAR_KIND) \
5588 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5589 else \
5590 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5591 } while (0)
5592
5593#define WRITE_WSTR(buf, index, value) \
5594 assert(kind == PyUnicode_WCHAR_KIND), \
5595 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5596
5597
Fredrik Lundh06d12682001-01-24 07:59:11 +00005598static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005599
Alexander Belopolsky40018472011-02-26 01:02:56 +00005600PyObject *
5601PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005602 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005603 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005604{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005605 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005606 Py_ssize_t startinpos;
5607 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005608 int j;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005609 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005610 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005611 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005612 char* message;
5613 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005614 PyObject *errorHandler = NULL;
5615 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005616 Py_ssize_t ascii_length;
5617 Py_ssize_t i;
5618 int kind;
5619 void *data;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005620
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005621 ascii_length = length_of_escaped_ascii_string(s, size);
5622
5623 /* After length_of_escaped_ascii_string() there are two alternatives,
5624 either the string is pure ASCII with named escapes like \n, etc.
5625 and we determined it's exact size (common case)
5626 or it contains \x, \u, ... escape sequences. then we create a
5627 legacy wchar string and resize it at the end of this function. */
5628 if (ascii_length >= 0) {
5629 v = (PyUnicodeObject *)PyUnicode_New(ascii_length, 127);
5630 if (!v)
5631 goto onError;
5632 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
5633 kind = PyUnicode_1BYTE_KIND;
5634 data = PyUnicode_DATA(v);
5635 }
5636 else {
5637 /* Escaped strings will always be longer than the resulting
5638 Unicode string, so we start with size here and then reduce the
5639 length after conversion to the true value.
5640 (but if the error callback returns a long replacement string
5641 we'll have to allocate more space) */
5642 v = _PyUnicode_New(size);
5643 if (!v)
5644 goto onError;
5645 kind = PyUnicode_WCHAR_KIND;
5646 data = PyUnicode_AS_UNICODE(v);
5647 }
5648
Guido van Rossumd57fd912000-03-10 22:53:23 +00005649 if (size == 0)
5650 return (PyObject *)v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005651 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005652 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005653
Guido van Rossumd57fd912000-03-10 22:53:23 +00005654 while (s < end) {
5655 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005656 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005657 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005658
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005659 if (kind == PyUnicode_WCHAR_KIND) {
5660 assert(i < _PyUnicode_WSTR_LENGTH(v));
5661 }
5662 else {
5663 /* The only case in which i == ascii_length is a backslash
5664 followed by a newline. */
5665 assert(i <= ascii_length);
5666 }
5667
Guido van Rossumd57fd912000-03-10 22:53:23 +00005668 /* Non-escape characters are interpreted as Unicode ordinals */
5669 if (*s != '\\') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005670 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char) *s++);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005671 continue;
5672 }
5673
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005674 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005675 /* \ - Escapes */
5676 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005677 c = *s++;
5678 if (s > end)
5679 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005680
5681 if (kind == PyUnicode_WCHAR_KIND) {
5682 assert(i < _PyUnicode_WSTR_LENGTH(v));
5683 }
5684 else {
5685 /* The only case in which i == ascii_length is a backslash
5686 followed by a newline. */
5687 assert(i < ascii_length || (i == ascii_length && c == '\n'));
5688 }
5689
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005690 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005691
Benjamin Peterson29060642009-01-31 22:14:21 +00005692 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005693 case '\n': break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005694 case '\\': WRITE_ASCII_OR_WSTR(kind, data, i++, '\\'); break;
5695 case '\'': WRITE_ASCII_OR_WSTR(kind, data, i++, '\''); break;
5696 case '\"': WRITE_ASCII_OR_WSTR(kind, data, i++, '\"'); break;
5697 case 'b': WRITE_ASCII_OR_WSTR(kind, data, i++, '\b'); break;
5698 /* FF */
5699 case 'f': WRITE_ASCII_OR_WSTR(kind, data, i++, '\014'); break;
5700 case 't': WRITE_ASCII_OR_WSTR(kind, data, i++, '\t'); break;
5701 case 'n': WRITE_ASCII_OR_WSTR(kind, data, i++, '\n'); break;
5702 case 'r': WRITE_ASCII_OR_WSTR(kind, data, i++, '\r'); break;
5703 /* VT */
5704 case 'v': WRITE_ASCII_OR_WSTR(kind, data, i++, '\013'); break;
5705 /* BEL, not classic C */
5706 case 'a': WRITE_ASCII_OR_WSTR(kind, data, i++, '\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005707
Benjamin Peterson29060642009-01-31 22:14:21 +00005708 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005709 case '0': case '1': case '2': case '3':
5710 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005711 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005712 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005713 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005714 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005715 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005716 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005717 WRITE_WSTR(data, i++, x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005718 break;
5719
Benjamin Peterson29060642009-01-31 22:14:21 +00005720 /* hex escapes */
5721 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005722 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005723 digits = 2;
5724 message = "truncated \\xXX escape";
5725 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005726
Benjamin Peterson29060642009-01-31 22:14:21 +00005727 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005728 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005729 digits = 4;
5730 message = "truncated \\uXXXX escape";
5731 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005732
Benjamin Peterson29060642009-01-31 22:14:21 +00005733 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005734 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005735 digits = 8;
5736 message = "truncated \\UXXXXXXXX escape";
5737 hexescape:
5738 chr = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005739 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005740 if (s+digits>end) {
5741 endinpos = size;
5742 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005743 errors, &errorHandler,
5744 "unicodeescape", "end of string in escape sequence",
5745 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005746 &v, &i, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005747 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005748 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005749 goto nextByte;
5750 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005751 for (j = 0; j < digits; ++j) {
5752 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005753 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005754 endinpos = (s+j+1)-starts;
5755 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005756 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005757 errors, &errorHandler,
5758 "unicodeescape", message,
5759 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005760 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005761 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005762 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005763 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005764 }
5765 chr = (chr<<4) & ~0xF;
5766 if (c >= '0' && c <= '9')
5767 chr += c - '0';
5768 else if (c >= 'a' && c <= 'f')
5769 chr += 10 + c - 'a';
5770 else
5771 chr += 10 + c - 'A';
5772 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005773 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005774 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005775 /* _decoding_error will have already written into the
5776 target buffer. */
5777 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005778 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005779 /* when we get here, chr is a 32-bit unicode character */
5780 if (chr <= 0xffff)
5781 /* UCS-2 character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005782 WRITE_WSTR(data, i++, chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005783 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005784 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00005785 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00005786#ifdef Py_UNICODE_WIDE
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005787 WRITE_WSTR(data, i++, chr);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005788#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00005789 chr -= 0x10000L;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005790 WRITE_WSTR(data, i++, 0xD800 + (Py_UNICODE) (chr >> 10));
5791 WRITE_WSTR(data, i++, 0xDC00 + (Py_UNICODE) (chr & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005792#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00005793 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005794 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005795 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005796 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005797 errors, &errorHandler,
5798 "unicodeescape", "illegal Unicode character",
5799 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005800 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005801 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005802 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005803 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005804 break;
5805
Benjamin Peterson29060642009-01-31 22:14:21 +00005806 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005807 case 'N':
5808 message = "malformed \\N character escape";
5809 if (ucnhash_CAPI == NULL) {
5810 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005811 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5812 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005813 if (ucnhash_CAPI == NULL)
5814 goto ucnhashError;
5815 }
5816 if (*s == '{') {
5817 const char *start = s+1;
5818 /* look for the closing brace */
5819 while (*s != '}' && s < end)
5820 s++;
5821 if (s > start && s < end && *s == '}') {
5822 /* found a name. look it up in the unicode database */
5823 message = "unknown Unicode character name";
5824 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005825 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
5826 &chr))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005827 goto store;
5828 }
5829 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005830 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005831 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005832 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005833 errors, &errorHandler,
5834 "unicodeescape", message,
5835 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005836 &v, &i, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005837 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005838 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005839 break;
5840
5841 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005842 if (s > end) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005843 assert(kind == PyUnicode_WCHAR_KIND);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005844 message = "\\ at end of string";
5845 s--;
5846 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005847 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005848 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005849 errors, &errorHandler,
5850 "unicodeescape", message,
5851 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005852 &v, &i, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00005853 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005854 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005855 }
5856 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005857 WRITE_ASCII_OR_WSTR(kind, data, i++, '\\');
5858 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005859 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005860 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005861 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005862 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005863 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005864 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005865 /* Ensure the length prediction worked in case of ASCII strings */
5866 assert(kind == PyUnicode_WCHAR_KIND || i == ascii_length);
5867
Victor Stinnerfe226c02011-10-03 03:52:20 +02005868 if (kind == PyUnicode_WCHAR_KIND)
5869 {
5870 if (PyUnicode_Resize((PyObject**)&v, i) < 0)
5871 goto onError;
Victor Stinnerfe226c02011-10-03 03:52:20 +02005872 }
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005873 Py_XDECREF(errorHandler);
5874 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005875#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005876 if (_PyUnicode_READY_REPLACE(&v)) {
5877 Py_DECREF(v);
5878 return NULL;
5879 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005880#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005881 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00005882 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005883
Benjamin Peterson29060642009-01-31 22:14:21 +00005884 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005885 PyErr_SetString(
5886 PyExc_UnicodeError,
5887 "\\N escapes not supported (can't load unicodedata module)"
5888 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005889 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005890 Py_XDECREF(errorHandler);
5891 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005892 return NULL;
5893
Benjamin Peterson29060642009-01-31 22:14:21 +00005894 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005895 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005896 Py_XDECREF(errorHandler);
5897 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005898 return NULL;
5899}
5900
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005901#undef WRITE_ASCII_OR_WSTR
5902#undef WRITE_WSTR
5903
Guido van Rossumd57fd912000-03-10 22:53:23 +00005904/* Return a Unicode-Escape string version of the Unicode object.
5905
5906 If quotes is true, the string is enclosed in u"" or u'' quotes as
5907 appropriate.
5908
5909*/
5910
Walter Dörwald79e913e2007-05-12 11:08:06 +00005911static const char *hexdigits = "0123456789abcdef";
5912
Alexander Belopolsky40018472011-02-26 01:02:56 +00005913PyObject *
5914PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005915 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005916{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005917 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005918 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005919
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005920#ifdef Py_UNICODE_WIDE
5921 const Py_ssize_t expandsize = 10;
5922#else
5923 const Py_ssize_t expandsize = 6;
5924#endif
5925
Thomas Wouters89f507f2006-12-13 04:49:30 +00005926 /* XXX(nnorwitz): rather than over-allocating, it would be
5927 better to choose a different scheme. Perhaps scan the
5928 first N-chars of the string and allocate based on that size.
5929 */
5930 /* Initial allocation is based on the longest-possible unichr
5931 escape.
5932
5933 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5934 unichr, so in this case it's the longest unichr escape. In
5935 narrow (UTF-16) builds this is five chars per source unichr
5936 since there are two unichrs in the surrogate pair, so in narrow
5937 (UTF-16) builds it's not the longest unichr escape.
5938
5939 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5940 so in the narrow (UTF-16) build case it's the longest unichr
5941 escape.
5942 */
5943
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005944 if (size == 0)
5945 return PyBytes_FromStringAndSize(NULL, 0);
5946
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005947 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005948 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005949
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005950 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005951 2
5952 + expandsize*size
5953 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005954 if (repr == NULL)
5955 return NULL;
5956
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005957 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005958
Guido van Rossumd57fd912000-03-10 22:53:23 +00005959 while (size-- > 0) {
5960 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005961
Walter Dörwald79e913e2007-05-12 11:08:06 +00005962 /* Escape backslashes */
5963 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005964 *p++ = '\\';
5965 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005966 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005967 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005968
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00005969#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005970 /* Map 21-bit characters to '\U00xxxxxx' */
5971 else if (ch >= 0x10000) {
5972 *p++ = '\\';
5973 *p++ = 'U';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005974 *p++ = hexdigits[(ch >> 28) & 0x0000000F];
5975 *p++ = hexdigits[(ch >> 24) & 0x0000000F];
5976 *p++ = hexdigits[(ch >> 20) & 0x0000000F];
5977 *p++ = hexdigits[(ch >> 16) & 0x0000000F];
5978 *p++ = hexdigits[(ch >> 12) & 0x0000000F];
5979 *p++ = hexdigits[(ch >> 8) & 0x0000000F];
5980 *p++ = hexdigits[(ch >> 4) & 0x0000000F];
5981 *p++ = hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005982 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005983 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005984#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005985 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
5986 else if (ch >= 0xD800 && ch < 0xDC00) {
5987 Py_UNICODE ch2;
5988 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00005989
Benjamin Peterson29060642009-01-31 22:14:21 +00005990 ch2 = *s++;
5991 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00005992 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005993 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
5994 *p++ = '\\';
5995 *p++ = 'U';
5996 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
5997 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
5998 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
5999 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
6000 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
6001 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
6002 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
6003 *p++ = hexdigits[ucs & 0x0000000F];
6004 continue;
6005 }
6006 /* Fall through: isolated surrogates are copied as-is */
6007 s--;
6008 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006009 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00006010#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006011
Guido van Rossumd57fd912000-03-10 22:53:23 +00006012 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006013 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006014 *p++ = '\\';
6015 *p++ = 'u';
Walter Dörwald79e913e2007-05-12 11:08:06 +00006016 *p++ = hexdigits[(ch >> 12) & 0x000F];
6017 *p++ = hexdigits[(ch >> 8) & 0x000F];
6018 *p++ = hexdigits[(ch >> 4) & 0x000F];
6019 *p++ = hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006020 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006021
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006022 /* Map special whitespace to '\t', \n', '\r' */
6023 else if (ch == '\t') {
6024 *p++ = '\\';
6025 *p++ = 't';
6026 }
6027 else if (ch == '\n') {
6028 *p++ = '\\';
6029 *p++ = 'n';
6030 }
6031 else if (ch == '\r') {
6032 *p++ = '\\';
6033 *p++ = 'r';
6034 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006035
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006036 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006037 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006038 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006039 *p++ = 'x';
Walter Dörwald79e913e2007-05-12 11:08:06 +00006040 *p++ = hexdigits[(ch >> 4) & 0x000F];
6041 *p++ = hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006042 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006043
Guido van Rossumd57fd912000-03-10 22:53:23 +00006044 /* Copy everything else as-is */
6045 else
6046 *p++ = (char) ch;
6047 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006048
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006049 assert(p - PyBytes_AS_STRING(repr) > 0);
6050 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6051 return NULL;
6052 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006053}
6054
Alexander Belopolsky40018472011-02-26 01:02:56 +00006055PyObject *
6056PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006057{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006058 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006059 if (!PyUnicode_Check(unicode)) {
6060 PyErr_BadArgument();
6061 return NULL;
6062 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00006063 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6064 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006065 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006066}
6067
6068/* --- Raw Unicode Escape Codec ------------------------------------------- */
6069
Alexander Belopolsky40018472011-02-26 01:02:56 +00006070PyObject *
6071PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006072 Py_ssize_t size,
6073 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006074{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006075 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006076 Py_ssize_t startinpos;
6077 Py_ssize_t endinpos;
6078 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006079 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006080 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006081 const char *end;
6082 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006083 PyObject *errorHandler = NULL;
6084 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006085
Guido van Rossumd57fd912000-03-10 22:53:23 +00006086 /* Escaped strings will always be longer than the resulting
6087 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006088 length after conversion to the true value. (But decoding error
6089 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006090 v = _PyUnicode_New(size);
6091 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006092 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006093 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006094 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006095 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006096 end = s + size;
6097 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006098 unsigned char c;
6099 Py_UCS4 x;
6100 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006101 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006102
Benjamin Peterson29060642009-01-31 22:14:21 +00006103 /* Non-escape characters are interpreted as Unicode ordinals */
6104 if (*s != '\\') {
6105 *p++ = (unsigned char)*s++;
6106 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006107 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006108 startinpos = s-starts;
6109
6110 /* \u-escapes are only interpreted iff the number of leading
6111 backslashes if odd */
6112 bs = s;
6113 for (;s < end;) {
6114 if (*s != '\\')
6115 break;
6116 *p++ = (unsigned char)*s++;
6117 }
6118 if (((s - bs) & 1) == 0 ||
6119 s >= end ||
6120 (*s != 'u' && *s != 'U')) {
6121 continue;
6122 }
6123 p--;
6124 count = *s=='u' ? 4 : 8;
6125 s++;
6126
6127 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
6128 outpos = p-PyUnicode_AS_UNICODE(v);
6129 for (x = 0, i = 0; i < count; ++i, ++s) {
6130 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006131 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006132 endinpos = s-starts;
6133 if (unicode_decode_call_errorhandler(
6134 errors, &errorHandler,
6135 "rawunicodeescape", "truncated \\uXXXX",
6136 &starts, &end, &startinpos, &endinpos, &exc, &s,
6137 &v, &outpos, &p))
6138 goto onError;
6139 goto nextByte;
6140 }
6141 x = (x<<4) & ~0xF;
6142 if (c >= '0' && c <= '9')
6143 x += c - '0';
6144 else if (c >= 'a' && c <= 'f')
6145 x += 10 + c - 'a';
6146 else
6147 x += 10 + c - 'A';
6148 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00006149 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00006150 /* UCS-2 character */
6151 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006152 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006153 /* UCS-4 character. Either store directly, or as
6154 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00006155#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006156 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006157#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006158 x -= 0x10000L;
6159 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
6160 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00006161#endif
6162 } else {
6163 endinpos = s-starts;
6164 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006165 if (unicode_decode_call_errorhandler(
6166 errors, &errorHandler,
6167 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006168 &starts, &end, &startinpos, &endinpos, &exc, &s,
6169 &v, &outpos, &p))
6170 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006171 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006172 nextByte:
6173 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006174 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02006175 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006176 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006177 Py_XDECREF(errorHandler);
6178 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006179#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006180 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006181 Py_DECREF(v);
6182 return NULL;
6183 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006184#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006185 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006186 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006187
Benjamin Peterson29060642009-01-31 22:14:21 +00006188 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006189 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006190 Py_XDECREF(errorHandler);
6191 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006192 return NULL;
6193}
6194
Alexander Belopolsky40018472011-02-26 01:02:56 +00006195PyObject *
6196PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006197 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006198{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006199 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006200 char *p;
6201 char *q;
6202
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006203#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006204 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006205#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006206 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006207#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00006208
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006209 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006210 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006211
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006212 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006213 if (repr == NULL)
6214 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00006215 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006216 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006217
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006218 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006219 while (size-- > 0) {
6220 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006221#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006222 /* Map 32-bit characters to '\Uxxxxxxxx' */
6223 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006224 *p++ = '\\';
6225 *p++ = 'U';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00006226 *p++ = hexdigits[(ch >> 28) & 0xf];
6227 *p++ = hexdigits[(ch >> 24) & 0xf];
6228 *p++ = hexdigits[(ch >> 20) & 0xf];
6229 *p++ = hexdigits[(ch >> 16) & 0xf];
6230 *p++ = hexdigits[(ch >> 12) & 0xf];
6231 *p++ = hexdigits[(ch >> 8) & 0xf];
6232 *p++ = hexdigits[(ch >> 4) & 0xf];
6233 *p++ = hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006234 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006235 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00006236#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006237 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
6238 if (ch >= 0xD800 && ch < 0xDC00) {
6239 Py_UNICODE ch2;
6240 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006241
Benjamin Peterson29060642009-01-31 22:14:21 +00006242 ch2 = *s++;
6243 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00006244 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006245 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
6246 *p++ = '\\';
6247 *p++ = 'U';
6248 *p++ = hexdigits[(ucs >> 28) & 0xf];
6249 *p++ = hexdigits[(ucs >> 24) & 0xf];
6250 *p++ = hexdigits[(ucs >> 20) & 0xf];
6251 *p++ = hexdigits[(ucs >> 16) & 0xf];
6252 *p++ = hexdigits[(ucs >> 12) & 0xf];
6253 *p++ = hexdigits[(ucs >> 8) & 0xf];
6254 *p++ = hexdigits[(ucs >> 4) & 0xf];
6255 *p++ = hexdigits[ucs & 0xf];
6256 continue;
6257 }
6258 /* Fall through: isolated surrogates are copied as-is */
6259 s--;
6260 size++;
6261 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006262#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006263 /* Map 16-bit characters to '\uxxxx' */
6264 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006265 *p++ = '\\';
6266 *p++ = 'u';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00006267 *p++ = hexdigits[(ch >> 12) & 0xf];
6268 *p++ = hexdigits[(ch >> 8) & 0xf];
6269 *p++ = hexdigits[(ch >> 4) & 0xf];
6270 *p++ = hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006271 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006272 /* Copy everything else as-is */
6273 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006274 *p++ = (char) ch;
6275 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006276 size = p - q;
6277
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006278 assert(size > 0);
6279 if (_PyBytes_Resize(&repr, size) < 0)
6280 return NULL;
6281 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006282}
6283
Alexander Belopolsky40018472011-02-26 01:02:56 +00006284PyObject *
6285PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006286{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006287 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006288 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00006289 PyErr_BadArgument();
6290 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006291 }
Walter Dörwald711005d2007-05-12 12:03:26 +00006292 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6293 PyUnicode_GET_SIZE(unicode));
6294
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006295 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006296}
6297
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006298/* --- Unicode Internal Codec ------------------------------------------- */
6299
Alexander Belopolsky40018472011-02-26 01:02:56 +00006300PyObject *
6301_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006302 Py_ssize_t size,
6303 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006304{
6305 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006306 Py_ssize_t startinpos;
6307 Py_ssize_t endinpos;
6308 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006309 PyUnicodeObject *v;
6310 Py_UNICODE *p;
6311 const char *end;
6312 const char *reason;
6313 PyObject *errorHandler = NULL;
6314 PyObject *exc = NULL;
6315
Neal Norwitzd43069c2006-01-08 01:12:10 +00006316#ifdef Py_UNICODE_WIDE
6317 Py_UNICODE unimax = PyUnicode_GetMax();
6318#endif
6319
Thomas Wouters89f507f2006-12-13 04:49:30 +00006320 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006321 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
6322 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006323 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006324 /* Intentionally PyUnicode_GET_SIZE instead of PyUnicode_GET_LENGTH
6325 as string was created with the old API. */
6326 if (PyUnicode_GET_SIZE(v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006327 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006328 p = PyUnicode_AS_UNICODE(v);
6329 end = s + size;
6330
6331 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006332 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006333 /* We have to sanity check the raw data, otherwise doom looms for
6334 some malformed UCS-4 data. */
6335 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006336#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006337 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006338#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006339 end-s < Py_UNICODE_SIZE
6340 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006341 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006342 startinpos = s - starts;
6343 if (end-s < Py_UNICODE_SIZE) {
6344 endinpos = end-starts;
6345 reason = "truncated input";
6346 }
6347 else {
6348 endinpos = s - starts + Py_UNICODE_SIZE;
6349 reason = "illegal code point (> 0x10FFFF)";
6350 }
6351 outpos = p - PyUnicode_AS_UNICODE(v);
6352 if (unicode_decode_call_errorhandler(
6353 errors, &errorHandler,
6354 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006355 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00006356 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006357 goto onError;
6358 }
6359 }
6360 else {
6361 p++;
6362 s += Py_UNICODE_SIZE;
6363 }
6364 }
6365
Victor Stinnerfe226c02011-10-03 03:52:20 +02006366 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006367 goto onError;
6368 Py_XDECREF(errorHandler);
6369 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006370#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006371 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006372 Py_DECREF(v);
6373 return NULL;
6374 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006375#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006376 assert(_PyUnicode_CheckConsistency(v, 1));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006377 return (PyObject *)v;
6378
Benjamin Peterson29060642009-01-31 22:14:21 +00006379 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006380 Py_XDECREF(v);
6381 Py_XDECREF(errorHandler);
6382 Py_XDECREF(exc);
6383 return NULL;
6384}
6385
Guido van Rossumd57fd912000-03-10 22:53:23 +00006386/* --- Latin-1 Codec ------------------------------------------------------ */
6387
Alexander Belopolsky40018472011-02-26 01:02:56 +00006388PyObject *
6389PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006390 Py_ssize_t size,
6391 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006392{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006393 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006394 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006395}
6396
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006397/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006398static void
6399make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006400 const char *encoding,
6401 const Py_UNICODE *unicode, Py_ssize_t size,
6402 Py_ssize_t startpos, Py_ssize_t endpos,
6403 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006404{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006405 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006406 *exceptionObject = PyUnicodeEncodeError_Create(
6407 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006408 }
6409 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006410 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6411 goto onError;
6412 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6413 goto onError;
6414 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6415 goto onError;
6416 return;
6417 onError:
6418 Py_DECREF(*exceptionObject);
6419 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006420 }
6421}
6422
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006423/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006424static void
6425raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006426 const char *encoding,
6427 const Py_UNICODE *unicode, Py_ssize_t size,
6428 Py_ssize_t startpos, Py_ssize_t endpos,
6429 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006430{
6431 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006432 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006433 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006434 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006435}
6436
6437/* error handling callback helper:
6438 build arguments, call the callback and check the arguments,
6439 put the result into newpos and return the replacement string, which
6440 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006441static PyObject *
6442unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006443 PyObject **errorHandler,
6444 const char *encoding, const char *reason,
6445 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
6446 Py_ssize_t startpos, Py_ssize_t endpos,
6447 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006448{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006449 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006450
6451 PyObject *restuple;
6452 PyObject *resunicode;
6453
6454 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006455 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006456 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006457 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006458 }
6459
6460 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006461 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006462 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006463 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006464
6465 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006466 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006467 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006468 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006469 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006470 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006471 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 (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006475 &resunicode, newpos)) {
6476 Py_DECREF(restuple);
6477 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006478 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006479 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6480 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6481 Py_DECREF(restuple);
6482 return NULL;
6483 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006484 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006485 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006486 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006487 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6488 Py_DECREF(restuple);
6489 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006490 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006491 Py_INCREF(resunicode);
6492 Py_DECREF(restuple);
6493 return resunicode;
6494}
6495
Alexander Belopolsky40018472011-02-26 01:02:56 +00006496static PyObject *
6497unicode_encode_ucs1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006498 Py_ssize_t size,
6499 const char *errors,
6500 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006501{
6502 /* output object */
6503 PyObject *res;
6504 /* pointers to the beginning and end+1 of input */
6505 const Py_UNICODE *startp = p;
6506 const Py_UNICODE *endp = p + size;
6507 /* pointer to the beginning of the unencodable characters */
6508 /* const Py_UNICODE *badp = NULL; */
6509 /* pointer into the output */
6510 char *str;
6511 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006512 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006513 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6514 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006515 PyObject *errorHandler = NULL;
6516 PyObject *exc = NULL;
6517 /* the following variable is used for caching string comparisons
6518 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6519 int known_errorHandler = -1;
6520
6521 /* allocate enough for a simple encoding without
6522 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006523 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006524 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006525 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006526 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006527 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006528 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006529 ressize = size;
6530
6531 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006532 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006533
Benjamin Peterson29060642009-01-31 22:14:21 +00006534 /* can we encode this? */
6535 if (c<limit) {
6536 /* no overflow check, because we know that the space is enough */
6537 *str++ = (char)c;
6538 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006539 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006540 else {
6541 Py_ssize_t unicodepos = p-startp;
6542 Py_ssize_t requiredsize;
6543 PyObject *repunicode;
6544 Py_ssize_t repsize;
6545 Py_ssize_t newpos;
6546 Py_ssize_t respos;
6547 Py_UNICODE *uni2;
6548 /* startpos for collecting unencodable chars */
6549 const Py_UNICODE *collstart = p;
6550 const Py_UNICODE *collend = p;
6551 /* find all unecodable characters */
6552 while ((collend < endp) && ((*collend)>=limit))
6553 ++collend;
6554 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6555 if (known_errorHandler==-1) {
6556 if ((errors==NULL) || (!strcmp(errors, "strict")))
6557 known_errorHandler = 1;
6558 else if (!strcmp(errors, "replace"))
6559 known_errorHandler = 2;
6560 else if (!strcmp(errors, "ignore"))
6561 known_errorHandler = 3;
6562 else if (!strcmp(errors, "xmlcharrefreplace"))
6563 known_errorHandler = 4;
6564 else
6565 known_errorHandler = 0;
6566 }
6567 switch (known_errorHandler) {
6568 case 1: /* strict */
6569 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
6570 goto onError;
6571 case 2: /* replace */
6572 while (collstart++<collend)
6573 *str++ = '?'; /* fall through */
6574 case 3: /* ignore */
6575 p = collend;
6576 break;
6577 case 4: /* xmlcharrefreplace */
6578 respos = str - PyBytes_AS_STRING(res);
6579 /* determine replacement size (temporarily (mis)uses p) */
6580 for (p = collstart, repsize = 0; p < collend; ++p) {
6581 if (*p<10)
6582 repsize += 2+1+1;
6583 else if (*p<100)
6584 repsize += 2+2+1;
6585 else if (*p<1000)
6586 repsize += 2+3+1;
6587 else if (*p<10000)
6588 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006589#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006590 else
6591 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006592#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006593 else if (*p<100000)
6594 repsize += 2+5+1;
6595 else if (*p<1000000)
6596 repsize += 2+6+1;
6597 else
6598 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006599#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006600 }
6601 requiredsize = respos+repsize+(endp-collend);
6602 if (requiredsize > ressize) {
6603 if (requiredsize<2*ressize)
6604 requiredsize = 2*ressize;
6605 if (_PyBytes_Resize(&res, requiredsize))
6606 goto onError;
6607 str = PyBytes_AS_STRING(res) + respos;
6608 ressize = requiredsize;
6609 }
6610 /* generate replacement (temporarily (mis)uses p) */
6611 for (p = collstart; p < collend; ++p) {
6612 str += sprintf(str, "&#%d;", (int)*p);
6613 }
6614 p = collend;
6615 break;
6616 default:
6617 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
6618 encoding, reason, startp, size, &exc,
6619 collstart-startp, collend-startp, &newpos);
6620 if (repunicode == NULL)
6621 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006622 if (PyBytes_Check(repunicode)) {
6623 /* Directly copy bytes result to output. */
6624 repsize = PyBytes_Size(repunicode);
6625 if (repsize > 1) {
6626 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006627 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006628 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6629 Py_DECREF(repunicode);
6630 goto onError;
6631 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006632 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006633 ressize += repsize-1;
6634 }
6635 memcpy(str, PyBytes_AsString(repunicode), repsize);
6636 str += repsize;
6637 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006638 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006639 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006640 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006641 /* need more space? (at least enough for what we
6642 have+the replacement+the rest of the string, so
6643 we won't have to check space for encodable characters) */
6644 respos = str - PyBytes_AS_STRING(res);
6645 repsize = PyUnicode_GET_SIZE(repunicode);
6646 requiredsize = respos+repsize+(endp-collend);
6647 if (requiredsize > ressize) {
6648 if (requiredsize<2*ressize)
6649 requiredsize = 2*ressize;
6650 if (_PyBytes_Resize(&res, requiredsize)) {
6651 Py_DECREF(repunicode);
6652 goto onError;
6653 }
6654 str = PyBytes_AS_STRING(res) + respos;
6655 ressize = requiredsize;
6656 }
6657 /* check if there is anything unencodable in the replacement
6658 and copy it to the output */
6659 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
6660 c = *uni2;
6661 if (c >= limit) {
6662 raise_encode_exception(&exc, encoding, startp, size,
6663 unicodepos, unicodepos+1, reason);
6664 Py_DECREF(repunicode);
6665 goto onError;
6666 }
6667 *str = (char)c;
6668 }
6669 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006670 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006671 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006672 }
6673 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006674 /* Resize if we allocated to much */
6675 size = str - PyBytes_AS_STRING(res);
6676 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006677 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006678 if (_PyBytes_Resize(&res, size) < 0)
6679 goto onError;
6680 }
6681
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006682 Py_XDECREF(errorHandler);
6683 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006684 return res;
6685
6686 onError:
6687 Py_XDECREF(res);
6688 Py_XDECREF(errorHandler);
6689 Py_XDECREF(exc);
6690 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006691}
6692
Alexander Belopolsky40018472011-02-26 01:02:56 +00006693PyObject *
6694PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006695 Py_ssize_t size,
6696 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006697{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006698 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006699}
6700
Alexander Belopolsky40018472011-02-26 01:02:56 +00006701PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006702_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006703{
6704 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006705 PyErr_BadArgument();
6706 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006707 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006708 if (PyUnicode_READY(unicode) == -1)
6709 return NULL;
6710 /* Fast path: if it is a one-byte string, construct
6711 bytes object directly. */
6712 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6713 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6714 PyUnicode_GET_LENGTH(unicode));
6715 /* Non-Latin-1 characters present. Defer to above function to
6716 raise the exception. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006717 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006718 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006719 errors);
6720}
6721
6722PyObject*
6723PyUnicode_AsLatin1String(PyObject *unicode)
6724{
6725 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006726}
6727
6728/* --- 7-bit ASCII Codec -------------------------------------------------- */
6729
Alexander Belopolsky40018472011-02-26 01:02:56 +00006730PyObject *
6731PyUnicode_DecodeASCII(const char *s,
6732 Py_ssize_t size,
6733 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006734{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006735 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006736 PyUnicodeObject *v;
Victor Stinner702c7342011-10-05 13:50:52 +02006737 Py_UNICODE *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006738 Py_ssize_t startinpos;
6739 Py_ssize_t endinpos;
6740 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006741 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006742 int has_error;
6743 const unsigned char *p = (const unsigned char *)s;
6744 const unsigned char *end = p + size;
6745 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006746 PyObject *errorHandler = NULL;
6747 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006748
Guido van Rossumd57fd912000-03-10 22:53:23 +00006749 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006750 if (size == 1 && (unsigned char)s[0] < 128)
6751 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006752
Victor Stinner702c7342011-10-05 13:50:52 +02006753 has_error = 0;
6754 while (p < end && !has_error) {
6755 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6756 an explanation. */
6757 if (!((size_t) p & LONG_PTR_MASK)) {
6758 /* Help register allocation */
6759 register const unsigned char *_p = p;
6760 while (_p < aligned_end) {
6761 unsigned long value = *(unsigned long *) _p;
6762 if (value & ASCII_CHAR_MASK) {
6763 has_error = 1;
6764 break;
6765 }
6766 _p += SIZEOF_LONG;
6767 }
6768 if (_p == end)
6769 break;
6770 if (has_error)
6771 break;
6772 p = _p;
6773 }
6774 if (*p & 0x80) {
6775 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006776 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006777 }
6778 else {
6779 ++p;
6780 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006781 }
Victor Stinner702c7342011-10-05 13:50:52 +02006782 if (!has_error)
6783 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006784
Guido van Rossumd57fd912000-03-10 22:53:23 +00006785 v = _PyUnicode_New(size);
6786 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006787 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006788 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006789 return (PyObject *)v;
Victor Stinner702c7342011-10-05 13:50:52 +02006790 u = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006791 e = s + size;
6792 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006793 register unsigned char c = (unsigned char)*s;
6794 if (c < 128) {
Victor Stinner702c7342011-10-05 13:50:52 +02006795 *u++ = c;
Benjamin Peterson29060642009-01-31 22:14:21 +00006796 ++s;
6797 }
6798 else {
6799 startinpos = s-starts;
6800 endinpos = startinpos + 1;
Victor Stinner702c7342011-10-05 13:50:52 +02006801 outpos = u - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006802 if (unicode_decode_call_errorhandler(
6803 errors, &errorHandler,
6804 "ascii", "ordinal not in range(128)",
6805 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinner702c7342011-10-05 13:50:52 +02006806 &v, &outpos, &u))
Benjamin Peterson29060642009-01-31 22:14:21 +00006807 goto onError;
6808 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006809 }
Victor Stinner702c7342011-10-05 13:50:52 +02006810 if (u - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
6811 if (PyUnicode_Resize((PyObject**)&v, u - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006812 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006813 Py_XDECREF(errorHandler);
6814 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006815#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006816 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006817 Py_DECREF(v);
6818 return NULL;
6819 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006820#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006821 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006822 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006823
Benjamin Peterson29060642009-01-31 22:14:21 +00006824 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006825 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006826 Py_XDECREF(errorHandler);
6827 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006828 return NULL;
6829}
6830
Alexander Belopolsky40018472011-02-26 01:02:56 +00006831PyObject *
6832PyUnicode_EncodeASCII(const Py_UNICODE *p,
6833 Py_ssize_t size,
6834 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006835{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006836 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006837}
6838
Alexander Belopolsky40018472011-02-26 01:02:56 +00006839PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006840_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006841{
6842 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006843 PyErr_BadArgument();
6844 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006845 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006846 if (PyUnicode_READY(unicode) == -1)
6847 return NULL;
6848 /* Fast path: if it is an ASCII-only string, construct bytes object
6849 directly. Else defer to above function to raise the exception. */
6850 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6851 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6852 PyUnicode_GET_LENGTH(unicode));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006853 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006854 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006855 errors);
6856}
6857
6858PyObject *
6859PyUnicode_AsASCIIString(PyObject *unicode)
6860{
6861 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006862}
6863
Victor Stinner99b95382011-07-04 14:23:54 +02006864#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006865
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006866/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006867
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006868#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006869#define NEED_RETRY
6870#endif
6871
6872/* XXX This code is limited to "true" double-byte encodings, as
6873 a) it assumes an incomplete character consists of a single byte, and
6874 b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
Benjamin Peterson29060642009-01-31 22:14:21 +00006875 encodings, see IsDBCSLeadByteEx documentation. */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006876
Alexander Belopolsky40018472011-02-26 01:02:56 +00006877static int
6878is_dbcs_lead_byte(const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006879{
6880 const char *curr = s + offset;
6881
6882 if (IsDBCSLeadByte(*curr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006883 const char *prev = CharPrev(s, curr);
6884 return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006885 }
6886 return 0;
6887}
6888
6889/*
6890 * Decode MBCS string into unicode object. If 'final' is set, converts
6891 * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
6892 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006893static int
6894decode_mbcs(PyUnicodeObject **v,
6895 const char *s, /* MBCS string */
6896 int size, /* sizeof MBCS string */
6897 int final,
6898 const char *errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006899{
6900 Py_UNICODE *p;
Victor Stinner554f3f02010-06-16 23:33:54 +00006901 Py_ssize_t n;
6902 DWORD usize;
6903 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006904
6905 assert(size >= 0);
6906
Victor Stinner554f3f02010-06-16 23:33:54 +00006907 /* check and handle 'errors' arg */
6908 if (errors==NULL || strcmp(errors, "strict")==0)
6909 flags = MB_ERR_INVALID_CHARS;
6910 else if (strcmp(errors, "ignore")==0)
6911 flags = 0;
6912 else {
6913 PyErr_Format(PyExc_ValueError,
6914 "mbcs encoding does not support errors='%s'",
6915 errors);
6916 return -1;
6917 }
6918
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006919 /* Skip trailing lead-byte unless 'final' is set */
6920 if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006921 --size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006922
6923 /* First get the size of the result */
6924 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00006925 usize = MultiByteToWideChar(CP_ACP, flags, s, size, NULL, 0);
6926 if (usize==0)
6927 goto mbcs_decode_error;
6928 } else
6929 usize = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006930
6931 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006932 /* Create unicode object */
6933 *v = _PyUnicode_New(usize);
6934 if (*v == NULL)
6935 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00006936 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006937 }
6938 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006939 /* Extend unicode object */
6940 n = PyUnicode_GET_SIZE(*v);
Victor Stinner2fd82272011-10-03 04:06:05 +02006941 if (PyUnicode_Resize((PyObject**)v, n + usize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006942 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006943 }
6944
6945 /* Do the conversion */
Victor Stinner554f3f02010-06-16 23:33:54 +00006946 if (usize > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006947 p = PyUnicode_AS_UNICODE(*v) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00006948 if (0 == MultiByteToWideChar(CP_ACP, flags, s, size, p, usize)) {
6949 goto mbcs_decode_error;
Benjamin Peterson29060642009-01-31 22:14:21 +00006950 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006951 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006952 return size;
Victor Stinner554f3f02010-06-16 23:33:54 +00006953
6954mbcs_decode_error:
6955 /* If the last error was ERROR_NO_UNICODE_TRANSLATION, then
6956 we raise a UnicodeDecodeError - else it is a 'generic'
6957 windows error
6958 */
6959 if (GetLastError()==ERROR_NO_UNICODE_TRANSLATION) {
6960 /* Ideally, we should get reason from FormatMessage - this
6961 is the Windows 2000 English version of the message
6962 */
6963 PyObject *exc = NULL;
6964 const char *reason = "No mapping for the Unicode character exists "
6965 "in the target multi-byte code page.";
6966 make_decode_exception(&exc, "mbcs", s, size, 0, 0, reason);
6967 if (exc != NULL) {
6968 PyCodec_StrictErrors(exc);
6969 Py_DECREF(exc);
6970 }
6971 } else {
6972 PyErr_SetFromWindowsErrWithFilename(0, NULL);
6973 }
6974 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006975}
6976
Alexander Belopolsky40018472011-02-26 01:02:56 +00006977PyObject *
6978PyUnicode_DecodeMBCSStateful(const char *s,
6979 Py_ssize_t size,
6980 const char *errors,
6981 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006982{
6983 PyUnicodeObject *v = NULL;
6984 int done;
6985
6986 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006987 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006988
6989#ifdef NEED_RETRY
6990 retry:
6991 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00006992 done = decode_mbcs(&v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006993 else
6994#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00006995 done = decode_mbcs(&v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006996
6997 if (done < 0) {
6998 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006999 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007000 }
7001
7002 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007003 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007004
7005#ifdef NEED_RETRY
7006 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007007 s += done;
7008 size -= done;
7009 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007010 }
7011#endif
Victor Stinner17efeed2011-10-04 20:05:46 +02007012#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007013 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007014 Py_DECREF(v);
7015 return NULL;
7016 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007017#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007018 assert(_PyUnicode_CheckConsistency(v, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007019 return (PyObject *)v;
7020}
7021
Alexander Belopolsky40018472011-02-26 01:02:56 +00007022PyObject *
7023PyUnicode_DecodeMBCS(const char *s,
7024 Py_ssize_t size,
7025 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007026{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007027 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7028}
7029
7030/*
7031 * Convert unicode into string object (MBCS).
7032 * Returns 0 if succeed, -1 otherwise.
7033 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007034static int
7035encode_mbcs(PyObject **repr,
7036 const Py_UNICODE *p, /* unicode */
7037 int size, /* size of unicode */
7038 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007039{
Victor Stinner554f3f02010-06-16 23:33:54 +00007040 BOOL usedDefaultChar = FALSE;
7041 BOOL *pusedDefaultChar;
7042 int mbcssize;
7043 Py_ssize_t n;
7044 PyObject *exc = NULL;
7045 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007046
7047 assert(size >= 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007048
Victor Stinner554f3f02010-06-16 23:33:54 +00007049 /* check and handle 'errors' arg */
7050 if (errors==NULL || strcmp(errors, "strict")==0) {
7051 flags = WC_NO_BEST_FIT_CHARS;
7052 pusedDefaultChar = &usedDefaultChar;
7053 } else if (strcmp(errors, "replace")==0) {
7054 flags = 0;
7055 pusedDefaultChar = NULL;
7056 } else {
7057 PyErr_Format(PyExc_ValueError,
7058 "mbcs encoding does not support errors='%s'",
7059 errors);
7060 return -1;
7061 }
7062
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007063 /* First get the size of the result */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007064 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00007065 mbcssize = WideCharToMultiByte(CP_ACP, flags, p, size, NULL, 0,
7066 NULL, pusedDefaultChar);
Benjamin Peterson29060642009-01-31 22:14:21 +00007067 if (mbcssize == 0) {
7068 PyErr_SetFromWindowsErrWithFilename(0, NULL);
7069 return -1;
7070 }
Victor Stinner554f3f02010-06-16 23:33:54 +00007071 /* If we used a default char, then we failed! */
7072 if (pusedDefaultChar && *pusedDefaultChar)
7073 goto mbcs_encode_error;
7074 } else {
7075 mbcssize = 0;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007076 }
7077
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007078 if (*repr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007079 /* Create string object */
7080 *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
7081 if (*repr == NULL)
7082 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00007083 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007084 }
7085 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007086 /* Extend string object */
7087 n = PyBytes_Size(*repr);
7088 if (_PyBytes_Resize(repr, n + mbcssize) < 0)
7089 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007090 }
7091
7092 /* Do the conversion */
7093 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007094 char *s = PyBytes_AS_STRING(*repr) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00007095 if (0 == WideCharToMultiByte(CP_ACP, flags, p, size, s, mbcssize,
7096 NULL, pusedDefaultChar)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007097 PyErr_SetFromWindowsErrWithFilename(0, NULL);
7098 return -1;
7099 }
Victor Stinner554f3f02010-06-16 23:33:54 +00007100 if (pusedDefaultChar && *pusedDefaultChar)
7101 goto mbcs_encode_error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007102 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007103 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007104
7105mbcs_encode_error:
7106 raise_encode_exception(&exc, "mbcs", p, size, 0, 0, "invalid character");
7107 Py_XDECREF(exc);
7108 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007109}
7110
Alexander Belopolsky40018472011-02-26 01:02:56 +00007111PyObject *
7112PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7113 Py_ssize_t size,
7114 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007115{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007116 PyObject *repr = NULL;
7117 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00007118
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007119#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00007120 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007121 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00007122 ret = encode_mbcs(&repr, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007123 else
7124#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00007125 ret = encode_mbcs(&repr, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007126
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007127 if (ret < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007128 Py_XDECREF(repr);
7129 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007130 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007131
7132#ifdef NEED_RETRY
7133 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007134 p += INT_MAX;
7135 size -= INT_MAX;
7136 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007137 }
7138#endif
7139
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007140 return repr;
7141}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007142
Alexander Belopolsky40018472011-02-26 01:02:56 +00007143PyObject *
7144PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007145{
7146 if (!PyUnicode_Check(unicode)) {
7147 PyErr_BadArgument();
7148 return NULL;
7149 }
7150 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00007151 PyUnicode_GET_SIZE(unicode),
7152 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007153}
7154
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007155#undef NEED_RETRY
7156
Victor Stinner99b95382011-07-04 14:23:54 +02007157#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007158
Guido van Rossumd57fd912000-03-10 22:53:23 +00007159/* --- Character Mapping Codec -------------------------------------------- */
7160
Alexander Belopolsky40018472011-02-26 01:02:56 +00007161PyObject *
7162PyUnicode_DecodeCharmap(const char *s,
7163 Py_ssize_t size,
7164 PyObject *mapping,
7165 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007166{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007167 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007168 Py_ssize_t startinpos;
7169 Py_ssize_t endinpos;
7170 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007171 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007172 PyUnicodeObject *v;
7173 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007174 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007175 PyObject *errorHandler = NULL;
7176 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007177 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007178 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00007179
Guido van Rossumd57fd912000-03-10 22:53:23 +00007180 /* Default to Latin-1 */
7181 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007182 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007183
7184 v = _PyUnicode_New(size);
7185 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007186 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007187 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007188 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007189 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007190 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007191 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007192 mapstring = PyUnicode_AS_UNICODE(mapping);
7193 maplen = PyUnicode_GET_SIZE(mapping);
7194 while (s < e) {
7195 unsigned char ch = *s;
7196 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007197
Benjamin Peterson29060642009-01-31 22:14:21 +00007198 if (ch < maplen)
7199 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00007200
Benjamin Peterson29060642009-01-31 22:14:21 +00007201 if (x == 0xfffe) {
7202 /* undefined mapping */
7203 outpos = p-PyUnicode_AS_UNICODE(v);
7204 startinpos = s-starts;
7205 endinpos = startinpos+1;
7206 if (unicode_decode_call_errorhandler(
7207 errors, &errorHandler,
7208 "charmap", "character maps to <undefined>",
7209 &starts, &e, &startinpos, &endinpos, &exc, &s,
7210 &v, &outpos, &p)) {
7211 goto onError;
7212 }
7213 continue;
7214 }
7215 *p++ = x;
7216 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007217 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007218 }
7219 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007220 while (s < e) {
7221 unsigned char ch = *s;
7222 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007223
Benjamin Peterson29060642009-01-31 22:14:21 +00007224 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7225 w = PyLong_FromLong((long)ch);
7226 if (w == NULL)
7227 goto onError;
7228 x = PyObject_GetItem(mapping, w);
7229 Py_DECREF(w);
7230 if (x == NULL) {
7231 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7232 /* No mapping found means: mapping is undefined. */
7233 PyErr_Clear();
7234 x = Py_None;
7235 Py_INCREF(x);
7236 } else
7237 goto onError;
7238 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007239
Benjamin Peterson29060642009-01-31 22:14:21 +00007240 /* Apply mapping */
7241 if (PyLong_Check(x)) {
7242 long value = PyLong_AS_LONG(x);
7243 if (value < 0 || value > 65535) {
7244 PyErr_SetString(PyExc_TypeError,
7245 "character mapping must be in range(65536)");
7246 Py_DECREF(x);
7247 goto onError;
7248 }
7249 *p++ = (Py_UNICODE)value;
7250 }
7251 else if (x == Py_None) {
7252 /* undefined mapping */
7253 outpos = p-PyUnicode_AS_UNICODE(v);
7254 startinpos = s-starts;
7255 endinpos = startinpos+1;
7256 if (unicode_decode_call_errorhandler(
7257 errors, &errorHandler,
7258 "charmap", "character maps to <undefined>",
7259 &starts, &e, &startinpos, &endinpos, &exc, &s,
7260 &v, &outpos, &p)) {
7261 Py_DECREF(x);
7262 goto onError;
7263 }
7264 Py_DECREF(x);
7265 continue;
7266 }
7267 else if (PyUnicode_Check(x)) {
7268 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007269
Benjamin Peterson29060642009-01-31 22:14:21 +00007270 if (targetsize == 1)
7271 /* 1-1 mapping */
7272 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007273
Benjamin Peterson29060642009-01-31 22:14:21 +00007274 else if (targetsize > 1) {
7275 /* 1-n mapping */
7276 if (targetsize > extrachars) {
7277 /* resize first */
7278 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
7279 Py_ssize_t needed = (targetsize - extrachars) + \
7280 (targetsize << 2);
7281 extrachars += needed;
7282 /* XXX overflow detection missing */
Victor Stinnerfe226c02011-10-03 03:52:20 +02007283 if (PyUnicode_Resize((PyObject**)&v,
Benjamin Peterson29060642009-01-31 22:14:21 +00007284 PyUnicode_GET_SIZE(v) + needed) < 0) {
7285 Py_DECREF(x);
7286 goto onError;
7287 }
7288 p = PyUnicode_AS_UNICODE(v) + oldpos;
7289 }
7290 Py_UNICODE_COPY(p,
7291 PyUnicode_AS_UNICODE(x),
7292 targetsize);
7293 p += targetsize;
7294 extrachars -= targetsize;
7295 }
7296 /* 1-0 mapping: skip the character */
7297 }
7298 else {
7299 /* wrong return value */
7300 PyErr_SetString(PyExc_TypeError,
7301 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007302 Py_DECREF(x);
7303 goto onError;
7304 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007305 Py_DECREF(x);
7306 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007307 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007308 }
7309 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Victor Stinnerfe226c02011-10-03 03:52:20 +02007310 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007311 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007312 Py_XDECREF(errorHandler);
7313 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02007314#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007315 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007316 Py_DECREF(v);
7317 return NULL;
7318 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007319#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007320 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007321 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00007322
Benjamin Peterson29060642009-01-31 22:14:21 +00007323 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007324 Py_XDECREF(errorHandler);
7325 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007326 Py_XDECREF(v);
7327 return NULL;
7328}
7329
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007330/* Charmap encoding: the lookup table */
7331
Alexander Belopolsky40018472011-02-26 01:02:56 +00007332struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007333 PyObject_HEAD
7334 unsigned char level1[32];
7335 int count2, count3;
7336 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007337};
7338
7339static PyObject*
7340encoding_map_size(PyObject *obj, PyObject* args)
7341{
7342 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007343 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007344 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007345}
7346
7347static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007348 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007349 PyDoc_STR("Return the size (in bytes) of this object") },
7350 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007351};
7352
7353static void
7354encoding_map_dealloc(PyObject* o)
7355{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007356 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007357}
7358
7359static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007360 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007361 "EncodingMap", /*tp_name*/
7362 sizeof(struct encoding_map), /*tp_basicsize*/
7363 0, /*tp_itemsize*/
7364 /* methods */
7365 encoding_map_dealloc, /*tp_dealloc*/
7366 0, /*tp_print*/
7367 0, /*tp_getattr*/
7368 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007369 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007370 0, /*tp_repr*/
7371 0, /*tp_as_number*/
7372 0, /*tp_as_sequence*/
7373 0, /*tp_as_mapping*/
7374 0, /*tp_hash*/
7375 0, /*tp_call*/
7376 0, /*tp_str*/
7377 0, /*tp_getattro*/
7378 0, /*tp_setattro*/
7379 0, /*tp_as_buffer*/
7380 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7381 0, /*tp_doc*/
7382 0, /*tp_traverse*/
7383 0, /*tp_clear*/
7384 0, /*tp_richcompare*/
7385 0, /*tp_weaklistoffset*/
7386 0, /*tp_iter*/
7387 0, /*tp_iternext*/
7388 encoding_map_methods, /*tp_methods*/
7389 0, /*tp_members*/
7390 0, /*tp_getset*/
7391 0, /*tp_base*/
7392 0, /*tp_dict*/
7393 0, /*tp_descr_get*/
7394 0, /*tp_descr_set*/
7395 0, /*tp_dictoffset*/
7396 0, /*tp_init*/
7397 0, /*tp_alloc*/
7398 0, /*tp_new*/
7399 0, /*tp_free*/
7400 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007401};
7402
7403PyObject*
7404PyUnicode_BuildEncodingMap(PyObject* string)
7405{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007406 PyObject *result;
7407 struct encoding_map *mresult;
7408 int i;
7409 int need_dict = 0;
7410 unsigned char level1[32];
7411 unsigned char level2[512];
7412 unsigned char *mlevel1, *mlevel2, *mlevel3;
7413 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007414 int kind;
7415 void *data;
7416 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007417
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007418 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007419 PyErr_BadArgument();
7420 return NULL;
7421 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007422 kind = PyUnicode_KIND(string);
7423 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007424 memset(level1, 0xFF, sizeof level1);
7425 memset(level2, 0xFF, sizeof level2);
7426
7427 /* If there isn't a one-to-one mapping of NULL to \0,
7428 or if there are non-BMP characters, we need to use
7429 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007430 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007431 need_dict = 1;
7432 for (i = 1; i < 256; i++) {
7433 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007434 ch = PyUnicode_READ(kind, data, i);
7435 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007436 need_dict = 1;
7437 break;
7438 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007439 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007440 /* unmapped character */
7441 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007442 l1 = ch >> 11;
7443 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007444 if (level1[l1] == 0xFF)
7445 level1[l1] = count2++;
7446 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007447 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007448 }
7449
7450 if (count2 >= 0xFF || count3 >= 0xFF)
7451 need_dict = 1;
7452
7453 if (need_dict) {
7454 PyObject *result = PyDict_New();
7455 PyObject *key, *value;
7456 if (!result)
7457 return NULL;
7458 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007459 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007460 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007461 if (!key || !value)
7462 goto failed1;
7463 if (PyDict_SetItem(result, key, value) == -1)
7464 goto failed1;
7465 Py_DECREF(key);
7466 Py_DECREF(value);
7467 }
7468 return result;
7469 failed1:
7470 Py_XDECREF(key);
7471 Py_XDECREF(value);
7472 Py_DECREF(result);
7473 return NULL;
7474 }
7475
7476 /* Create a three-level trie */
7477 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7478 16*count2 + 128*count3 - 1);
7479 if (!result)
7480 return PyErr_NoMemory();
7481 PyObject_Init(result, &EncodingMapType);
7482 mresult = (struct encoding_map*)result;
7483 mresult->count2 = count2;
7484 mresult->count3 = count3;
7485 mlevel1 = mresult->level1;
7486 mlevel2 = mresult->level23;
7487 mlevel3 = mresult->level23 + 16*count2;
7488 memcpy(mlevel1, level1, 32);
7489 memset(mlevel2, 0xFF, 16*count2);
7490 memset(mlevel3, 0, 128*count3);
7491 count3 = 0;
7492 for (i = 1; i < 256; i++) {
7493 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007494 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007495 /* unmapped character */
7496 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007497 o1 = PyUnicode_READ(kind, data, i)>>11;
7498 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007499 i2 = 16*mlevel1[o1] + o2;
7500 if (mlevel2[i2] == 0xFF)
7501 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007502 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007503 i3 = 128*mlevel2[i2] + o3;
7504 mlevel3[i3] = i;
7505 }
7506 return result;
7507}
7508
7509static int
7510encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
7511{
7512 struct encoding_map *map = (struct encoding_map*)mapping;
7513 int l1 = c>>11;
7514 int l2 = (c>>7) & 0xF;
7515 int l3 = c & 0x7F;
7516 int i;
7517
7518#ifdef Py_UNICODE_WIDE
7519 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007520 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007521 }
7522#endif
7523 if (c == 0)
7524 return 0;
7525 /* level 1*/
7526 i = map->level1[l1];
7527 if (i == 0xFF) {
7528 return -1;
7529 }
7530 /* level 2*/
7531 i = map->level23[16*i+l2];
7532 if (i == 0xFF) {
7533 return -1;
7534 }
7535 /* level 3 */
7536 i = map->level23[16*map->count2 + 128*i + l3];
7537 if (i == 0) {
7538 return -1;
7539 }
7540 return i;
7541}
7542
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007543/* Lookup the character ch in the mapping. If the character
7544 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007545 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007546static PyObject *
7547charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007548{
Christian Heimes217cfd12007-12-02 14:31:20 +00007549 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007550 PyObject *x;
7551
7552 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007553 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007554 x = PyObject_GetItem(mapping, w);
7555 Py_DECREF(w);
7556 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007557 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7558 /* No mapping found means: mapping is undefined. */
7559 PyErr_Clear();
7560 x = Py_None;
7561 Py_INCREF(x);
7562 return x;
7563 } else
7564 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007565 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007566 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007567 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007568 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007569 long value = PyLong_AS_LONG(x);
7570 if (value < 0 || value > 255) {
7571 PyErr_SetString(PyExc_TypeError,
7572 "character mapping must be in range(256)");
7573 Py_DECREF(x);
7574 return NULL;
7575 }
7576 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007577 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007578 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007579 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007580 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007581 /* wrong return value */
7582 PyErr_Format(PyExc_TypeError,
7583 "character mapping must return integer, bytes or None, not %.400s",
7584 x->ob_type->tp_name);
7585 Py_DECREF(x);
7586 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007587 }
7588}
7589
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007590static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007591charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007592{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007593 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7594 /* exponentially overallocate to minimize reallocations */
7595 if (requiredsize < 2*outsize)
7596 requiredsize = 2*outsize;
7597 if (_PyBytes_Resize(outobj, requiredsize))
7598 return -1;
7599 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007600}
7601
Benjamin Peterson14339b62009-01-31 16:36:08 +00007602typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007603 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007604} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007605/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007606 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007607 space is available. Return a new reference to the object that
7608 was put in the output buffer, or Py_None, if the mapping was undefined
7609 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007610 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007611static charmapencode_result
7612charmapencode_output(Py_UNICODE c, PyObject *mapping,
7613 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007614{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007615 PyObject *rep;
7616 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007617 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007618
Christian Heimes90aa7642007-12-19 02:45:37 +00007619 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007620 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007621 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007622 if (res == -1)
7623 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007624 if (outsize<requiredsize)
7625 if (charmapencode_resize(outobj, outpos, requiredsize))
7626 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007627 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007628 outstart[(*outpos)++] = (char)res;
7629 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007630 }
7631
7632 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007633 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007634 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007635 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007636 Py_DECREF(rep);
7637 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007638 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007639 if (PyLong_Check(rep)) {
7640 Py_ssize_t requiredsize = *outpos+1;
7641 if (outsize<requiredsize)
7642 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7643 Py_DECREF(rep);
7644 return enc_EXCEPTION;
7645 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007646 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007647 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007648 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007649 else {
7650 const char *repchars = PyBytes_AS_STRING(rep);
7651 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7652 Py_ssize_t requiredsize = *outpos+repsize;
7653 if (outsize<requiredsize)
7654 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7655 Py_DECREF(rep);
7656 return enc_EXCEPTION;
7657 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007658 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007659 memcpy(outstart + *outpos, repchars, repsize);
7660 *outpos += repsize;
7661 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007662 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007663 Py_DECREF(rep);
7664 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007665}
7666
7667/* handle an error in PyUnicode_EncodeCharmap
7668 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007669static int
7670charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00007671 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007672 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007673 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007674 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007675{
7676 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007677 Py_ssize_t repsize;
7678 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007679 Py_UNICODE *uni2;
7680 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007681 Py_ssize_t collstartpos = *inpos;
7682 Py_ssize_t collendpos = *inpos+1;
7683 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007684 char *encoding = "charmap";
7685 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007686 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007687
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007688 /* find all unencodable characters */
7689 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007690 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007691 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007692 int res = encoding_map_lookup(p[collendpos], mapping);
7693 if (res != -1)
7694 break;
7695 ++collendpos;
7696 continue;
7697 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007698
Benjamin Peterson29060642009-01-31 22:14:21 +00007699 rep = charmapencode_lookup(p[collendpos], mapping);
7700 if (rep==NULL)
7701 return -1;
7702 else if (rep!=Py_None) {
7703 Py_DECREF(rep);
7704 break;
7705 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007706 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007707 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007708 }
7709 /* cache callback name lookup
7710 * (if not done yet, i.e. it's the first error) */
7711 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007712 if ((errors==NULL) || (!strcmp(errors, "strict")))
7713 *known_errorHandler = 1;
7714 else if (!strcmp(errors, "replace"))
7715 *known_errorHandler = 2;
7716 else if (!strcmp(errors, "ignore"))
7717 *known_errorHandler = 3;
7718 else if (!strcmp(errors, "xmlcharrefreplace"))
7719 *known_errorHandler = 4;
7720 else
7721 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007722 }
7723 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007724 case 1: /* strict */
7725 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7726 return -1;
7727 case 2: /* replace */
7728 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007729 x = charmapencode_output('?', mapping, res, respos);
7730 if (x==enc_EXCEPTION) {
7731 return -1;
7732 }
7733 else if (x==enc_FAILED) {
7734 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7735 return -1;
7736 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007737 }
7738 /* fall through */
7739 case 3: /* ignore */
7740 *inpos = collendpos;
7741 break;
7742 case 4: /* xmlcharrefreplace */
7743 /* generate replacement (temporarily (mis)uses p) */
7744 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007745 char buffer[2+29+1+1];
7746 char *cp;
7747 sprintf(buffer, "&#%d;", (int)p[collpos]);
7748 for (cp = buffer; *cp; ++cp) {
7749 x = charmapencode_output(*cp, mapping, res, respos);
7750 if (x==enc_EXCEPTION)
7751 return -1;
7752 else if (x==enc_FAILED) {
7753 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7754 return -1;
7755 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007756 }
7757 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007758 *inpos = collendpos;
7759 break;
7760 default:
7761 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00007762 encoding, reason, p, size, exceptionObject,
7763 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007764 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007765 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00007766 if (PyBytes_Check(repunicode)) {
7767 /* Directly copy bytes result to output. */
7768 Py_ssize_t outsize = PyBytes_Size(*res);
7769 Py_ssize_t requiredsize;
7770 repsize = PyBytes_Size(repunicode);
7771 requiredsize = *respos + repsize;
7772 if (requiredsize > outsize)
7773 /* Make room for all additional bytes. */
7774 if (charmapencode_resize(res, respos, requiredsize)) {
7775 Py_DECREF(repunicode);
7776 return -1;
7777 }
7778 memcpy(PyBytes_AsString(*res) + *respos,
7779 PyBytes_AsString(repunicode), repsize);
7780 *respos += repsize;
7781 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007782 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00007783 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007784 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007785 /* generate replacement */
7786 repsize = PyUnicode_GET_SIZE(repunicode);
7787 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007788 x = charmapencode_output(*uni2, mapping, res, respos);
7789 if (x==enc_EXCEPTION) {
7790 return -1;
7791 }
7792 else if (x==enc_FAILED) {
7793 Py_DECREF(repunicode);
7794 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7795 return -1;
7796 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007797 }
7798 *inpos = newpos;
7799 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007800 }
7801 return 0;
7802}
7803
Alexander Belopolsky40018472011-02-26 01:02:56 +00007804PyObject *
7805PyUnicode_EncodeCharmap(const Py_UNICODE *p,
7806 Py_ssize_t size,
7807 PyObject *mapping,
7808 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007809{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007810 /* output object */
7811 PyObject *res = NULL;
7812 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007813 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007814 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007815 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007816 PyObject *errorHandler = NULL;
7817 PyObject *exc = NULL;
7818 /* the following variable is used for caching string comparisons
7819 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
7820 * 3=ignore, 4=xmlcharrefreplace */
7821 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007822
7823 /* Default to Latin-1 */
7824 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007825 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007826
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007827 /* allocate enough for a simple encoding without
7828 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00007829 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007830 if (res == NULL)
7831 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00007832 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007833 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007834
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007835 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007836 /* try to encode it */
7837 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
7838 if (x==enc_EXCEPTION) /* error */
7839 goto onError;
7840 if (x==enc_FAILED) { /* unencodable character */
7841 if (charmap_encoding_error(p, size, &inpos, mapping,
7842 &exc,
7843 &known_errorHandler, &errorHandler, errors,
7844 &res, &respos)) {
7845 goto onError;
7846 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007847 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007848 else
7849 /* done with this character => adjust input position */
7850 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007851 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007852
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007853 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00007854 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00007855 if (_PyBytes_Resize(&res, respos) < 0)
7856 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00007857
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007858 Py_XDECREF(exc);
7859 Py_XDECREF(errorHandler);
7860 return res;
7861
Benjamin Peterson29060642009-01-31 22:14:21 +00007862 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007863 Py_XDECREF(res);
7864 Py_XDECREF(exc);
7865 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007866 return NULL;
7867}
7868
Alexander Belopolsky40018472011-02-26 01:02:56 +00007869PyObject *
7870PyUnicode_AsCharmapString(PyObject *unicode,
7871 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007872{
7873 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007874 PyErr_BadArgument();
7875 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007876 }
7877 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00007878 PyUnicode_GET_SIZE(unicode),
7879 mapping,
7880 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007881}
7882
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007883/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007884static void
7885make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007886 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007887 Py_ssize_t startpos, Py_ssize_t endpos,
7888 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007889{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007890 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007891 *exceptionObject = _PyUnicodeTranslateError_Create(
7892 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007893 }
7894 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007895 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
7896 goto onError;
7897 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
7898 goto onError;
7899 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
7900 goto onError;
7901 return;
7902 onError:
7903 Py_DECREF(*exceptionObject);
7904 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007905 }
7906}
7907
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007908/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007909static void
7910raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007911 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007912 Py_ssize_t startpos, Py_ssize_t endpos,
7913 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007914{
7915 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007916 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007917 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007918 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007919}
7920
7921/* error handling callback helper:
7922 build arguments, call the callback and check the arguments,
7923 put the result into newpos and return the replacement string, which
7924 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007925static PyObject *
7926unicode_translate_call_errorhandler(const char *errors,
7927 PyObject **errorHandler,
7928 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007929 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007930 Py_ssize_t startpos, Py_ssize_t endpos,
7931 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007932{
Benjamin Peterson142957c2008-07-04 19:55:29 +00007933 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007934
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007935 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007936 PyObject *restuple;
7937 PyObject *resunicode;
7938
7939 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007940 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007941 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007942 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007943 }
7944
7945 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007946 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007947 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007948 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007949
7950 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00007951 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007952 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007953 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007954 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00007955 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00007956 Py_DECREF(restuple);
7957 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007958 }
7959 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00007960 &resunicode, &i_newpos)) {
7961 Py_DECREF(restuple);
7962 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007963 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00007964 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007965 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007966 else
7967 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007968 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007969 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
7970 Py_DECREF(restuple);
7971 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00007972 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007973 Py_INCREF(resunicode);
7974 Py_DECREF(restuple);
7975 return resunicode;
7976}
7977
7978/* Lookup the character ch in the mapping and put the result in result,
7979 which must be decrefed by the caller.
7980 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007981static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007982charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007983{
Christian Heimes217cfd12007-12-02 14:31:20 +00007984 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007985 PyObject *x;
7986
7987 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007988 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007989 x = PyObject_GetItem(mapping, w);
7990 Py_DECREF(w);
7991 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007992 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7993 /* No mapping found means: use 1:1 mapping. */
7994 PyErr_Clear();
7995 *result = NULL;
7996 return 0;
7997 } else
7998 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007999 }
8000 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008001 *result = x;
8002 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008003 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008004 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008005 long value = PyLong_AS_LONG(x);
8006 long max = PyUnicode_GetMax();
8007 if (value < 0 || value > max) {
8008 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008009 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008010 Py_DECREF(x);
8011 return -1;
8012 }
8013 *result = x;
8014 return 0;
8015 }
8016 else if (PyUnicode_Check(x)) {
8017 *result = x;
8018 return 0;
8019 }
8020 else {
8021 /* wrong return value */
8022 PyErr_SetString(PyExc_TypeError,
8023 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008024 Py_DECREF(x);
8025 return -1;
8026 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008027}
8028/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008029 if not reallocate and adjust various state variables.
8030 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008031static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008032charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008033 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008034{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008035 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008036 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008037 /* exponentially overallocate to minimize reallocations */
8038 if (requiredsize < 2 * oldsize)
8039 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008040 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8041 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008042 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008043 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008044 }
8045 return 0;
8046}
8047/* lookup the character, put the result in the output string and adjust
8048 various state variables. Return a new reference to the object that
8049 was put in the output buffer in *result, or Py_None, if the mapping was
8050 undefined (in which case no character was written).
8051 The called must decref result.
8052 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008053static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008054charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8055 PyObject *mapping, Py_UCS4 **output,
8056 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008057 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008058{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008059 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8060 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008061 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008062 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008063 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008064 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008065 }
8066 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008067 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008068 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008069 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008070 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008071 }
8072 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008073 Py_ssize_t repsize;
8074 if (PyUnicode_READY(*res) == -1)
8075 return -1;
8076 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008077 if (repsize==1) {
8078 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008079 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008080 }
8081 else if (repsize!=0) {
8082 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008083 Py_ssize_t requiredsize = *opos +
8084 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008085 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008086 Py_ssize_t i;
8087 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008088 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008089 for(i = 0; i < repsize; i++)
8090 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008091 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008092 }
8093 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008094 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008095 return 0;
8096}
8097
Alexander Belopolsky40018472011-02-26 01:02:56 +00008098PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008099_PyUnicode_TranslateCharmap(PyObject *input,
8100 PyObject *mapping,
8101 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008102{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008103 /* input object */
8104 char *idata;
8105 Py_ssize_t size, i;
8106 int kind;
8107 /* output buffer */
8108 Py_UCS4 *output = NULL;
8109 Py_ssize_t osize;
8110 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008111 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008112 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008113 char *reason = "character maps to <undefined>";
8114 PyObject *errorHandler = NULL;
8115 PyObject *exc = NULL;
8116 /* the following variable is used for caching string comparisons
8117 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8118 * 3=ignore, 4=xmlcharrefreplace */
8119 int known_errorHandler = -1;
8120
Guido van Rossumd57fd912000-03-10 22:53:23 +00008121 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008122 PyErr_BadArgument();
8123 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008124 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008125
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008126 if (PyUnicode_READY(input) == -1)
8127 return NULL;
8128 idata = (char*)PyUnicode_DATA(input);
8129 kind = PyUnicode_KIND(input);
8130 size = PyUnicode_GET_LENGTH(input);
8131 i = 0;
8132
8133 if (size == 0) {
8134 Py_INCREF(input);
8135 return input;
8136 }
8137
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008138 /* allocate enough for a simple 1:1 translation without
8139 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008140 osize = size;
8141 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8142 opos = 0;
8143 if (output == NULL) {
8144 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008145 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008146 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008147
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008148 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008149 /* try to encode it */
8150 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008151 if (charmaptranslate_output(input, i, mapping,
8152 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008153 Py_XDECREF(x);
8154 goto onError;
8155 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008156 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008157 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008158 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008159 else { /* untranslatable character */
8160 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8161 Py_ssize_t repsize;
8162 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008163 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008164 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008165 Py_ssize_t collstart = i;
8166 Py_ssize_t collend = i+1;
8167 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008168
Benjamin Peterson29060642009-01-31 22:14:21 +00008169 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008170 while (collend < size) {
8171 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008172 goto onError;
8173 Py_XDECREF(x);
8174 if (x!=Py_None)
8175 break;
8176 ++collend;
8177 }
8178 /* cache callback name lookup
8179 * (if not done yet, i.e. it's the first error) */
8180 if (known_errorHandler==-1) {
8181 if ((errors==NULL) || (!strcmp(errors, "strict")))
8182 known_errorHandler = 1;
8183 else if (!strcmp(errors, "replace"))
8184 known_errorHandler = 2;
8185 else if (!strcmp(errors, "ignore"))
8186 known_errorHandler = 3;
8187 else if (!strcmp(errors, "xmlcharrefreplace"))
8188 known_errorHandler = 4;
8189 else
8190 known_errorHandler = 0;
8191 }
8192 switch (known_errorHandler) {
8193 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008194 raise_translate_exception(&exc, input, collstart,
8195 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008196 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008197 case 2: /* replace */
8198 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008199 for (coll = collstart; coll<collend; coll++)
8200 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008201 /* fall through */
8202 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008203 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008204 break;
8205 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008206 /* generate replacement (temporarily (mis)uses i) */
8207 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008208 char buffer[2+29+1+1];
8209 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008210 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8211 if (charmaptranslate_makespace(&output, &osize,
8212 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008213 goto onError;
8214 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008215 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008216 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008217 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008218 break;
8219 default:
8220 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008221 reason, input, &exc,
8222 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008223 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008224 goto onError;
8225 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008226 repsize = PyUnicode_GET_LENGTH(repunicode);
8227 if (charmaptranslate_makespace(&output, &osize,
8228 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008229 Py_DECREF(repunicode);
8230 goto onError;
8231 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008232 for (uni2 = 0; repsize-->0; ++uni2)
8233 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8234 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008235 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008236 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008237 }
8238 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008239 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8240 if (!res)
8241 goto onError;
8242 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008243 Py_XDECREF(exc);
8244 Py_XDECREF(errorHandler);
8245 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008246
Benjamin Peterson29060642009-01-31 22:14:21 +00008247 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008248 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008249 Py_XDECREF(exc);
8250 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008251 return NULL;
8252}
8253
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008254/* Deprecated. Use PyUnicode_Translate instead. */
8255PyObject *
8256PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8257 Py_ssize_t size,
8258 PyObject *mapping,
8259 const char *errors)
8260{
8261 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8262 if (!unicode)
8263 return NULL;
8264 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8265}
8266
Alexander Belopolsky40018472011-02-26 01:02:56 +00008267PyObject *
8268PyUnicode_Translate(PyObject *str,
8269 PyObject *mapping,
8270 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008271{
8272 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008273
Guido van Rossumd57fd912000-03-10 22:53:23 +00008274 str = PyUnicode_FromObject(str);
8275 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008276 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008277 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008278 Py_DECREF(str);
8279 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008280
Benjamin Peterson29060642009-01-31 22:14:21 +00008281 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008282 Py_XDECREF(str);
8283 return NULL;
8284}
Tim Petersced69f82003-09-16 20:30:58 +00008285
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008286static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008287fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008288{
8289 /* No need to call PyUnicode_READY(self) because this function is only
8290 called as a callback from fixup() which does it already. */
8291 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8292 const int kind = PyUnicode_KIND(self);
8293 void *data = PyUnicode_DATA(self);
8294 Py_UCS4 maxchar = 0, ch, fixed;
8295 Py_ssize_t i;
8296
8297 for (i = 0; i < len; ++i) {
8298 ch = PyUnicode_READ(kind, data, i);
8299 fixed = 0;
8300 if (ch > 127) {
8301 if (Py_UNICODE_ISSPACE(ch))
8302 fixed = ' ';
8303 else {
8304 const int decimal = Py_UNICODE_TODECIMAL(ch);
8305 if (decimal >= 0)
8306 fixed = '0' + decimal;
8307 }
8308 if (fixed != 0) {
8309 if (fixed > maxchar)
8310 maxchar = fixed;
8311 PyUnicode_WRITE(kind, data, i, fixed);
8312 }
8313 else if (ch > maxchar)
8314 maxchar = ch;
8315 }
8316 else if (ch > maxchar)
8317 maxchar = ch;
8318 }
8319
8320 return maxchar;
8321}
8322
8323PyObject *
8324_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8325{
8326 if (!PyUnicode_Check(unicode)) {
8327 PyErr_BadInternalCall();
8328 return NULL;
8329 }
8330 if (PyUnicode_READY(unicode) == -1)
8331 return NULL;
8332 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8333 /* If the string is already ASCII, just return the same string */
8334 Py_INCREF(unicode);
8335 return unicode;
8336 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008337 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008338}
8339
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008340PyObject *
8341PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8342 Py_ssize_t length)
8343{
8344 PyObject *result;
8345 Py_UNICODE *p; /* write pointer into result */
8346 Py_ssize_t i;
8347 /* Copy to a new string */
8348 result = (PyObject *)_PyUnicode_New(length);
8349 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8350 if (result == NULL)
8351 return result;
8352 p = PyUnicode_AS_UNICODE(result);
8353 /* Iterate over code points */
8354 for (i = 0; i < length; i++) {
8355 Py_UNICODE ch =s[i];
8356 if (ch > 127) {
8357 int decimal = Py_UNICODE_TODECIMAL(ch);
8358 if (decimal >= 0)
8359 p[i] = '0' + decimal;
8360 }
8361 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008362#ifndef DONT_MAKE_RESULT_READY
8363 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008364 Py_DECREF(result);
8365 return NULL;
8366 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008367#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008368 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008369 return result;
8370}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008371/* --- Decimal Encoder ---------------------------------------------------- */
8372
Alexander Belopolsky40018472011-02-26 01:02:56 +00008373int
8374PyUnicode_EncodeDecimal(Py_UNICODE *s,
8375 Py_ssize_t length,
8376 char *output,
8377 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008378{
8379 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008380 PyObject *errorHandler = NULL;
8381 PyObject *exc = NULL;
8382 const char *encoding = "decimal";
8383 const char *reason = "invalid decimal Unicode string";
8384 /* the following variable is used for caching string comparisons
8385 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8386 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008387
8388 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008389 PyErr_BadArgument();
8390 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008391 }
8392
8393 p = s;
8394 end = s + length;
8395 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008396 register Py_UNICODE ch = *p;
8397 int decimal;
8398 PyObject *repunicode;
8399 Py_ssize_t repsize;
8400 Py_ssize_t newpos;
8401 Py_UNICODE *uni2;
8402 Py_UNICODE *collstart;
8403 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008404
Benjamin Peterson29060642009-01-31 22:14:21 +00008405 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008406 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008407 ++p;
8408 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008409 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008410 decimal = Py_UNICODE_TODECIMAL(ch);
8411 if (decimal >= 0) {
8412 *output++ = '0' + decimal;
8413 ++p;
8414 continue;
8415 }
8416 if (0 < ch && ch < 256) {
8417 *output++ = (char)ch;
8418 ++p;
8419 continue;
8420 }
8421 /* All other characters are considered unencodable */
8422 collstart = p;
8423 collend = p+1;
8424 while (collend < end) {
8425 if ((0 < *collend && *collend < 256) ||
8426 !Py_UNICODE_ISSPACE(*collend) ||
8427 Py_UNICODE_TODECIMAL(*collend))
8428 break;
8429 }
8430 /* cache callback name lookup
8431 * (if not done yet, i.e. it's the first error) */
8432 if (known_errorHandler==-1) {
8433 if ((errors==NULL) || (!strcmp(errors, "strict")))
8434 known_errorHandler = 1;
8435 else if (!strcmp(errors, "replace"))
8436 known_errorHandler = 2;
8437 else if (!strcmp(errors, "ignore"))
8438 known_errorHandler = 3;
8439 else if (!strcmp(errors, "xmlcharrefreplace"))
8440 known_errorHandler = 4;
8441 else
8442 known_errorHandler = 0;
8443 }
8444 switch (known_errorHandler) {
8445 case 1: /* strict */
8446 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
8447 goto onError;
8448 case 2: /* replace */
8449 for (p = collstart; p < collend; ++p)
8450 *output++ = '?';
8451 /* fall through */
8452 case 3: /* ignore */
8453 p = collend;
8454 break;
8455 case 4: /* xmlcharrefreplace */
8456 /* generate replacement (temporarily (mis)uses p) */
8457 for (p = collstart; p < collend; ++p)
8458 output += sprintf(output, "&#%d;", (int)*p);
8459 p = collend;
8460 break;
8461 default:
8462 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
8463 encoding, reason, s, length, &exc,
8464 collstart-s, collend-s, &newpos);
8465 if (repunicode == NULL)
8466 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008467 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008468 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008469 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8470 Py_DECREF(repunicode);
8471 goto onError;
8472 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008473 /* generate replacement */
8474 repsize = PyUnicode_GET_SIZE(repunicode);
8475 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
8476 Py_UNICODE ch = *uni2;
8477 if (Py_UNICODE_ISSPACE(ch))
8478 *output++ = ' ';
8479 else {
8480 decimal = Py_UNICODE_TODECIMAL(ch);
8481 if (decimal >= 0)
8482 *output++ = '0' + decimal;
8483 else if (0 < ch && ch < 256)
8484 *output++ = (char)ch;
8485 else {
8486 Py_DECREF(repunicode);
8487 raise_encode_exception(&exc, encoding,
8488 s, length, collstart-s, collend-s, reason);
8489 goto onError;
8490 }
8491 }
8492 }
8493 p = s + newpos;
8494 Py_DECREF(repunicode);
8495 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008496 }
8497 /* 0-terminate the output string */
8498 *output++ = '\0';
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 0;
8502
Benjamin Peterson29060642009-01-31 22:14:21 +00008503 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008504 Py_XDECREF(exc);
8505 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008506 return -1;
8507}
8508
Guido van Rossumd57fd912000-03-10 22:53:23 +00008509/* --- Helpers ------------------------------------------------------------ */
8510
Victor Stinnerc3cec782011-10-05 21:24:08 +02008511#include "stringlib/asciilib.h"
8512#include "stringlib/fastsearch.h"
8513#include "stringlib/partition.h"
8514#include "stringlib/split.h"
8515#include "stringlib/count.h"
8516#include "stringlib/find.h"
8517#include "stringlib/localeutil.h"
8518#include "stringlib/undef.h"
8519
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008520#include "stringlib/ucs1lib.h"
8521#include "stringlib/fastsearch.h"
8522#include "stringlib/partition.h"
8523#include "stringlib/split.h"
8524#include "stringlib/count.h"
8525#include "stringlib/find.h"
8526#include "stringlib/localeutil.h"
8527#include "stringlib/undef.h"
8528
8529#include "stringlib/ucs2lib.h"
8530#include "stringlib/fastsearch.h"
8531#include "stringlib/partition.h"
8532#include "stringlib/split.h"
8533#include "stringlib/count.h"
8534#include "stringlib/find.h"
8535#include "stringlib/localeutil.h"
8536#include "stringlib/undef.h"
8537
8538#include "stringlib/ucs4lib.h"
8539#include "stringlib/fastsearch.h"
8540#include "stringlib/partition.h"
8541#include "stringlib/split.h"
8542#include "stringlib/count.h"
8543#include "stringlib/find.h"
8544#include "stringlib/localeutil.h"
8545#include "stringlib/undef.h"
8546
8547static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008548any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008549 Py_ssize_t start,
8550 Py_ssize_t end)
8551{
8552 int kind1, kind2, kind;
8553 void *buf1, *buf2;
8554 Py_ssize_t len1, len2, result;
8555
8556 kind1 = PyUnicode_KIND(s1);
8557 kind2 = PyUnicode_KIND(s2);
8558 kind = kind1 > kind2 ? kind1 : kind2;
8559 buf1 = PyUnicode_DATA(s1);
8560 buf2 = PyUnicode_DATA(s2);
8561 if (kind1 != kind)
8562 buf1 = _PyUnicode_AsKind(s1, kind);
8563 if (!buf1)
8564 return -2;
8565 if (kind2 != kind)
8566 buf2 = _PyUnicode_AsKind(s2, kind);
8567 if (!buf2) {
8568 if (kind1 != kind) PyMem_Free(buf1);
8569 return -2;
8570 }
8571 len1 = PyUnicode_GET_LENGTH(s1);
8572 len2 = PyUnicode_GET_LENGTH(s2);
8573
Victor Stinner794d5672011-10-10 03:21:36 +02008574 if (direction > 0) {
8575 switch(kind) {
8576 case PyUnicode_1BYTE_KIND:
8577 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8578 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8579 else
8580 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8581 break;
8582 case PyUnicode_2BYTE_KIND:
8583 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8584 break;
8585 case PyUnicode_4BYTE_KIND:
8586 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8587 break;
8588 default:
8589 assert(0); result = -2;
8590 }
8591 }
8592 else {
8593 switch(kind) {
8594 case PyUnicode_1BYTE_KIND:
8595 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8596 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8597 else
8598 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8599 break;
8600 case PyUnicode_2BYTE_KIND:
8601 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8602 break;
8603 case PyUnicode_4BYTE_KIND:
8604 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8605 break;
8606 default:
8607 assert(0); result = -2;
8608 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008609 }
8610
8611 if (kind1 != kind)
8612 PyMem_Free(buf1);
8613 if (kind2 != kind)
8614 PyMem_Free(buf2);
8615
8616 return result;
8617}
8618
8619Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02008620_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008621 Py_ssize_t n_buffer,
8622 void *digits, Py_ssize_t n_digits,
8623 Py_ssize_t min_width,
8624 const char *grouping,
8625 const char *thousands_sep)
8626{
8627 switch(kind) {
8628 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008629 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
8630 return _PyUnicode_ascii_InsertThousandsGrouping(
8631 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
8632 min_width, grouping, thousands_sep);
8633 else
8634 return _PyUnicode_ucs1_InsertThousandsGrouping(
8635 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
8636 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008637 case PyUnicode_2BYTE_KIND:
8638 return _PyUnicode_ucs2_InsertThousandsGrouping(
8639 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
8640 min_width, grouping, thousands_sep);
8641 case PyUnicode_4BYTE_KIND:
8642 return _PyUnicode_ucs4_InsertThousandsGrouping(
8643 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
8644 min_width, grouping, thousands_sep);
8645 }
8646 assert(0);
8647 return -1;
8648}
8649
8650
Eric Smith8c663262007-08-25 02:26:07 +00008651#include "stringlib/unicodedefs.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00008652#include "stringlib/fastsearch.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008653
Thomas Wouters477c8d52006-05-27 19:21:47 +00008654#include "stringlib/count.h"
8655#include "stringlib/find.h"
Eric Smith5807c412008-05-11 21:00:57 +00008656
Thomas Wouters477c8d52006-05-27 19:21:47 +00008657/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008658#define ADJUST_INDICES(start, end, len) \
8659 if (end > len) \
8660 end = len; \
8661 else if (end < 0) { \
8662 end += len; \
8663 if (end < 0) \
8664 end = 0; \
8665 } \
8666 if (start < 0) { \
8667 start += len; \
8668 if (start < 0) \
8669 start = 0; \
8670 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008671
Alexander Belopolsky40018472011-02-26 01:02:56 +00008672Py_ssize_t
8673PyUnicode_Count(PyObject *str,
8674 PyObject *substr,
8675 Py_ssize_t start,
8676 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008677{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008678 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008679 PyUnicodeObject* str_obj;
8680 PyUnicodeObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008681 int kind1, kind2, kind;
8682 void *buf1 = NULL, *buf2 = NULL;
8683 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008684
Thomas Wouters477c8d52006-05-27 19:21:47 +00008685 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008686 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008687 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008688 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02008689 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008690 Py_DECREF(str_obj);
8691 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008692 }
Tim Petersced69f82003-09-16 20:30:58 +00008693
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008694 kind1 = PyUnicode_KIND(str_obj);
8695 kind2 = PyUnicode_KIND(sub_obj);
8696 kind = kind1 > kind2 ? kind1 : kind2;
8697 buf1 = PyUnicode_DATA(str_obj);
8698 if (kind1 != kind)
8699 buf1 = _PyUnicode_AsKind((PyObject*)str_obj, kind);
8700 if (!buf1)
8701 goto onError;
8702 buf2 = PyUnicode_DATA(sub_obj);
8703 if (kind2 != kind)
8704 buf2 = _PyUnicode_AsKind((PyObject*)sub_obj, kind);
8705 if (!buf2)
8706 goto onError;
8707 len1 = PyUnicode_GET_LENGTH(str_obj);
8708 len2 = PyUnicode_GET_LENGTH(sub_obj);
8709
8710 ADJUST_INDICES(start, end, len1);
8711 switch(kind) {
8712 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008713 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
8714 result = asciilib_count(
8715 ((Py_UCS1*)buf1) + start, end - start,
8716 buf2, len2, PY_SSIZE_T_MAX
8717 );
8718 else
8719 result = ucs1lib_count(
8720 ((Py_UCS1*)buf1) + start, end - start,
8721 buf2, len2, PY_SSIZE_T_MAX
8722 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008723 break;
8724 case PyUnicode_2BYTE_KIND:
8725 result = ucs2lib_count(
8726 ((Py_UCS2*)buf1) + start, end - start,
8727 buf2, len2, PY_SSIZE_T_MAX
8728 );
8729 break;
8730 case PyUnicode_4BYTE_KIND:
8731 result = ucs4lib_count(
8732 ((Py_UCS4*)buf1) + start, end - start,
8733 buf2, len2, PY_SSIZE_T_MAX
8734 );
8735 break;
8736 default:
8737 assert(0); result = 0;
8738 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008739
8740 Py_DECREF(sub_obj);
8741 Py_DECREF(str_obj);
8742
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008743 if (kind1 != kind)
8744 PyMem_Free(buf1);
8745 if (kind2 != kind)
8746 PyMem_Free(buf2);
8747
Guido van Rossumd57fd912000-03-10 22:53:23 +00008748 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008749 onError:
8750 Py_DECREF(sub_obj);
8751 Py_DECREF(str_obj);
8752 if (kind1 != kind && buf1)
8753 PyMem_Free(buf1);
8754 if (kind2 != kind && buf2)
8755 PyMem_Free(buf2);
8756 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008757}
8758
Alexander Belopolsky40018472011-02-26 01:02:56 +00008759Py_ssize_t
8760PyUnicode_Find(PyObject *str,
8761 PyObject *sub,
8762 Py_ssize_t start,
8763 Py_ssize_t end,
8764 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008765{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008766 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008767
Guido van Rossumd57fd912000-03-10 22:53:23 +00008768 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008769 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008770 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008771 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008772 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008773 Py_DECREF(str);
8774 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008775 }
Tim Petersced69f82003-09-16 20:30:58 +00008776
Victor Stinner794d5672011-10-10 03:21:36 +02008777 result = any_find_slice(direction,
8778 str, sub, start, end
8779 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00008780
Guido van Rossumd57fd912000-03-10 22:53:23 +00008781 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008782 Py_DECREF(sub);
8783
Guido van Rossumd57fd912000-03-10 22:53:23 +00008784 return result;
8785}
8786
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008787Py_ssize_t
8788PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
8789 Py_ssize_t start, Py_ssize_t end,
8790 int direction)
8791{
8792 char *result;
8793 int kind;
8794 if (PyUnicode_READY(str) == -1)
8795 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02008796 if (start < 0 || end < 0) {
8797 PyErr_SetString(PyExc_IndexError, "string index out of range");
8798 return -2;
8799 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008800 if (end > PyUnicode_GET_LENGTH(str))
8801 end = PyUnicode_GET_LENGTH(str);
8802 kind = PyUnicode_KIND(str);
8803 result = findchar(PyUnicode_1BYTE_DATA(str)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02008804 + kind*start,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008805 kind,
8806 end-start, ch, direction);
8807 if (!result)
8808 return -1;
8809 return (result-(char*)PyUnicode_DATA(str)) >> (kind-1);
8810}
8811
Alexander Belopolsky40018472011-02-26 01:02:56 +00008812static int
8813tailmatch(PyUnicodeObject *self,
8814 PyUnicodeObject *substring,
8815 Py_ssize_t start,
8816 Py_ssize_t end,
8817 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008818{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008819 int kind_self;
8820 int kind_sub;
8821 void *data_self;
8822 void *data_sub;
8823 Py_ssize_t offset;
8824 Py_ssize_t i;
8825 Py_ssize_t end_sub;
8826
8827 if (PyUnicode_READY(self) == -1 ||
8828 PyUnicode_READY(substring) == -1)
8829 return 0;
8830
8831 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008832 return 1;
8833
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008834 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
8835 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008836 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00008837 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008838
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008839 kind_self = PyUnicode_KIND(self);
8840 data_self = PyUnicode_DATA(self);
8841 kind_sub = PyUnicode_KIND(substring);
8842 data_sub = PyUnicode_DATA(substring);
8843 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
8844
8845 if (direction > 0)
8846 offset = end;
8847 else
8848 offset = start;
8849
8850 if (PyUnicode_READ(kind_self, data_self, offset) ==
8851 PyUnicode_READ(kind_sub, data_sub, 0) &&
8852 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
8853 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
8854 /* If both are of the same kind, memcmp is sufficient */
8855 if (kind_self == kind_sub) {
8856 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02008857 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008858 data_sub,
8859 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02008860 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008861 }
8862 /* otherwise we have to compare each character by first accesing it */
8863 else {
8864 /* We do not need to compare 0 and len(substring)-1 because
8865 the if statement above ensured already that they are equal
8866 when we end up here. */
8867 // TODO: honor direction and do a forward or backwards search
8868 for (i = 1; i < end_sub; ++i) {
8869 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
8870 PyUnicode_READ(kind_sub, data_sub, i))
8871 return 0;
8872 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008873 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008874 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008875 }
8876
8877 return 0;
8878}
8879
Alexander Belopolsky40018472011-02-26 01:02:56 +00008880Py_ssize_t
8881PyUnicode_Tailmatch(PyObject *str,
8882 PyObject *substr,
8883 Py_ssize_t start,
8884 Py_ssize_t end,
8885 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008886{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008887 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008888
Guido van Rossumd57fd912000-03-10 22:53:23 +00008889 str = PyUnicode_FromObject(str);
8890 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008891 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008892 substr = PyUnicode_FromObject(substr);
8893 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008894 Py_DECREF(str);
8895 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008896 }
Tim Petersced69f82003-09-16 20:30:58 +00008897
Guido van Rossumd57fd912000-03-10 22:53:23 +00008898 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00008899 (PyUnicodeObject *)substr,
8900 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008901 Py_DECREF(str);
8902 Py_DECREF(substr);
8903 return result;
8904}
8905
Guido van Rossumd57fd912000-03-10 22:53:23 +00008906/* Apply fixfct filter to the Unicode object self and return a
8907 reference to the modified object */
8908
Alexander Belopolsky40018472011-02-26 01:02:56 +00008909static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02008910fixup(PyObject *self,
8911 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008912{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008913 PyObject *u;
8914 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008915
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008916 if (PyUnicode_READY(self) == -1)
8917 return NULL;
8918 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
8919 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
8920 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008921 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008922 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00008923
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008924 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02008925 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00008926
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008927 /* fix functions return the new maximum character in a string,
8928 if the kind of the resulting unicode object does not change,
8929 everything is fine. Otherwise we need to change the string kind
8930 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02008931 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008932 if (maxchar_new == 0)
8933 /* do nothing, keep maxchar_new at 0 which means no changes. */;
8934 else if (maxchar_new <= 127)
8935 maxchar_new = 127;
8936 else if (maxchar_new <= 255)
8937 maxchar_new = 255;
8938 else if (maxchar_new <= 65535)
8939 maxchar_new = 65535;
8940 else
8941 maxchar_new = 1114111; /* 0x10ffff */
8942
8943 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008944 /* fixfct should return TRUE if it modified the buffer. If
8945 FALSE, return a reference to the original buffer instead
8946 (to save space, not time) */
8947 Py_INCREF(self);
8948 Py_DECREF(u);
8949 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008950 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008951 else if (maxchar_new == maxchar_old) {
8952 return u;
8953 }
8954 else {
8955 /* In case the maximum character changed, we need to
8956 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008957 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008958 if (v == NULL) {
8959 Py_DECREF(u);
8960 return NULL;
8961 }
8962 if (maxchar_new > maxchar_old) {
8963 /* If the maxchar increased so that the kind changed, not all
8964 characters are representable anymore and we need to fix the
8965 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02008966 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02008967 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008968 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
8969 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008970 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02008971 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008972 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008973
8974 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008975 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008976 return v;
8977 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008978}
8979
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008980static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008981fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008982{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008983 /* No need to call PyUnicode_READY(self) because this function is only
8984 called as a callback from fixup() which does it already. */
8985 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8986 const int kind = PyUnicode_KIND(self);
8987 void *data = PyUnicode_DATA(self);
8988 int touched = 0;
8989 Py_UCS4 maxchar = 0;
8990 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008991
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008992 for (i = 0; i < len; ++i) {
8993 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8994 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
8995 if (up != ch) {
8996 if (up > maxchar)
8997 maxchar = up;
8998 PyUnicode_WRITE(kind, data, i, up);
8999 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009000 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009001 else if (ch > maxchar)
9002 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009003 }
9004
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009005 if (touched)
9006 return maxchar;
9007 else
9008 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009009}
9010
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009011static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009012fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009013{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009014 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9015 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9016 const int kind = PyUnicode_KIND(self);
9017 void *data = PyUnicode_DATA(self);
9018 int touched = 0;
9019 Py_UCS4 maxchar = 0;
9020 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009021
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009022 for(i = 0; i < len; ++i) {
9023 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9024 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9025 if (lo != ch) {
9026 if (lo > maxchar)
9027 maxchar = lo;
9028 PyUnicode_WRITE(kind, data, i, lo);
9029 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009030 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009031 else if (ch > maxchar)
9032 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009033 }
9034
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009035 if (touched)
9036 return maxchar;
9037 else
9038 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009039}
9040
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009041static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009042fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009043{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009044 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9045 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9046 const int kind = PyUnicode_KIND(self);
9047 void *data = PyUnicode_DATA(self);
9048 int touched = 0;
9049 Py_UCS4 maxchar = 0;
9050 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009051
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009052 for(i = 0; i < len; ++i) {
9053 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9054 Py_UCS4 nu = 0;
9055
9056 if (Py_UNICODE_ISUPPER(ch))
9057 nu = Py_UNICODE_TOLOWER(ch);
9058 else if (Py_UNICODE_ISLOWER(ch))
9059 nu = Py_UNICODE_TOUPPER(ch);
9060
9061 if (nu != 0) {
9062 if (nu > maxchar)
9063 maxchar = nu;
9064 PyUnicode_WRITE(kind, data, i, nu);
9065 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009066 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009067 else if (ch > maxchar)
9068 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009069 }
9070
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009071 if (touched)
9072 return maxchar;
9073 else
9074 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009075}
9076
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009077static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009078fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009079{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009080 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9081 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9082 const int kind = PyUnicode_KIND(self);
9083 void *data = PyUnicode_DATA(self);
9084 int touched = 0;
9085 Py_UCS4 maxchar = 0;
9086 Py_ssize_t i = 0;
9087 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009088
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009089 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009090 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009091
9092 ch = PyUnicode_READ(kind, data, i);
9093 if (!Py_UNICODE_ISUPPER(ch)) {
9094 maxchar = Py_UNICODE_TOUPPER(ch);
9095 PyUnicode_WRITE(kind, data, i, maxchar);
9096 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009097 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009098 ++i;
9099 for(; i < len; ++i) {
9100 ch = PyUnicode_READ(kind, data, i);
9101 if (!Py_UNICODE_ISLOWER(ch)) {
9102 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9103 if (lo > maxchar)
9104 maxchar = lo;
9105 PyUnicode_WRITE(kind, data, i, lo);
9106 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009107 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009108 else if (ch > maxchar)
9109 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009110 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009111
9112 if (touched)
9113 return maxchar;
9114 else
9115 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009116}
9117
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009118static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009119fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009120{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009121 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9122 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9123 const int kind = PyUnicode_KIND(self);
9124 void *data = PyUnicode_DATA(self);
9125 Py_UCS4 maxchar = 0;
9126 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009127 int previous_is_cased;
9128
9129 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009130 if (len == 1) {
9131 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9132 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9133 if (ti != ch) {
9134 PyUnicode_WRITE(kind, data, i, ti);
9135 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009136 }
9137 else
9138 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009139 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009140 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009141 for(; i < len; ++i) {
9142 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9143 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009144
Benjamin Peterson29060642009-01-31 22:14:21 +00009145 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009146 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009147 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009148 nu = Py_UNICODE_TOTITLE(ch);
9149
9150 if (nu > maxchar)
9151 maxchar = nu;
9152 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009153
Benjamin Peterson29060642009-01-31 22:14:21 +00009154 if (Py_UNICODE_ISLOWER(ch) ||
9155 Py_UNICODE_ISUPPER(ch) ||
9156 Py_UNICODE_ISTITLE(ch))
9157 previous_is_cased = 1;
9158 else
9159 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009160 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009161 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009162}
9163
Tim Peters8ce9f162004-08-27 01:49:32 +00009164PyObject *
9165PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009166{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009167 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009168 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009169 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009170 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009171 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9172 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009173 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009174 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009175 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009176 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009177 int use_memcpy;
9178 unsigned char *res_data = NULL, *sep_data = NULL;
9179 PyObject *last_obj;
9180 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009181
Tim Peters05eba1f2004-08-27 21:32:02 +00009182 fseq = PySequence_Fast(seq, "");
9183 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009184 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009185 }
9186
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009187 /* NOTE: the following code can't call back into Python code,
9188 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009189 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009190
Tim Peters05eba1f2004-08-27 21:32:02 +00009191 seqlen = PySequence_Fast_GET_SIZE(fseq);
9192 /* If empty sequence, return u"". */
9193 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009194 Py_DECREF(fseq);
9195 Py_INCREF(unicode_empty);
9196 res = unicode_empty;
9197 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009198 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009199
Tim Peters05eba1f2004-08-27 21:32:02 +00009200 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009201 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009202 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009203 if (seqlen == 1) {
9204 if (PyUnicode_CheckExact(items[0])) {
9205 res = items[0];
9206 Py_INCREF(res);
9207 Py_DECREF(fseq);
9208 return res;
9209 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009210 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009211 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009212 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009213 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009214 /* Set up sep and seplen */
9215 if (separator == NULL) {
9216 /* fall back to a blank space separator */
9217 sep = PyUnicode_FromOrdinal(' ');
9218 if (!sep)
9219 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009220 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009221 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009222 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009223 else {
9224 if (!PyUnicode_Check(separator)) {
9225 PyErr_Format(PyExc_TypeError,
9226 "separator: expected str instance,"
9227 " %.80s found",
9228 Py_TYPE(separator)->tp_name);
9229 goto onError;
9230 }
9231 if (PyUnicode_READY(separator))
9232 goto onError;
9233 sep = separator;
9234 seplen = PyUnicode_GET_LENGTH(separator);
9235 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9236 /* inc refcount to keep this code path symmetric with the
9237 above case of a blank separator */
9238 Py_INCREF(sep);
9239 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009240 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009241 }
9242
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009243 /* There are at least two things to join, or else we have a subclass
9244 * of str in the sequence.
9245 * Do a pre-pass to figure out the total amount of space we'll
9246 * need (sz), and see whether all argument are strings.
9247 */
9248 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009249#ifdef Py_DEBUG
9250 use_memcpy = 0;
9251#else
9252 use_memcpy = 1;
9253#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009254 for (i = 0; i < seqlen; i++) {
9255 const Py_ssize_t old_sz = sz;
9256 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009257 if (!PyUnicode_Check(item)) {
9258 PyErr_Format(PyExc_TypeError,
9259 "sequence item %zd: expected str instance,"
9260 " %.80s found",
9261 i, Py_TYPE(item)->tp_name);
9262 goto onError;
9263 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009264 if (PyUnicode_READY(item) == -1)
9265 goto onError;
9266 sz += PyUnicode_GET_LENGTH(item);
9267 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009268 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009269 if (i != 0)
9270 sz += seplen;
9271 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9272 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009273 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009274 goto onError;
9275 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009276 if (use_memcpy && last_obj != NULL) {
9277 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9278 use_memcpy = 0;
9279 }
9280 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009281 }
Tim Petersced69f82003-09-16 20:30:58 +00009282
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009283 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009284 if (res == NULL)
9285 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009286
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009287 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009288#ifdef Py_DEBUG
9289 use_memcpy = 0;
9290#else
9291 if (use_memcpy) {
9292 res_data = PyUnicode_1BYTE_DATA(res);
9293 kind = PyUnicode_KIND(res);
9294 if (seplen != 0)
9295 sep_data = PyUnicode_1BYTE_DATA(sep);
9296 }
9297#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009298 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009299 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009300 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009301 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009302 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009303 if (use_memcpy) {
9304 Py_MEMCPY(res_data,
9305 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009306 kind * seplen);
9307 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009308 }
9309 else {
9310 copy_characters(res, res_offset, sep, 0, seplen);
9311 res_offset += seplen;
9312 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009313 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009314 itemlen = PyUnicode_GET_LENGTH(item);
9315 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009316 if (use_memcpy) {
9317 Py_MEMCPY(res_data,
9318 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009319 kind * itemlen);
9320 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009321 }
9322 else {
9323 copy_characters(res, res_offset, item, 0, itemlen);
9324 res_offset += itemlen;
9325 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009326 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009327 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009328 if (use_memcpy)
9329 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009330 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009331 else
9332 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009333
Tim Peters05eba1f2004-08-27 21:32:02 +00009334 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009335 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009336 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009337 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009338
Benjamin Peterson29060642009-01-31 22:14:21 +00009339 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009340 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009341 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009342 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009343 return NULL;
9344}
9345
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009346#define FILL(kind, data, value, start, length) \
9347 do { \
9348 Py_ssize_t i_ = 0; \
9349 assert(kind != PyUnicode_WCHAR_KIND); \
9350 switch ((kind)) { \
9351 case PyUnicode_1BYTE_KIND: { \
9352 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9353 memset(to_, (unsigned char)value, length); \
9354 break; \
9355 } \
9356 case PyUnicode_2BYTE_KIND: { \
9357 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9358 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9359 break; \
9360 } \
9361 default: { \
9362 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9363 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9364 break; \
9365 } \
9366 } \
9367 } while (0)
9368
Victor Stinner9310abb2011-10-05 00:59:23 +02009369static PyObject *
9370pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009371 Py_ssize_t left,
9372 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009373 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009374{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009375 PyObject *u;
9376 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009377 int kind;
9378 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009379
9380 if (left < 0)
9381 left = 0;
9382 if (right < 0)
9383 right = 0;
9384
Tim Peters7a29bd52001-09-12 03:03:31 +00009385 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009386 Py_INCREF(self);
9387 return self;
9388 }
9389
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009390 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9391 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009392 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9393 return NULL;
9394 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009395 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9396 if (fill > maxchar)
9397 maxchar = fill;
9398 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009399 if (!u)
9400 return NULL;
9401
9402 kind = PyUnicode_KIND(u);
9403 data = PyUnicode_DATA(u);
9404 if (left)
9405 FILL(kind, data, fill, 0, left);
9406 if (right)
9407 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009408 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009409 assert(_PyUnicode_CheckConsistency(u, 1));
9410 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009411}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009412#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009413
Alexander Belopolsky40018472011-02-26 01:02:56 +00009414PyObject *
9415PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009416{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009417 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009418
9419 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009420 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009421 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009422
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009423 switch(PyUnicode_KIND(string)) {
9424 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009425 if (PyUnicode_IS_ASCII(string))
9426 list = asciilib_splitlines(
9427 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9428 PyUnicode_GET_LENGTH(string), keepends);
9429 else
9430 list = ucs1lib_splitlines(
9431 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9432 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009433 break;
9434 case PyUnicode_2BYTE_KIND:
9435 list = ucs2lib_splitlines(
9436 (PyObject*) string, PyUnicode_2BYTE_DATA(string),
9437 PyUnicode_GET_LENGTH(string), keepends);
9438 break;
9439 case PyUnicode_4BYTE_KIND:
9440 list = ucs4lib_splitlines(
9441 (PyObject*) string, PyUnicode_4BYTE_DATA(string),
9442 PyUnicode_GET_LENGTH(string), keepends);
9443 break;
9444 default:
9445 assert(0);
9446 list = 0;
9447 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009448 Py_DECREF(string);
9449 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009450}
9451
Alexander Belopolsky40018472011-02-26 01:02:56 +00009452static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009453split(PyObject *self,
9454 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009455 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009456{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009457 int kind1, kind2, kind;
9458 void *buf1, *buf2;
9459 Py_ssize_t len1, len2;
9460 PyObject* out;
9461
Guido van Rossumd57fd912000-03-10 22:53:23 +00009462 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009463 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009464
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009465 if (PyUnicode_READY(self) == -1)
9466 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009467
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009468 if (substring == NULL)
9469 switch(PyUnicode_KIND(self)) {
9470 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009471 if (PyUnicode_IS_ASCII(self))
9472 return asciilib_split_whitespace(
9473 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9474 PyUnicode_GET_LENGTH(self), maxcount
9475 );
9476 else
9477 return ucs1lib_split_whitespace(
9478 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9479 PyUnicode_GET_LENGTH(self), maxcount
9480 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009481 case PyUnicode_2BYTE_KIND:
9482 return ucs2lib_split_whitespace(
9483 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9484 PyUnicode_GET_LENGTH(self), maxcount
9485 );
9486 case PyUnicode_4BYTE_KIND:
9487 return ucs4lib_split_whitespace(
9488 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
9489 PyUnicode_GET_LENGTH(self), maxcount
9490 );
9491 default:
9492 assert(0);
9493 return NULL;
9494 }
9495
9496 if (PyUnicode_READY(substring) == -1)
9497 return NULL;
9498
9499 kind1 = PyUnicode_KIND(self);
9500 kind2 = PyUnicode_KIND(substring);
9501 kind = kind1 > kind2 ? kind1 : kind2;
9502 buf1 = PyUnicode_DATA(self);
9503 buf2 = PyUnicode_DATA(substring);
9504 if (kind1 != kind)
9505 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9506 if (!buf1)
9507 return NULL;
9508 if (kind2 != kind)
9509 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9510 if (!buf2) {
9511 if (kind1 != kind) PyMem_Free(buf1);
9512 return NULL;
9513 }
9514 len1 = PyUnicode_GET_LENGTH(self);
9515 len2 = PyUnicode_GET_LENGTH(substring);
9516
9517 switch(kind) {
9518 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009519 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9520 out = asciilib_split(
9521 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9522 else
9523 out = ucs1lib_split(
9524 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009525 break;
9526 case PyUnicode_2BYTE_KIND:
9527 out = ucs2lib_split(
9528 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9529 break;
9530 case PyUnicode_4BYTE_KIND:
9531 out = ucs4lib_split(
9532 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9533 break;
9534 default:
9535 out = NULL;
9536 }
9537 if (kind1 != kind)
9538 PyMem_Free(buf1);
9539 if (kind2 != kind)
9540 PyMem_Free(buf2);
9541 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009542}
9543
Alexander Belopolsky40018472011-02-26 01:02:56 +00009544static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009545rsplit(PyObject *self,
9546 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009547 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009548{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009549 int kind1, kind2, kind;
9550 void *buf1, *buf2;
9551 Py_ssize_t len1, len2;
9552 PyObject* out;
9553
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009554 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009555 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009556
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009557 if (PyUnicode_READY(self) == -1)
9558 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009559
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009560 if (substring == NULL)
9561 switch(PyUnicode_KIND(self)) {
9562 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009563 if (PyUnicode_IS_ASCII(self))
9564 return asciilib_rsplit_whitespace(
9565 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9566 PyUnicode_GET_LENGTH(self), maxcount
9567 );
9568 else
9569 return ucs1lib_rsplit_whitespace(
9570 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9571 PyUnicode_GET_LENGTH(self), maxcount
9572 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009573 case PyUnicode_2BYTE_KIND:
9574 return ucs2lib_rsplit_whitespace(
9575 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9576 PyUnicode_GET_LENGTH(self), maxcount
9577 );
9578 case PyUnicode_4BYTE_KIND:
9579 return ucs4lib_rsplit_whitespace(
9580 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
9581 PyUnicode_GET_LENGTH(self), maxcount
9582 );
9583 default:
9584 assert(0);
9585 return NULL;
9586 }
9587
9588 if (PyUnicode_READY(substring) == -1)
9589 return NULL;
9590
9591 kind1 = PyUnicode_KIND(self);
9592 kind2 = PyUnicode_KIND(substring);
9593 kind = kind1 > kind2 ? kind1 : kind2;
9594 buf1 = PyUnicode_DATA(self);
9595 buf2 = PyUnicode_DATA(substring);
9596 if (kind1 != kind)
9597 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9598 if (!buf1)
9599 return NULL;
9600 if (kind2 != kind)
9601 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9602 if (!buf2) {
9603 if (kind1 != kind) PyMem_Free(buf1);
9604 return NULL;
9605 }
9606 len1 = PyUnicode_GET_LENGTH(self);
9607 len2 = PyUnicode_GET_LENGTH(substring);
9608
9609 switch(kind) {
9610 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009611 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9612 out = asciilib_rsplit(
9613 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9614 else
9615 out = ucs1lib_rsplit(
9616 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009617 break;
9618 case PyUnicode_2BYTE_KIND:
9619 out = ucs2lib_rsplit(
9620 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9621 break;
9622 case PyUnicode_4BYTE_KIND:
9623 out = ucs4lib_rsplit(
9624 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9625 break;
9626 default:
9627 out = NULL;
9628 }
9629 if (kind1 != kind)
9630 PyMem_Free(buf1);
9631 if (kind2 != kind)
9632 PyMem_Free(buf2);
9633 return out;
9634}
9635
9636static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009637anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9638 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009639{
9640 switch(kind) {
9641 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009642 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
9643 return asciilib_find(buf1, len1, buf2, len2, offset);
9644 else
9645 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009646 case PyUnicode_2BYTE_KIND:
9647 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9648 case PyUnicode_4BYTE_KIND:
9649 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9650 }
9651 assert(0);
9652 return -1;
9653}
9654
9655static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009656anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
9657 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009658{
9659 switch(kind) {
9660 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009661 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
9662 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
9663 else
9664 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009665 case PyUnicode_2BYTE_KIND:
9666 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
9667 case PyUnicode_4BYTE_KIND:
9668 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
9669 }
9670 assert(0);
9671 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009672}
9673
Alexander Belopolsky40018472011-02-26 01:02:56 +00009674static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009675replace(PyObject *self, PyObject *str1,
9676 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009677{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009678 PyObject *u;
9679 char *sbuf = PyUnicode_DATA(self);
9680 char *buf1 = PyUnicode_DATA(str1);
9681 char *buf2 = PyUnicode_DATA(str2);
9682 int srelease = 0, release1 = 0, release2 = 0;
9683 int skind = PyUnicode_KIND(self);
9684 int kind1 = PyUnicode_KIND(str1);
9685 int kind2 = PyUnicode_KIND(str2);
9686 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
9687 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
9688 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +02009689 int mayshrink;
9690 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009691
9692 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009693 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009694 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009695 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009696
Victor Stinner59de0ee2011-10-07 10:01:28 +02009697 if (str1 == str2)
9698 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009699 if (skind < kind1)
9700 /* substring too wide to be present */
9701 goto nothing;
9702
Victor Stinner49a0a212011-10-12 23:46:10 +02009703 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9704 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
9705 /* Replacing str1 with str2 may cause a maxchar reduction in the
9706 result string. */
9707 mayshrink = (maxchar_str2 < maxchar);
9708 maxchar = Py_MAX(maxchar, maxchar_str2);
9709
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009710 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +00009711 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009712 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009713 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009714 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009715 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009716 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +02009717 Py_UCS4 u1, u2;
9718 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009719 u1 = PyUnicode_READ_CHAR(str1, 0);
9720 if (!findchar(sbuf, PyUnicode_KIND(self),
9721 slen, u1, 1))
Thomas Wouters477c8d52006-05-27 19:21:47 +00009722 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009723 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009724 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009725 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009726 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009727 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009728 rkind = PyUnicode_KIND(u);
9729 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
9730 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009731 if (--maxcount < 0)
9732 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009733 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009734 }
Victor Stinner49a0a212011-10-12 23:46:10 +02009735 }
9736 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009737 int rkind = skind;
9738 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +02009739
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009740 if (kind1 < rkind) {
9741 /* widen substring */
9742 buf1 = _PyUnicode_AsKind(str1, rkind);
9743 if (!buf1) goto error;
9744 release1 = 1;
9745 }
Victor Stinnerc3cec782011-10-05 21:24:08 +02009746 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009747 if (i < 0)
9748 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009749 if (rkind > kind2) {
9750 /* widen replacement */
9751 buf2 = _PyUnicode_AsKind(str2, rkind);
9752 if (!buf2) goto error;
9753 release2 = 1;
9754 }
9755 else if (rkind < kind2) {
9756 /* widen self and buf1 */
9757 rkind = kind2;
9758 if (release1) PyMem_Free(buf1);
9759 sbuf = _PyUnicode_AsKind(self, rkind);
9760 if (!sbuf) goto error;
9761 srelease = 1;
9762 buf1 = _PyUnicode_AsKind(str1, rkind);
9763 if (!buf1) goto error;
9764 release1 = 1;
9765 }
Victor Stinner49a0a212011-10-12 23:46:10 +02009766 u = PyUnicode_New(slen, maxchar);
9767 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009768 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +02009769 assert(PyUnicode_KIND(u) == rkind);
9770 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +02009771
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009772 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009773 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009774 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009775 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009776 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009777 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009778
9779 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +02009780 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009781 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +02009782 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009783 if (i == -1)
9784 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009785 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009786 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009787 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009788 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009789 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009790 }
Victor Stinner49a0a212011-10-12 23:46:10 +02009791 }
9792 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009793 Py_ssize_t n, i, j, ires;
9794 Py_ssize_t product, new_size;
9795 int rkind = skind;
9796 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009797
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009798 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +02009799 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009800 buf1 = _PyUnicode_AsKind(str1, rkind);
9801 if (!buf1) goto error;
9802 release1 = 1;
9803 }
Victor Stinnerc3cec782011-10-05 21:24:08 +02009804 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009805 if (n == 0)
9806 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009807 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +02009808 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009809 buf2 = _PyUnicode_AsKind(str2, rkind);
9810 if (!buf2) goto error;
9811 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009812 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009813 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +02009814 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009815 rkind = kind2;
9816 sbuf = _PyUnicode_AsKind(self, rkind);
9817 if (!sbuf) goto error;
9818 srelease = 1;
9819 if (release1) PyMem_Free(buf1);
9820 buf1 = _PyUnicode_AsKind(str1, rkind);
9821 if (!buf1) goto error;
9822 release1 = 1;
9823 }
9824 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
9825 PyUnicode_GET_LENGTH(str1))); */
9826 product = n * (len2-len1);
9827 if ((product / (len2-len1)) != n) {
9828 PyErr_SetString(PyExc_OverflowError,
9829 "replace string is too long");
9830 goto error;
9831 }
9832 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +02009833 if (new_size == 0) {
9834 Py_INCREF(unicode_empty);
9835 u = unicode_empty;
9836 goto done;
9837 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009838 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
9839 PyErr_SetString(PyExc_OverflowError,
9840 "replace string is too long");
9841 goto error;
9842 }
Victor Stinner49a0a212011-10-12 23:46:10 +02009843 u = PyUnicode_New(new_size, maxchar);
9844 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009845 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +02009846 assert(PyUnicode_KIND(u) == rkind);
9847 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009848 ires = i = 0;
9849 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009850 while (n-- > 0) {
9851 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +02009852 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009853 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +02009854 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009855 if (j == -1)
9856 break;
9857 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009858 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009859 memcpy(res + rkind * ires,
9860 sbuf + rkind * i,
9861 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009862 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009863 }
9864 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009865 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009866 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009867 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009868 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009869 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009870 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009871 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009872 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009873 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +00009874 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009875 memcpy(res + rkind * ires,
9876 sbuf + rkind * i,
9877 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +02009878 }
9879 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009880 /* interleave */
9881 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009882 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009883 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009884 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009885 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009886 if (--n <= 0)
9887 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009888 memcpy(res + rkind * ires,
9889 sbuf + rkind * i,
9890 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009891 ires++;
9892 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009893 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009894 memcpy(res + rkind * ires,
9895 sbuf + rkind * i,
9896 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00009897 }
Victor Stinner49a0a212011-10-12 23:46:10 +02009898 }
9899
9900 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +02009901 unicode_adjust_maxchar(&u);
9902 if (u == NULL)
9903 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009904 }
Victor Stinner49a0a212011-10-12 23:46:10 +02009905
9906 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009907 if (srelease)
9908 PyMem_FREE(sbuf);
9909 if (release1)
9910 PyMem_FREE(buf1);
9911 if (release2)
9912 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009913 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009914 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009915
Benjamin Peterson29060642009-01-31 22:14:21 +00009916 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00009917 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009918 if (srelease)
9919 PyMem_FREE(sbuf);
9920 if (release1)
9921 PyMem_FREE(buf1);
9922 if (release2)
9923 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009924 if (PyUnicode_CheckExact(self)) {
9925 Py_INCREF(self);
9926 return (PyObject *) self;
9927 }
Victor Stinner034f6cf2011-09-30 02:26:44 +02009928 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009929 error:
9930 if (srelease && sbuf)
9931 PyMem_FREE(sbuf);
9932 if (release1 && buf1)
9933 PyMem_FREE(buf1);
9934 if (release2 && buf2)
9935 PyMem_FREE(buf2);
9936 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009937}
9938
9939/* --- Unicode Object Methods --------------------------------------------- */
9940
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009941PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009942 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009943\n\
9944Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009945characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009946
9947static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +02009948unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009949{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009950 return fixup(self, fixtitle);
9951}
9952
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009953PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009954 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009955\n\
9956Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +00009957have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009958
9959static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +02009960unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009961{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009962 return fixup(self, fixcapitalize);
9963}
9964
9965#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009966PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009967 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009968\n\
9969Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009970normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009971
9972static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009973unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009974{
9975 PyObject *list;
9976 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009977 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009978
Guido van Rossumd57fd912000-03-10 22:53:23 +00009979 /* Split into words */
9980 list = split(self, NULL, -1);
9981 if (!list)
9982 return NULL;
9983
9984 /* Capitalize each word */
9985 for (i = 0; i < PyList_GET_SIZE(list); i++) {
9986 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00009987 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009988 if (item == NULL)
9989 goto onError;
9990 Py_DECREF(PyList_GET_ITEM(list, i));
9991 PyList_SET_ITEM(list, i, item);
9992 }
9993
9994 /* Join the words to form a new string */
9995 item = PyUnicode_Join(NULL, list);
9996
Benjamin Peterson29060642009-01-31 22:14:21 +00009997 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009998 Py_DECREF(list);
9999 return (PyObject *)item;
10000}
10001#endif
10002
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010003/* Argument converter. Coerces to a single unicode character */
10004
10005static int
10006convert_uc(PyObject *obj, void *addr)
10007{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010008 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010009 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010010
Benjamin Peterson14339b62009-01-31 16:36:08 +000010011 uniobj = PyUnicode_FromObject(obj);
10012 if (uniobj == NULL) {
10013 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010014 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010015 return 0;
10016 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010017 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010018 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010019 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010020 Py_DECREF(uniobj);
10021 return 0;
10022 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010023 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010024 Py_DECREF(uniobj);
10025 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010026}
10027
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010028PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010029 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010030\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010031Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010032done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010033
10034static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010035unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010036{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010037 Py_ssize_t marg, left;
10038 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010039 Py_UCS4 fillchar = ' ';
10040
Victor Stinnere9a29352011-10-01 02:14:59 +020010041 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010042 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010043
Victor Stinnere9a29352011-10-01 02:14:59 +020010044 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010045 return NULL;
10046
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010047 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010048 Py_INCREF(self);
10049 return (PyObject*) self;
10050 }
10051
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010052 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010053 left = marg / 2 + (marg & width & 1);
10054
Victor Stinner9310abb2011-10-05 00:59:23 +020010055 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010056}
10057
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010058/* This function assumes that str1 and str2 are readied by the caller. */
10059
Marc-André Lemburge5034372000-08-08 08:04:29 +000010060static int
10061unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
10062{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010063 int kind1, kind2;
10064 void *data1, *data2;
10065 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010066
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010067 kind1 = PyUnicode_KIND(str1);
10068 kind2 = PyUnicode_KIND(str2);
10069 data1 = PyUnicode_DATA(str1);
10070 data2 = PyUnicode_DATA(str2);
10071 len1 = PyUnicode_GET_LENGTH(str1);
10072 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010073
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010074 for (i = 0; i < len1 && i < len2; ++i) {
10075 Py_UCS4 c1, c2;
10076 c1 = PyUnicode_READ(kind1, data1, i);
10077 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010078
10079 if (c1 != c2)
10080 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010081 }
10082
10083 return (len1 < len2) ? -1 : (len1 != len2);
10084}
10085
Alexander Belopolsky40018472011-02-26 01:02:56 +000010086int
10087PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010088{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010089 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10090 if (PyUnicode_READY(left) == -1 ||
10091 PyUnicode_READY(right) == -1)
10092 return -1;
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010093 return unicode_compare((PyUnicodeObject *)left,
10094 (PyUnicodeObject *)right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010095 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010096 PyErr_Format(PyExc_TypeError,
10097 "Can't compare %.100s and %.100s",
10098 left->ob_type->tp_name,
10099 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010100 return -1;
10101}
10102
Martin v. Löwis5b222132007-06-10 09:51:05 +000010103int
10104PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10105{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010106 Py_ssize_t i;
10107 int kind;
10108 void *data;
10109 Py_UCS4 chr;
10110
Victor Stinner910337b2011-10-03 03:20:16 +020010111 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010112 if (PyUnicode_READY(uni) == -1)
10113 return -1;
10114 kind = PyUnicode_KIND(uni);
10115 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010116 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010117 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10118 if (chr != str[i])
10119 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010120 /* This check keeps Python strings that end in '\0' from comparing equal
10121 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010122 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010123 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010124 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010125 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010126 return 0;
10127}
10128
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010129
Benjamin Peterson29060642009-01-31 22:14:21 +000010130#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010131 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010132
Alexander Belopolsky40018472011-02-26 01:02:56 +000010133PyObject *
10134PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010135{
10136 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010137
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010138 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10139 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010140 if (PyUnicode_READY(left) == -1 ||
10141 PyUnicode_READY(right) == -1)
10142 return NULL;
10143 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10144 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010145 if (op == Py_EQ) {
10146 Py_INCREF(Py_False);
10147 return Py_False;
10148 }
10149 if (op == Py_NE) {
10150 Py_INCREF(Py_True);
10151 return Py_True;
10152 }
10153 }
10154 if (left == right)
10155 result = 0;
10156 else
10157 result = unicode_compare((PyUnicodeObject *)left,
10158 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010159
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010160 /* Convert the return value to a Boolean */
10161 switch (op) {
10162 case Py_EQ:
10163 v = TEST_COND(result == 0);
10164 break;
10165 case Py_NE:
10166 v = TEST_COND(result != 0);
10167 break;
10168 case Py_LE:
10169 v = TEST_COND(result <= 0);
10170 break;
10171 case Py_GE:
10172 v = TEST_COND(result >= 0);
10173 break;
10174 case Py_LT:
10175 v = TEST_COND(result == -1);
10176 break;
10177 case Py_GT:
10178 v = TEST_COND(result == 1);
10179 break;
10180 default:
10181 PyErr_BadArgument();
10182 return NULL;
10183 }
10184 Py_INCREF(v);
10185 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010186 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010187
Brian Curtindfc80e32011-08-10 20:28:54 -050010188 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010189}
10190
Alexander Belopolsky40018472011-02-26 01:02:56 +000010191int
10192PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010193{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010194 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010195 int kind1, kind2, kind;
10196 void *buf1, *buf2;
10197 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010198 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010199
10200 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010201 sub = PyUnicode_FromObject(element);
10202 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010203 PyErr_Format(PyExc_TypeError,
10204 "'in <string>' requires string as left operand, not %s",
10205 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010206 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010207 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010208 if (PyUnicode_READY(sub) == -1)
10209 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010210
Thomas Wouters477c8d52006-05-27 19:21:47 +000010211 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010212 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010213 Py_DECREF(sub);
10214 return -1;
10215 }
10216
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010217 kind1 = PyUnicode_KIND(str);
10218 kind2 = PyUnicode_KIND(sub);
10219 kind = kind1 > kind2 ? kind1 : kind2;
10220 buf1 = PyUnicode_DATA(str);
10221 buf2 = PyUnicode_DATA(sub);
10222 if (kind1 != kind)
10223 buf1 = _PyUnicode_AsKind((PyObject*)str, kind);
10224 if (!buf1) {
10225 Py_DECREF(sub);
10226 return -1;
10227 }
10228 if (kind2 != kind)
10229 buf2 = _PyUnicode_AsKind((PyObject*)sub, kind);
10230 if (!buf2) {
10231 Py_DECREF(sub);
10232 if (kind1 != kind) PyMem_Free(buf1);
10233 return -1;
10234 }
10235 len1 = PyUnicode_GET_LENGTH(str);
10236 len2 = PyUnicode_GET_LENGTH(sub);
10237
10238 switch(kind) {
10239 case PyUnicode_1BYTE_KIND:
10240 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10241 break;
10242 case PyUnicode_2BYTE_KIND:
10243 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10244 break;
10245 case PyUnicode_4BYTE_KIND:
10246 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10247 break;
10248 default:
10249 result = -1;
10250 assert(0);
10251 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010252
10253 Py_DECREF(str);
10254 Py_DECREF(sub);
10255
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010256 if (kind1 != kind)
10257 PyMem_Free(buf1);
10258 if (kind2 != kind)
10259 PyMem_Free(buf2);
10260
Guido van Rossum403d68b2000-03-13 15:55:09 +000010261 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010262}
10263
Guido van Rossumd57fd912000-03-10 22:53:23 +000010264/* Concat to string or Unicode object giving a new Unicode object. */
10265
Alexander Belopolsky40018472011-02-26 01:02:56 +000010266PyObject *
10267PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010268{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010269 PyObject *u = NULL, *v = NULL, *w;
10270 Py_UCS4 maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010271
10272 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010273 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010274 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010275 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010276 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010277 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010278 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010279
10280 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010281 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010282 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010283 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010284 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010285 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010286 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010288 }
10289
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010290 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinnerff9e50f2011-09-28 22:17:19 +020010291 maxchar = Py_MAX(maxchar, PyUnicode_MAX_CHAR_VALUE(v));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010292
Guido van Rossumd57fd912000-03-10 22:53:23 +000010293 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010294 w = PyUnicode_New(
10295 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10296 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010297 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010298 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010299 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10300 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010301 Py_DECREF(u);
10302 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010303 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010304 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010305
Benjamin Peterson29060642009-01-31 22:14:21 +000010306 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010307 Py_XDECREF(u);
10308 Py_XDECREF(v);
10309 return NULL;
10310}
10311
Victor Stinnerb0923652011-10-04 01:17:31 +020010312static void
10313unicode_append_inplace(PyObject **p_left, PyObject *right)
10314{
10315 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010316
10317 assert(PyUnicode_IS_READY(*p_left));
10318 assert(PyUnicode_IS_READY(right));
10319
10320 left_len = PyUnicode_GET_LENGTH(*p_left);
10321 right_len = PyUnicode_GET_LENGTH(right);
10322 if (left_len > PY_SSIZE_T_MAX - right_len) {
10323 PyErr_SetString(PyExc_OverflowError,
10324 "strings are too large to concat");
10325 goto error;
10326 }
10327 new_len = left_len + right_len;
10328
10329 /* Now we own the last reference to 'left', so we can resize it
10330 * in-place.
10331 */
10332 if (unicode_resize(p_left, new_len) != 0) {
10333 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10334 * deallocated so it cannot be put back into
10335 * 'variable'. The MemoryError is raised when there
10336 * is no value in 'variable', which might (very
10337 * remotely) be a cause of incompatibilities.
10338 */
10339 goto error;
10340 }
10341 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010342 copy_characters(*p_left, left_len, right, 0, right_len);
10343 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010344 return;
10345
10346error:
10347 Py_DECREF(*p_left);
10348 *p_left = NULL;
10349}
10350
Walter Dörwald1ab83302007-05-18 17:15:44 +000010351void
Victor Stinner23e56682011-10-03 03:54:37 +020010352PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010353{
Victor Stinner23e56682011-10-03 03:54:37 +020010354 PyObject *left, *res;
10355
10356 if (p_left == NULL) {
10357 if (!PyErr_Occurred())
10358 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010359 return;
10360 }
Victor Stinner23e56682011-10-03 03:54:37 +020010361 left = *p_left;
10362 if (right == NULL || !PyUnicode_Check(left)) {
10363 if (!PyErr_Occurred())
10364 PyErr_BadInternalCall();
10365 goto error;
10366 }
10367
Victor Stinnere1335c72011-10-04 20:53:03 +020010368 if (PyUnicode_READY(left))
10369 goto error;
10370 if (PyUnicode_READY(right))
10371 goto error;
10372
Victor Stinner23e56682011-10-03 03:54:37 +020010373 if (PyUnicode_CheckExact(left) && left != unicode_empty
10374 && PyUnicode_CheckExact(right) && right != unicode_empty
10375 && unicode_resizable(left)
10376 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10377 || _PyUnicode_WSTR(left) != NULL))
10378 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010379 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10380 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010381 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010382 not so different than duplicating the string. */
10383 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010384 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010385 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010386 if (p_left != NULL)
10387 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010388 return;
10389 }
10390 }
10391
10392 res = PyUnicode_Concat(left, right);
10393 if (res == NULL)
10394 goto error;
10395 Py_DECREF(left);
10396 *p_left = res;
10397 return;
10398
10399error:
10400 Py_DECREF(*p_left);
10401 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010402}
10403
10404void
10405PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10406{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010407 PyUnicode_Append(pleft, right);
10408 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010409}
10410
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010411PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010412 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010413\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010414Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010415string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010416interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010417
10418static PyObject *
10419unicode_count(PyUnicodeObject *self, PyObject *args)
10420{
10421 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010422 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010423 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010424 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010425 int kind1, kind2, kind;
10426 void *buf1, *buf2;
10427 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010428
Jesus Ceaac451502011-04-20 17:09:23 +020010429 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10430 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010431 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010432
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010433 kind1 = PyUnicode_KIND(self);
10434 kind2 = PyUnicode_KIND(substring);
10435 kind = kind1 > kind2 ? kind1 : kind2;
10436 buf1 = PyUnicode_DATA(self);
10437 buf2 = PyUnicode_DATA(substring);
10438 if (kind1 != kind)
10439 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10440 if (!buf1) {
10441 Py_DECREF(substring);
10442 return NULL;
10443 }
10444 if (kind2 != kind)
10445 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10446 if (!buf2) {
10447 Py_DECREF(substring);
10448 if (kind1 != kind) PyMem_Free(buf1);
10449 return NULL;
10450 }
10451 len1 = PyUnicode_GET_LENGTH(self);
10452 len2 = PyUnicode_GET_LENGTH(substring);
10453
10454 ADJUST_INDICES(start, end, len1);
10455 switch(kind) {
10456 case PyUnicode_1BYTE_KIND:
10457 iresult = ucs1lib_count(
10458 ((Py_UCS1*)buf1) + start, end - start,
10459 buf2, len2, PY_SSIZE_T_MAX
10460 );
10461 break;
10462 case PyUnicode_2BYTE_KIND:
10463 iresult = ucs2lib_count(
10464 ((Py_UCS2*)buf1) + start, end - start,
10465 buf2, len2, PY_SSIZE_T_MAX
10466 );
10467 break;
10468 case PyUnicode_4BYTE_KIND:
10469 iresult = ucs4lib_count(
10470 ((Py_UCS4*)buf1) + start, end - start,
10471 buf2, len2, PY_SSIZE_T_MAX
10472 );
10473 break;
10474 default:
10475 assert(0); iresult = 0;
10476 }
10477
10478 result = PyLong_FromSsize_t(iresult);
10479
10480 if (kind1 != kind)
10481 PyMem_Free(buf1);
10482 if (kind2 != kind)
10483 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010484
10485 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010486
Guido van Rossumd57fd912000-03-10 22:53:23 +000010487 return result;
10488}
10489
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010490PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010491 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010492\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010493Encode S using the codec registered for encoding. Default encoding\n\
10494is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010495handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010496a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10497'xmlcharrefreplace' as well as any other name registered with\n\
10498codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010499
10500static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +000010501unicode_encode(PyUnicodeObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010502{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010503 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010504 char *encoding = NULL;
10505 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010506
Benjamin Peterson308d6372009-09-18 21:42:35 +000010507 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10508 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010509 return NULL;
Georg Brandl3b9406b2010-12-03 07:54:09 +000010510 return PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010511}
10512
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010513PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010514 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010515\n\
10516Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010517If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010518
10519static PyObject*
10520unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
10521{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010522 Py_ssize_t i, j, line_pos, src_len, incr;
10523 Py_UCS4 ch;
10524 PyObject *u;
10525 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010526 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010527 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010528 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010529
10530 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010531 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010532
Antoine Pitrou22425222011-10-04 19:10:51 +020010533 if (PyUnicode_READY(self) == -1)
10534 return NULL;
10535
Thomas Wouters7e474022000-07-16 12:04:32 +000010536 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010537 src_len = PyUnicode_GET_LENGTH(self);
10538 i = j = line_pos = 0;
10539 kind = PyUnicode_KIND(self);
10540 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010541 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010542 for (; i < src_len; i++) {
10543 ch = PyUnicode_READ(kind, src_data, i);
10544 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010545 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010546 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010547 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010548 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010549 goto overflow;
10550 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010551 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010552 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010553 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010554 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010555 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010556 goto overflow;
10557 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010558 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010559 if (ch == '\n' || ch == '\r')
10560 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010561 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010562 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020010563 if (!found && PyUnicode_CheckExact(self)) {
10564 Py_INCREF((PyObject *) self);
10565 return (PyObject *) self;
10566 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010567
Guido van Rossumd57fd912000-03-10 22:53:23 +000010568 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010569 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010570 if (!u)
10571 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010572 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010573
Antoine Pitroue71d5742011-10-04 15:55:09 +020010574 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010575
Antoine Pitroue71d5742011-10-04 15:55:09 +020010576 for (; i < src_len; i++) {
10577 ch = PyUnicode_READ(kind, src_data, i);
10578 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010579 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010580 incr = tabsize - (line_pos % tabsize);
10581 line_pos += incr;
10582 while (incr--) {
10583 PyUnicode_WRITE(kind, dest_data, j, ' ');
10584 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010585 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010586 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010587 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010588 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010589 line_pos++;
10590 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010591 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010592 if (ch == '\n' || ch == '\r')
10593 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010594 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010595 }
10596 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020010597#ifndef DONT_MAKE_RESULT_READY
10598 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010599 Py_DECREF(u);
10600 return NULL;
10601 }
Victor Stinner17efeed2011-10-04 20:05:46 +020010602#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010603 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010604 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010605
Antoine Pitroue71d5742011-10-04 15:55:09 +020010606 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010607 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10608 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010609}
10610
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010611PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010612 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010613\n\
10614Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010615such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010616arguments start and end are interpreted as in slice notation.\n\
10617\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010618Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010619
10620static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010621unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010622{
Jesus Ceaac451502011-04-20 17:09:23 +020010623 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010624 Py_ssize_t start;
10625 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010626 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010627
Jesus Ceaac451502011-04-20 17:09:23 +020010628 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10629 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010630 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010631
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010632 if (PyUnicode_READY(self) == -1)
10633 return NULL;
10634 if (PyUnicode_READY(substring) == -1)
10635 return NULL;
10636
Victor Stinner794d5672011-10-10 03:21:36 +020010637 result = any_find_slice(1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010638 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010639 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010640
10641 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010642
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010643 if (result == -2)
10644 return NULL;
10645
Christian Heimes217cfd12007-12-02 14:31:20 +000010646 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010647}
10648
10649static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010650unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010651{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010652 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
10653 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010654 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010655 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010656}
10657
Guido van Rossumc2504932007-09-18 19:42:40 +000010658/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010010659 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000010660static Py_hash_t
Neil Schemenauerf8c37d12007-09-07 20:49:04 +000010661unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010662{
Guido van Rossumc2504932007-09-18 19:42:40 +000010663 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010010664 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010665
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010666 if (_PyUnicode_HASH(self) != -1)
10667 return _PyUnicode_HASH(self);
10668 if (PyUnicode_READY(self) == -1)
10669 return -1;
10670 len = PyUnicode_GET_LENGTH(self);
10671
10672 /* The hash function as a macro, gets expanded three times below. */
10673#define HASH(P) \
10674 x = (Py_uhash_t)*P << 7; \
10675 while (--len >= 0) \
10676 x = (1000003*x) ^ (Py_uhash_t)*P++;
10677
10678 switch (PyUnicode_KIND(self)) {
10679 case PyUnicode_1BYTE_KIND: {
10680 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
10681 HASH(c);
10682 break;
10683 }
10684 case PyUnicode_2BYTE_KIND: {
10685 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
10686 HASH(s);
10687 break;
10688 }
10689 default: {
10690 Py_UCS4 *l;
10691 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
10692 "Impossible switch case in unicode_hash");
10693 l = PyUnicode_4BYTE_DATA(self);
10694 HASH(l);
10695 break;
10696 }
10697 }
10698 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
10699
Guido van Rossumc2504932007-09-18 19:42:40 +000010700 if (x == -1)
10701 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010702 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010703 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010704}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010705#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000010706
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010707PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010708 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010709\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010710Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010711
10712static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010713unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010714{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010715 Py_ssize_t result;
Jesus Ceaac451502011-04-20 17:09:23 +020010716 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010717 Py_ssize_t start;
10718 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010719
Jesus Ceaac451502011-04-20 17:09:23 +020010720 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
10721 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010722 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010723
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010724 if (PyUnicode_READY(self) == -1)
10725 return NULL;
10726 if (PyUnicode_READY(substring) == -1)
10727 return NULL;
10728
Victor Stinner794d5672011-10-10 03:21:36 +020010729 result = any_find_slice(1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010730 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010731 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010732
10733 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010734
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010735 if (result == -2)
10736 return NULL;
10737
Guido van Rossumd57fd912000-03-10 22:53:23 +000010738 if (result < 0) {
10739 PyErr_SetString(PyExc_ValueError, "substring not found");
10740 return NULL;
10741 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010742
Christian Heimes217cfd12007-12-02 14:31:20 +000010743 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010744}
10745
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010746PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010747 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010748\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010749Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010750at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010751
10752static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010753unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010754{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010755 Py_ssize_t i, length;
10756 int kind;
10757 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010758 int cased;
10759
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010760 if (PyUnicode_READY(self) == -1)
10761 return NULL;
10762 length = PyUnicode_GET_LENGTH(self);
10763 kind = PyUnicode_KIND(self);
10764 data = PyUnicode_DATA(self);
10765
Guido van Rossumd57fd912000-03-10 22:53:23 +000010766 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010767 if (length == 1)
10768 return PyBool_FromLong(
10769 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010770
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010771 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010772 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010773 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010774
Guido van Rossumd57fd912000-03-10 22:53:23 +000010775 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010776 for (i = 0; i < length; i++) {
10777 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010778
Benjamin Peterson29060642009-01-31 22:14:21 +000010779 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
10780 return PyBool_FromLong(0);
10781 else if (!cased && Py_UNICODE_ISLOWER(ch))
10782 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010783 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010784 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010785}
10786
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010787PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010788 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010789\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010790Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010791at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010792
10793static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010794unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010795{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010796 Py_ssize_t i, length;
10797 int kind;
10798 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010799 int cased;
10800
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010801 if (PyUnicode_READY(self) == -1)
10802 return NULL;
10803 length = PyUnicode_GET_LENGTH(self);
10804 kind = PyUnicode_KIND(self);
10805 data = PyUnicode_DATA(self);
10806
Guido van Rossumd57fd912000-03-10 22:53:23 +000010807 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010808 if (length == 1)
10809 return PyBool_FromLong(
10810 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010811
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010812 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010813 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010814 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010815
Guido van Rossumd57fd912000-03-10 22:53:23 +000010816 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010817 for (i = 0; i < length; i++) {
10818 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010819
Benjamin Peterson29060642009-01-31 22:14:21 +000010820 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
10821 return PyBool_FromLong(0);
10822 else if (!cased && Py_UNICODE_ISUPPER(ch))
10823 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010824 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010825 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010826}
10827
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010828PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010829 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010830\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010831Return True if S is a titlecased string and there is at least one\n\
10832character in S, i.e. upper- and titlecase characters may only\n\
10833follow uncased characters and lowercase characters only cased ones.\n\
10834Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010835
10836static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010837unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010838{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010839 Py_ssize_t i, length;
10840 int kind;
10841 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010842 int cased, previous_is_cased;
10843
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010844 if (PyUnicode_READY(self) == -1)
10845 return NULL;
10846 length = PyUnicode_GET_LENGTH(self);
10847 kind = PyUnicode_KIND(self);
10848 data = PyUnicode_DATA(self);
10849
Guido van Rossumd57fd912000-03-10 22:53:23 +000010850 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010851 if (length == 1) {
10852 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10853 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
10854 (Py_UNICODE_ISUPPER(ch) != 0));
10855 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010856
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010857 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010858 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010859 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010860
Guido van Rossumd57fd912000-03-10 22:53:23 +000010861 cased = 0;
10862 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010863 for (i = 0; i < length; i++) {
10864 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010865
Benjamin Peterson29060642009-01-31 22:14:21 +000010866 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
10867 if (previous_is_cased)
10868 return PyBool_FromLong(0);
10869 previous_is_cased = 1;
10870 cased = 1;
10871 }
10872 else if (Py_UNICODE_ISLOWER(ch)) {
10873 if (!previous_is_cased)
10874 return PyBool_FromLong(0);
10875 previous_is_cased = 1;
10876 cased = 1;
10877 }
10878 else
10879 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010880 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010881 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010882}
10883
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010884PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010885 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010886\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010887Return True if all characters in S are whitespace\n\
10888and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010889
10890static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010891unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010892{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010893 Py_ssize_t i, length;
10894 int kind;
10895 void *data;
10896
10897 if (PyUnicode_READY(self) == -1)
10898 return NULL;
10899 length = PyUnicode_GET_LENGTH(self);
10900 kind = PyUnicode_KIND(self);
10901 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010902
Guido van Rossumd57fd912000-03-10 22:53:23 +000010903 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010904 if (length == 1)
10905 return PyBool_FromLong(
10906 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010907
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010908 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010909 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010910 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010911
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010912 for (i = 0; i < length; i++) {
10913 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010914 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000010915 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010916 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010917 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010918}
10919
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010920PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010921 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010922\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010923Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010924and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010925
10926static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010927unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010928{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010929 Py_ssize_t i, length;
10930 int kind;
10931 void *data;
10932
10933 if (PyUnicode_READY(self) == -1)
10934 return NULL;
10935 length = PyUnicode_GET_LENGTH(self);
10936 kind = PyUnicode_KIND(self);
10937 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010938
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010939 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010940 if (length == 1)
10941 return PyBool_FromLong(
10942 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010943
10944 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010945 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010946 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010947
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010948 for (i = 0; i < length; i++) {
10949 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010950 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010951 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010952 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010953}
10954
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010955PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010956 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010957\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010958Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010959and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010960
10961static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010962unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010963{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010964 int kind;
10965 void *data;
10966 Py_ssize_t len, i;
10967
10968 if (PyUnicode_READY(self) == -1)
10969 return NULL;
10970
10971 kind = PyUnicode_KIND(self);
10972 data = PyUnicode_DATA(self);
10973 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010974
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010975 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010976 if (len == 1) {
10977 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10978 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
10979 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010980
10981 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010982 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010983 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010984
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010985 for (i = 0; i < len; i++) {
10986 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010987 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000010988 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010989 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010990 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010991}
10992
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010993PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010994 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010995\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010996Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010997False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010998
10999static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011000unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011001{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011002 Py_ssize_t i, length;
11003 int kind;
11004 void *data;
11005
11006 if (PyUnicode_READY(self) == -1)
11007 return NULL;
11008 length = PyUnicode_GET_LENGTH(self);
11009 kind = PyUnicode_KIND(self);
11010 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011011
Guido van Rossumd57fd912000-03-10 22:53:23 +000011012 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011013 if (length == 1)
11014 return PyBool_FromLong(
11015 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011016
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011017 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011018 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011019 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011020
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011021 for (i = 0; i < length; i++) {
11022 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011023 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011024 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011025 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011026}
11027
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011028PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011029 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011030\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011031Return True if all characters in S are digits\n\
11032and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011033
11034static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011035unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011036{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011037 Py_ssize_t i, length;
11038 int kind;
11039 void *data;
11040
11041 if (PyUnicode_READY(self) == -1)
11042 return NULL;
11043 length = PyUnicode_GET_LENGTH(self);
11044 kind = PyUnicode_KIND(self);
11045 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011046
Guido van Rossumd57fd912000-03-10 22:53:23 +000011047 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011048 if (length == 1) {
11049 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11050 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11051 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011052
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011053 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011054 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011055 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011056
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011057 for (i = 0; i < length; i++) {
11058 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011059 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011060 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011061 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011062}
11063
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011064PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011065 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011066\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011067Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011068False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011069
11070static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011071unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011072{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011073 Py_ssize_t i, length;
11074 int kind;
11075 void *data;
11076
11077 if (PyUnicode_READY(self) == -1)
11078 return NULL;
11079 length = PyUnicode_GET_LENGTH(self);
11080 kind = PyUnicode_KIND(self);
11081 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011082
Guido van Rossumd57fd912000-03-10 22:53:23 +000011083 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011084 if (length == 1)
11085 return PyBool_FromLong(
11086 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011087
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011088 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011089 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011090 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011091
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011092 for (i = 0; i < length; i++) {
11093 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011094 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011095 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011096 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011097}
11098
Martin v. Löwis47383402007-08-15 07:32:56 +000011099int
11100PyUnicode_IsIdentifier(PyObject *self)
11101{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011102 int kind;
11103 void *data;
11104 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011105 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011106
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011107 if (PyUnicode_READY(self) == -1) {
11108 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011109 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011110 }
11111
11112 /* Special case for empty strings */
11113 if (PyUnicode_GET_LENGTH(self) == 0)
11114 return 0;
11115 kind = PyUnicode_KIND(self);
11116 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011117
11118 /* PEP 3131 says that the first character must be in
11119 XID_Start and subsequent characters in XID_Continue,
11120 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011121 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011122 letters, digits, underscore). However, given the current
11123 definition of XID_Start and XID_Continue, it is sufficient
11124 to check just for these, except that _ must be allowed
11125 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011126 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011127 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011128 return 0;
11129
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011130 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011131 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011132 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011133 return 1;
11134}
11135
11136PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011137 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011138\n\
11139Return True if S is a valid identifier according\n\
11140to the language definition.");
11141
11142static PyObject*
11143unicode_isidentifier(PyObject *self)
11144{
11145 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11146}
11147
Georg Brandl559e5d72008-06-11 18:37:52 +000011148PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011149 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011150\n\
11151Return True if all characters in S are considered\n\
11152printable in repr() or S is empty, False otherwise.");
11153
11154static PyObject*
11155unicode_isprintable(PyObject *self)
11156{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011157 Py_ssize_t i, length;
11158 int kind;
11159 void *data;
11160
11161 if (PyUnicode_READY(self) == -1)
11162 return NULL;
11163 length = PyUnicode_GET_LENGTH(self);
11164 kind = PyUnicode_KIND(self);
11165 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011166
11167 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011168 if (length == 1)
11169 return PyBool_FromLong(
11170 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011171
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011172 for (i = 0; i < length; i++) {
11173 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011174 Py_RETURN_FALSE;
11175 }
11176 }
11177 Py_RETURN_TRUE;
11178}
11179
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011180PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011181 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011182\n\
11183Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011184iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011185
11186static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011187unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011188{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011189 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011190}
11191
Martin v. Löwis18e16552006-02-15 17:27:45 +000011192static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +000011193unicode_length(PyUnicodeObject *self)
11194{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011195 if (PyUnicode_READY(self) == -1)
11196 return -1;
11197 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011198}
11199
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011200PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011201 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011202\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011203Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011204done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011205
11206static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011207unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011208{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011209 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011210 Py_UCS4 fillchar = ' ';
11211
11212 if (PyUnicode_READY(self) == -1)
11213 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011214
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011215 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011216 return NULL;
11217
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011218 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011219 Py_INCREF(self);
11220 return (PyObject*) self;
11221 }
11222
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011223 return (PyObject*) pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011224}
11225
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011226PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011227 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011228\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011229Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011230
11231static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011232unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011233{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011234 return fixup(self, fixlower);
11235}
11236
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011237#define LEFTSTRIP 0
11238#define RIGHTSTRIP 1
11239#define BOTHSTRIP 2
11240
11241/* Arrays indexed by above */
11242static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11243
11244#define STRIPNAME(i) (stripformat[i]+3)
11245
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011246/* externally visible for str.strip(unicode) */
11247PyObject *
11248_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
11249{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011250 void *data;
11251 int kind;
11252 Py_ssize_t i, j, len;
11253 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011254
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011255 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11256 return NULL;
11257
11258 kind = PyUnicode_KIND(self);
11259 data = PyUnicode_DATA(self);
11260 len = PyUnicode_GET_LENGTH(self);
11261 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11262 PyUnicode_DATA(sepobj),
11263 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011264
Benjamin Peterson14339b62009-01-31 16:36:08 +000011265 i = 0;
11266 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011267 while (i < len &&
11268 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011269 i++;
11270 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011271 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011272
Benjamin Peterson14339b62009-01-31 16:36:08 +000011273 j = len;
11274 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011275 do {
11276 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011277 } while (j >= i &&
11278 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011279 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011280 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011281
Victor Stinner12bab6d2011-10-01 01:53:49 +020011282 return PyUnicode_Substring((PyObject*)self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011283}
11284
11285PyObject*
11286PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11287{
11288 unsigned char *data;
11289 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011290 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011291
Victor Stinnerde636f32011-10-01 03:55:54 +020011292 if (PyUnicode_READY(self) == -1)
11293 return NULL;
11294
11295 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11296
Victor Stinner12bab6d2011-10-01 01:53:49 +020011297 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011298 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011299 if (PyUnicode_CheckExact(self)) {
11300 Py_INCREF(self);
11301 return self;
11302 }
11303 else
11304 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011305 }
11306
Victor Stinner12bab6d2011-10-01 01:53:49 +020011307 length = end - start;
11308 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011309 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011310
Victor Stinnerde636f32011-10-01 03:55:54 +020011311 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011312 PyErr_SetString(PyExc_IndexError, "string index out of range");
11313 return NULL;
11314 }
11315
Victor Stinnerb9275c12011-10-05 14:01:42 +020011316 if (PyUnicode_IS_ASCII(self)) {
11317 kind = PyUnicode_KIND(self);
11318 data = PyUnicode_1BYTE_DATA(self);
11319 return unicode_fromascii(data + start, length);
11320 }
11321 else {
11322 kind = PyUnicode_KIND(self);
11323 data = PyUnicode_1BYTE_DATA(self);
11324 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011325 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011326 length);
11327 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011328}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011329
11330static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011331do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011332{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011333 int kind;
11334 void *data;
11335 Py_ssize_t len, i, j;
11336
11337 if (PyUnicode_READY(self) == -1)
11338 return NULL;
11339
11340 kind = PyUnicode_KIND(self);
11341 data = PyUnicode_DATA(self);
11342 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011343
Benjamin Peterson14339b62009-01-31 16:36:08 +000011344 i = 0;
11345 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011346 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011347 i++;
11348 }
11349 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011350
Benjamin Peterson14339b62009-01-31 16:36:08 +000011351 j = len;
11352 if (striptype != LEFTSTRIP) {
11353 do {
11354 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011355 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011356 j++;
11357 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011358
Victor Stinner12bab6d2011-10-01 01:53:49 +020011359 return PyUnicode_Substring((PyObject*)self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011360}
11361
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011362
11363static PyObject *
11364do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
11365{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011366 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011367
Benjamin Peterson14339b62009-01-31 16:36:08 +000011368 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11369 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011370
Benjamin Peterson14339b62009-01-31 16:36:08 +000011371 if (sep != NULL && sep != Py_None) {
11372 if (PyUnicode_Check(sep))
11373 return _PyUnicode_XStrip(self, striptype, sep);
11374 else {
11375 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011376 "%s arg must be None or str",
11377 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011378 return NULL;
11379 }
11380 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011381
Benjamin Peterson14339b62009-01-31 16:36:08 +000011382 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011383}
11384
11385
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011386PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011387 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011388\n\
11389Return a copy of the string S with leading and trailing\n\
11390whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011391If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011392
11393static PyObject *
11394unicode_strip(PyUnicodeObject *self, PyObject *args)
11395{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011396 if (PyTuple_GET_SIZE(args) == 0)
11397 return do_strip(self, BOTHSTRIP); /* Common case */
11398 else
11399 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011400}
11401
11402
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011403PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011404 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011405\n\
11406Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011407If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011408
11409static PyObject *
11410unicode_lstrip(PyUnicodeObject *self, PyObject *args)
11411{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011412 if (PyTuple_GET_SIZE(args) == 0)
11413 return do_strip(self, LEFTSTRIP); /* Common case */
11414 else
11415 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011416}
11417
11418
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011419PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011420 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011421\n\
11422Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011423If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011424
11425static PyObject *
11426unicode_rstrip(PyUnicodeObject *self, PyObject *args)
11427{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011428 if (PyTuple_GET_SIZE(args) == 0)
11429 return do_strip(self, RIGHTSTRIP); /* Common case */
11430 else
11431 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011432}
11433
11434
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +000011436unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437{
11438 PyUnicodeObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011439 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011440
Georg Brandl222de0f2009-04-12 12:01:50 +000011441 if (len < 1) {
11442 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011443 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011444 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011445
Tim Peters7a29bd52001-09-12 03:03:31 +000011446 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011447 /* no repeat, return original string */
11448 Py_INCREF(str);
11449 return (PyObject*) str;
11450 }
Tim Peters8f422462000-09-09 06:13:41 +000011451
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011452 if (PyUnicode_READY(str) == -1)
11453 return NULL;
11454
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011455 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011456 PyErr_SetString(PyExc_OverflowError,
11457 "repeated string is too long");
11458 return NULL;
11459 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011460 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011461
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011462 u = (PyUnicodeObject *)PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011463 if (!u)
11464 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011465 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011466
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011467 if (PyUnicode_GET_LENGTH(str) == 1) {
11468 const int kind = PyUnicode_KIND(str);
11469 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11470 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011471 if (kind == PyUnicode_1BYTE_KIND)
11472 memset(to, (unsigned char)fill_char, len);
11473 else {
11474 for (n = 0; n < len; ++n)
11475 PyUnicode_WRITE(kind, to, n, fill_char);
11476 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011477 }
11478 else {
11479 /* number of characters copied this far */
11480 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011481 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011482 char *to = (char *) PyUnicode_DATA(u);
11483 Py_MEMCPY(to, PyUnicode_DATA(str),
11484 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011485 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011486 n = (done <= nchars-done) ? done : nchars-done;
11487 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011488 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011489 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011490 }
11491
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011492 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011493 return (PyObject*) u;
11494}
11495
Alexander Belopolsky40018472011-02-26 01:02:56 +000011496PyObject *
11497PyUnicode_Replace(PyObject *obj,
11498 PyObject *subobj,
11499 PyObject *replobj,
11500 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011501{
11502 PyObject *self;
11503 PyObject *str1;
11504 PyObject *str2;
11505 PyObject *result;
11506
11507 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011508 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011509 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011511 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011512 Py_DECREF(self);
11513 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011514 }
11515 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011516 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011517 Py_DECREF(self);
11518 Py_DECREF(str1);
11519 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011521 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011522 Py_DECREF(self);
11523 Py_DECREF(str1);
11524 Py_DECREF(str2);
11525 return result;
11526}
11527
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011528PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011529 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011530\n\
11531Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011532old replaced by new. If the optional argument count is\n\
11533given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011534
11535static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011536unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011537{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011538 PyObject *str1;
11539 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011540 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011541 PyObject *result;
11542
Martin v. Löwis18e16552006-02-15 17:27:45 +000011543 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011544 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011545 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011546 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011547 str1 = PyUnicode_FromObject(str1);
11548 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11549 return NULL;
11550 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011551 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011552 Py_DECREF(str1);
11553 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011554 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555
11556 result = replace(self, str1, str2, maxcount);
11557
11558 Py_DECREF(str1);
11559 Py_DECREF(str2);
11560 return result;
11561}
11562
Alexander Belopolsky40018472011-02-26 01:02:56 +000011563static PyObject *
11564unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011565{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011566 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011567 Py_ssize_t isize;
11568 Py_ssize_t osize, squote, dquote, i, o;
11569 Py_UCS4 max, quote;
11570 int ikind, okind;
11571 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011572
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011573 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011574 return NULL;
11575
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011576 isize = PyUnicode_GET_LENGTH(unicode);
11577 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011578
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011579 /* Compute length of output, quote characters, and
11580 maximum character */
11581 osize = 2; /* quotes */
11582 max = 127;
11583 squote = dquote = 0;
11584 ikind = PyUnicode_KIND(unicode);
11585 for (i = 0; i < isize; i++) {
11586 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11587 switch (ch) {
11588 case '\'': squote++; osize++; break;
11589 case '"': dquote++; osize++; break;
11590 case '\\': case '\t': case '\r': case '\n':
11591 osize += 2; break;
11592 default:
11593 /* Fast-path ASCII */
11594 if (ch < ' ' || ch == 0x7f)
11595 osize += 4; /* \xHH */
11596 else if (ch < 0x7f)
11597 osize++;
11598 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11599 osize++;
11600 max = ch > max ? ch : max;
11601 }
11602 else if (ch < 0x100)
11603 osize += 4; /* \xHH */
11604 else if (ch < 0x10000)
11605 osize += 6; /* \uHHHH */
11606 else
11607 osize += 10; /* \uHHHHHHHH */
11608 }
11609 }
11610
11611 quote = '\'';
11612 if (squote) {
11613 if (dquote)
11614 /* Both squote and dquote present. Use squote,
11615 and escape them */
11616 osize += squote;
11617 else
11618 quote = '"';
11619 }
11620
11621 repr = PyUnicode_New(osize, max);
11622 if (repr == NULL)
11623 return NULL;
11624 okind = PyUnicode_KIND(repr);
11625 odata = PyUnicode_DATA(repr);
11626
11627 PyUnicode_WRITE(okind, odata, 0, quote);
11628 PyUnicode_WRITE(okind, odata, osize-1, quote);
11629
11630 for (i = 0, o = 1; i < isize; i++) {
11631 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011632
11633 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011634 if ((ch == quote) || (ch == '\\')) {
11635 PyUnicode_WRITE(okind, odata, o++, '\\');
11636 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011637 continue;
11638 }
11639
Benjamin Peterson29060642009-01-31 22:14:21 +000011640 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011641 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011642 PyUnicode_WRITE(okind, odata, o++, '\\');
11643 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011644 }
11645 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011646 PyUnicode_WRITE(okind, odata, o++, '\\');
11647 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011648 }
11649 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011650 PyUnicode_WRITE(okind, odata, o++, '\\');
11651 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011652 }
11653
11654 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011655 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011656 PyUnicode_WRITE(okind, odata, o++, '\\');
11657 PyUnicode_WRITE(okind, odata, o++, 'x');
11658 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
11659 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011660 }
11661
Georg Brandl559e5d72008-06-11 18:37:52 +000011662 /* Copy ASCII characters as-is */
11663 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011664 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011665 }
11666
Benjamin Peterson29060642009-01-31 22:14:21 +000011667 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000011668 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011669 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000011670 (categories Z* and C* except ASCII space)
11671 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011672 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011673 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011674 if (ch <= 0xff) {
11675 PyUnicode_WRITE(okind, odata, o++, '\\');
11676 PyUnicode_WRITE(okind, odata, o++, 'x');
11677 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
11678 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011679 }
11680 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011681 else if (ch >= 0x10000) {
11682 PyUnicode_WRITE(okind, odata, o++, '\\');
11683 PyUnicode_WRITE(okind, odata, o++, 'U');
11684 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 28) & 0xF]);
11685 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 24) & 0xF]);
11686 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 20) & 0xF]);
11687 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 16) & 0xF]);
11688 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
11689 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
11690 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
11691 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011692 }
11693 /* Map 16-bit characters to '\uxxxx' */
11694 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011695 PyUnicode_WRITE(okind, odata, o++, '\\');
11696 PyUnicode_WRITE(okind, odata, o++, 'u');
11697 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
11698 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
11699 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
11700 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011701 }
11702 }
11703 /* Copy characters as-is */
11704 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011705 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011706 }
11707 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000011708 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011709 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020011710 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000011711 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011712}
11713
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011714PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011715 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011716\n\
11717Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011718such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011719arguments start and end are interpreted as in slice notation.\n\
11720\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011721Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011722
11723static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011724unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011725{
Jesus Ceaac451502011-04-20 17:09:23 +020011726 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011727 Py_ssize_t start;
11728 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011729 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011730
Jesus Ceaac451502011-04-20 17:09:23 +020011731 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
11732 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000011733 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011734
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011735 if (PyUnicode_READY(self) == -1)
11736 return NULL;
11737 if (PyUnicode_READY(substring) == -1)
11738 return NULL;
11739
Victor Stinner794d5672011-10-10 03:21:36 +020011740 result = any_find_slice(-1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011741 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011742 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011743
11744 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011745
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011746 if (result == -2)
11747 return NULL;
11748
Christian Heimes217cfd12007-12-02 14:31:20 +000011749 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011750}
11751
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011752PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011753 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011754\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011755Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011756
11757static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011758unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011759{
Jesus Ceaac451502011-04-20 17:09:23 +020011760 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011761 Py_ssize_t start;
11762 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011763 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011764
Jesus Ceaac451502011-04-20 17:09:23 +020011765 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
11766 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000011767 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011768
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011769 if (PyUnicode_READY(self) == -1)
11770 return NULL;
11771 if (PyUnicode_READY(substring) == -1)
11772 return NULL;
11773
Victor Stinner794d5672011-10-10 03:21:36 +020011774 result = any_find_slice(-1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011775 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011776 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011777
11778 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011779
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011780 if (result == -2)
11781 return NULL;
11782
Guido van Rossumd57fd912000-03-10 22:53:23 +000011783 if (result < 0) {
11784 PyErr_SetString(PyExc_ValueError, "substring not found");
11785 return NULL;
11786 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011787
Christian Heimes217cfd12007-12-02 14:31:20 +000011788 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011789}
11790
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011791PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011792 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011793\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011794Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011795done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011796
11797static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011798unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011799{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011800 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011801 Py_UCS4 fillchar = ' ';
11802
Victor Stinnere9a29352011-10-01 02:14:59 +020011803 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011804 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011805
Victor Stinnere9a29352011-10-01 02:14:59 +020011806 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011807 return NULL;
11808
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011809 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011810 Py_INCREF(self);
11811 return (PyObject*) self;
11812 }
11813
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011814 return (PyObject*) pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011815}
11816
Alexander Belopolsky40018472011-02-26 01:02:56 +000011817PyObject *
11818PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011819{
11820 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000011821
Guido van Rossumd57fd912000-03-10 22:53:23 +000011822 s = PyUnicode_FromObject(s);
11823 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000011824 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000011825 if (sep != NULL) {
11826 sep = PyUnicode_FromObject(sep);
11827 if (sep == NULL) {
11828 Py_DECREF(s);
11829 return NULL;
11830 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011831 }
11832
Victor Stinner9310abb2011-10-05 00:59:23 +020011833 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011834
11835 Py_DECREF(s);
11836 Py_XDECREF(sep);
11837 return result;
11838}
11839
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011840PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011841 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011842\n\
11843Return a list of the words in S, using sep as the\n\
11844delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000011845splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000011846whitespace string is a separator and empty strings are\n\
11847removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011848
11849static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011850unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011851{
11852 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011853 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011854
Martin v. Löwis18e16552006-02-15 17:27:45 +000011855 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011856 return NULL;
11857
11858 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000011859 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011860 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020011861 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011862 else
Benjamin Peterson29060642009-01-31 22:14:21 +000011863 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011864}
11865
Thomas Wouters477c8d52006-05-27 19:21:47 +000011866PyObject *
11867PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
11868{
11869 PyObject* str_obj;
11870 PyObject* sep_obj;
11871 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011872 int kind1, kind2, kind;
11873 void *buf1 = NULL, *buf2 = NULL;
11874 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011875
11876 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020011877 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011878 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011879 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011880 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000011881 Py_DECREF(str_obj);
11882 return NULL;
11883 }
11884
Victor Stinner14f8f022011-10-05 20:58:25 +020011885 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011886 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020011887 kind = Py_MAX(kind1, kind2);
11888 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011889 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020011890 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011891 if (!buf1)
11892 goto onError;
11893 buf2 = PyUnicode_DATA(sep_obj);
11894 if (kind2 != kind)
11895 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11896 if (!buf2)
11897 goto onError;
11898 len1 = PyUnicode_GET_LENGTH(str_obj);
11899 len2 = PyUnicode_GET_LENGTH(sep_obj);
11900
Victor Stinner14f8f022011-10-05 20:58:25 +020011901 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011902 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020011903 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
11904 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11905 else
11906 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011907 break;
11908 case PyUnicode_2BYTE_KIND:
11909 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11910 break;
11911 case PyUnicode_4BYTE_KIND:
11912 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11913 break;
11914 default:
11915 assert(0);
11916 out = 0;
11917 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011918
11919 Py_DECREF(sep_obj);
11920 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011921 if (kind1 != kind)
11922 PyMem_Free(buf1);
11923 if (kind2 != kind)
11924 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011925
11926 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011927 onError:
11928 Py_DECREF(sep_obj);
11929 Py_DECREF(str_obj);
11930 if (kind1 != kind && buf1)
11931 PyMem_Free(buf1);
11932 if (kind2 != kind && buf2)
11933 PyMem_Free(buf2);
11934 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011935}
11936
11937
11938PyObject *
11939PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
11940{
11941 PyObject* str_obj;
11942 PyObject* sep_obj;
11943 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011944 int kind1, kind2, kind;
11945 void *buf1 = NULL, *buf2 = NULL;
11946 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011947
11948 str_obj = PyUnicode_FromObject(str_in);
11949 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000011950 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011951 sep_obj = PyUnicode_FromObject(sep_in);
11952 if (!sep_obj) {
11953 Py_DECREF(str_obj);
11954 return NULL;
11955 }
11956
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011957 kind1 = PyUnicode_KIND(str_in);
11958 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020011959 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011960 buf1 = PyUnicode_DATA(str_in);
11961 if (kind1 != kind)
11962 buf1 = _PyUnicode_AsKind(str_in, kind);
11963 if (!buf1)
11964 goto onError;
11965 buf2 = PyUnicode_DATA(sep_obj);
11966 if (kind2 != kind)
11967 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11968 if (!buf2)
11969 goto onError;
11970 len1 = PyUnicode_GET_LENGTH(str_obj);
11971 len2 = PyUnicode_GET_LENGTH(sep_obj);
11972
11973 switch(PyUnicode_KIND(str_in)) {
11974 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020011975 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
11976 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11977 else
11978 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011979 break;
11980 case PyUnicode_2BYTE_KIND:
11981 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11982 break;
11983 case PyUnicode_4BYTE_KIND:
11984 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11985 break;
11986 default:
11987 assert(0);
11988 out = 0;
11989 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011990
11991 Py_DECREF(sep_obj);
11992 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011993 if (kind1 != kind)
11994 PyMem_Free(buf1);
11995 if (kind2 != kind)
11996 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011997
11998 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011999 onError:
12000 Py_DECREF(sep_obj);
12001 Py_DECREF(str_obj);
12002 if (kind1 != kind && buf1)
12003 PyMem_Free(buf1);
12004 if (kind2 != kind && buf2)
12005 PyMem_Free(buf2);
12006 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012007}
12008
12009PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012010 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012011\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012012Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012013the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012014found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012015
12016static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012017unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012018{
Victor Stinner9310abb2011-10-05 00:59:23 +020012019 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012020}
12021
12022PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012023 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012024\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012025Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012026the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012027separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012028
12029static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012030unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012031{
Victor Stinner9310abb2011-10-05 00:59:23 +020012032 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012033}
12034
Alexander Belopolsky40018472011-02-26 01:02:56 +000012035PyObject *
12036PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012037{
12038 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012039
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012040 s = PyUnicode_FromObject(s);
12041 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012042 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012043 if (sep != NULL) {
12044 sep = PyUnicode_FromObject(sep);
12045 if (sep == NULL) {
12046 Py_DECREF(s);
12047 return NULL;
12048 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012049 }
12050
Victor Stinner9310abb2011-10-05 00:59:23 +020012051 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012052
12053 Py_DECREF(s);
12054 Py_XDECREF(sep);
12055 return result;
12056}
12057
12058PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012059 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012060\n\
12061Return a list of the words in S, using sep as the\n\
12062delimiter string, starting at the end of the string and\n\
12063working to the front. If maxsplit is given, at most maxsplit\n\
12064splits are done. If sep is not specified, any whitespace string\n\
12065is a separator.");
12066
12067static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012068unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012069{
12070 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012071 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012072
Martin v. Löwis18e16552006-02-15 17:27:45 +000012073 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012074 return NULL;
12075
12076 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012077 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012078 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012079 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012080 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012081 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012082}
12083
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012084PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012085 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012086\n\
12087Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012088Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012089is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012090
12091static PyObject*
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012092unicode_splitlines(PyUnicodeObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012093{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012094 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012095 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012096
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012097 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12098 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012099 return NULL;
12100
Guido van Rossum86662912000-04-11 15:38:46 +000012101 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012102}
12103
12104static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012105PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012106{
Walter Dörwald346737f2007-05-31 10:44:43 +000012107 if (PyUnicode_CheckExact(self)) {
12108 Py_INCREF(self);
12109 return self;
12110 } else
12111 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012112 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012113}
12114
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012115PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012116 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012117\n\
12118Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012119and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012120
12121static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012122unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012123{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012124 return fixup(self, fixswapcase);
12125}
12126
Georg Brandlceee0772007-11-27 23:48:05 +000012127PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012128 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012129\n\
12130Return a translation table usable for str.translate().\n\
12131If there is only one argument, it must be a dictionary mapping Unicode\n\
12132ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012133Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012134If there are two arguments, they must be strings of equal length, and\n\
12135in the resulting dictionary, each character in x will be mapped to the\n\
12136character at the same position in y. If there is a third argument, it\n\
12137must be a string, whose characters will be mapped to None in the result.");
12138
12139static PyObject*
12140unicode_maketrans(PyUnicodeObject *null, PyObject *args)
12141{
12142 PyObject *x, *y = NULL, *z = NULL;
12143 PyObject *new = NULL, *key, *value;
12144 Py_ssize_t i = 0;
12145 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012146
Georg Brandlceee0772007-11-27 23:48:05 +000012147 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12148 return NULL;
12149 new = PyDict_New();
12150 if (!new)
12151 return NULL;
12152 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012153 int x_kind, y_kind, z_kind;
12154 void *x_data, *y_data, *z_data;
12155
Georg Brandlceee0772007-11-27 23:48:05 +000012156 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012157 if (!PyUnicode_Check(x)) {
12158 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12159 "be a string if there is a second argument");
12160 goto err;
12161 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012162 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012163 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12164 "arguments must have equal length");
12165 goto err;
12166 }
12167 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012168 x_kind = PyUnicode_KIND(x);
12169 y_kind = PyUnicode_KIND(y);
12170 x_data = PyUnicode_DATA(x);
12171 y_data = PyUnicode_DATA(y);
12172 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12173 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12174 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012175 if (!key || !value)
12176 goto err;
12177 res = PyDict_SetItem(new, key, value);
12178 Py_DECREF(key);
12179 Py_DECREF(value);
12180 if (res < 0)
12181 goto err;
12182 }
12183 /* create entries for deleting chars in z */
12184 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012185 z_kind = PyUnicode_KIND(z);
12186 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012187 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012188 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012189 if (!key)
12190 goto err;
12191 res = PyDict_SetItem(new, key, Py_None);
12192 Py_DECREF(key);
12193 if (res < 0)
12194 goto err;
12195 }
12196 }
12197 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012198 int kind;
12199 void *data;
12200
Georg Brandlceee0772007-11-27 23:48:05 +000012201 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012202 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012203 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12204 "to maketrans it must be a dict");
12205 goto err;
12206 }
12207 /* copy entries into the new dict, converting string keys to int keys */
12208 while (PyDict_Next(x, &i, &key, &value)) {
12209 if (PyUnicode_Check(key)) {
12210 /* convert string keys to integer keys */
12211 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012212 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012213 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12214 "table must be of length 1");
12215 goto err;
12216 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012217 kind = PyUnicode_KIND(key);
12218 data = PyUnicode_DATA(key);
12219 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012220 if (!newkey)
12221 goto err;
12222 res = PyDict_SetItem(new, newkey, value);
12223 Py_DECREF(newkey);
12224 if (res < 0)
12225 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012226 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012227 /* just keep integer keys */
12228 if (PyDict_SetItem(new, key, value) < 0)
12229 goto err;
12230 } else {
12231 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12232 "be strings or integers");
12233 goto err;
12234 }
12235 }
12236 }
12237 return new;
12238 err:
12239 Py_DECREF(new);
12240 return NULL;
12241}
12242
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012243PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012244 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012245\n\
12246Return a copy of the string S, where all characters have been mapped\n\
12247through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012248Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012249Unmapped characters are left untouched. Characters mapped to None\n\
12250are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012251
12252static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012253unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012254{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012255 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012256}
12257
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012258PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012259 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012260\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012261Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012262
12263static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012264unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012265{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012266 return fixup(self, fixupper);
12267}
12268
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012269PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012270 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012271\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012272Pad a numeric string S with zeros on the left, to fill a field\n\
12273of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012274
12275static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012276unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012277{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012278 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012279 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012280 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012281 int kind;
12282 void *data;
12283 Py_UCS4 chr;
12284
12285 if (PyUnicode_READY(self) == -1)
12286 return NULL;
12287
Martin v. Löwis18e16552006-02-15 17:27:45 +000012288 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012289 return NULL;
12290
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012291 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012292 if (PyUnicode_CheckExact(self)) {
12293 Py_INCREF(self);
12294 return (PyObject*) self;
12295 }
12296 else
Victor Stinner2219e0a2011-10-01 01:16:59 +020012297 return PyUnicode_Copy((PyObject*)self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012298 }
12299
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012300 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012301
12302 u = pad(self, fill, 0, '0');
12303
Walter Dörwald068325e2002-04-15 13:36:47 +000012304 if (u == NULL)
12305 return NULL;
12306
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012307 kind = PyUnicode_KIND(u);
12308 data = PyUnicode_DATA(u);
12309 chr = PyUnicode_READ(kind, data, fill);
12310
12311 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012312 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012313 PyUnicode_WRITE(kind, data, 0, chr);
12314 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012315 }
12316
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012317 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012318 return (PyObject*) u;
12319}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012320
12321#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012322static PyObject *
12323unicode__decimal2ascii(PyObject *self)
12324{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012325 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012326}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012327#endif
12328
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012329PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012330 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012331\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012332Return True if S starts with the specified prefix, False otherwise.\n\
12333With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012334With optional end, stop comparing S at that position.\n\
12335prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012336
12337static PyObject *
12338unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012339 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012340{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012341 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012342 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012343 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012344 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012345 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012346
Jesus Ceaac451502011-04-20 17:09:23 +020012347 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012348 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012349 if (PyTuple_Check(subobj)) {
12350 Py_ssize_t i;
12351 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
12352 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012353 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012354 if (substring == NULL)
12355 return NULL;
12356 result = tailmatch(self, substring, start, end, -1);
12357 Py_DECREF(substring);
12358 if (result) {
12359 Py_RETURN_TRUE;
12360 }
12361 }
12362 /* nothing matched */
12363 Py_RETURN_FALSE;
12364 }
12365 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012366 if (substring == NULL) {
12367 if (PyErr_ExceptionMatches(PyExc_TypeError))
12368 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12369 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012370 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012371 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012372 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012373 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012374 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012375}
12376
12377
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012378PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012379 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012380\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012381Return True if S ends with the specified suffix, False otherwise.\n\
12382With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012383With optional end, stop comparing S at that position.\n\
12384suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012385
12386static PyObject *
12387unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012388 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012389{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012390 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012391 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012392 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012393 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012394 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012395
Jesus Ceaac451502011-04-20 17:09:23 +020012396 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012397 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012398 if (PyTuple_Check(subobj)) {
12399 Py_ssize_t i;
12400 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
12401 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012402 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012403 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012404 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012405 result = tailmatch(self, substring, start, end, +1);
12406 Py_DECREF(substring);
12407 if (result) {
12408 Py_RETURN_TRUE;
12409 }
12410 }
12411 Py_RETURN_FALSE;
12412 }
12413 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012414 if (substring == NULL) {
12415 if (PyErr_ExceptionMatches(PyExc_TypeError))
12416 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12417 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012418 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012419 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012420 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012421 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012422 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012423}
12424
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012425#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012426
12427PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012428 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012429\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012430Return a formatted version of S, using substitutions from args and kwargs.\n\
12431The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012432
Eric Smith27bbca62010-11-04 17:06:58 +000012433PyDoc_STRVAR(format_map__doc__,
12434 "S.format_map(mapping) -> str\n\
12435\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012436Return a formatted version of S, using substitutions from mapping.\n\
12437The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012438
Eric Smith4a7d76d2008-05-30 18:10:19 +000012439static PyObject *
12440unicode__format__(PyObject* self, PyObject* args)
12441{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012442 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012443
12444 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12445 return NULL;
12446
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012447 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012448 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012449 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012450}
12451
Eric Smith8c663262007-08-25 02:26:07 +000012452PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012453 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012454\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012455Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012456
12457static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012458unicode__sizeof__(PyUnicodeObject *v)
12459{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012460 Py_ssize_t size;
12461
12462 /* If it's a compact object, account for base structure +
12463 character data. */
12464 if (PyUnicode_IS_COMPACT_ASCII(v))
12465 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12466 else if (PyUnicode_IS_COMPACT(v))
12467 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012468 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012469 else {
12470 /* If it is a two-block object, account for base object, and
12471 for character block if present. */
12472 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012473 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012474 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012475 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012476 }
12477 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012478 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012479 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012480 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012481 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012482 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012483
12484 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012485}
12486
12487PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012488 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012489
12490static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012491unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012492{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012493 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012494 if (!copy)
12495 return NULL;
12496 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012497}
12498
Guido van Rossumd57fd912000-03-10 22:53:23 +000012499static PyMethodDef unicode_methods[] = {
12500
12501 /* Order is according to common usage: often used methods should
12502 appear first, since lookup is done sequentially. */
12503
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012504 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012505 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12506 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012507 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012508 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12509 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12510 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12511 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12512 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12513 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12514 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012515 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012516 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12517 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12518 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012519 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012520 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12521 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12522 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012523 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012524 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012525 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012526 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012527 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12528 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12529 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12530 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12531 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12532 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12533 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12534 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12535 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12536 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12537 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12538 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12539 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12540 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012541 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012542 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012543 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012544 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012545 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012546 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012547 {"maketrans", (PyCFunction) unicode_maketrans,
12548 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012549 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012550#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012551 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012552#endif
12553
12554#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012555 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012556 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012557#endif
12558
Benjamin Peterson14339b62009-01-31 16:36:08 +000012559 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012560 {NULL, NULL}
12561};
12562
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012563static PyObject *
12564unicode_mod(PyObject *v, PyObject *w)
12565{
Brian Curtindfc80e32011-08-10 20:28:54 -050012566 if (!PyUnicode_Check(v))
12567 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012568 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012569}
12570
12571static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012572 0, /*nb_add*/
12573 0, /*nb_subtract*/
12574 0, /*nb_multiply*/
12575 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012576};
12577
Guido van Rossumd57fd912000-03-10 22:53:23 +000012578static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012579 (lenfunc) unicode_length, /* sq_length */
12580 PyUnicode_Concat, /* sq_concat */
12581 (ssizeargfunc) unicode_repeat, /* sq_repeat */
12582 (ssizeargfunc) unicode_getitem, /* sq_item */
12583 0, /* sq_slice */
12584 0, /* sq_ass_item */
12585 0, /* sq_ass_slice */
12586 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012587};
12588
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012589static PyObject*
12590unicode_subscript(PyUnicodeObject* self, PyObject* item)
12591{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012592 if (PyUnicode_READY(self) == -1)
12593 return NULL;
12594
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000012595 if (PyIndex_Check(item)) {
12596 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012597 if (i == -1 && PyErr_Occurred())
12598 return NULL;
12599 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012600 i += PyUnicode_GET_LENGTH(self);
Victor Stinner2fe5ced2011-10-02 00:25:40 +020012601 return unicode_getitem((PyObject*)self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012602 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000012603 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012604 PyObject *result;
12605 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012606 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012607 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012608
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012609 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000012610 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012611 return NULL;
12612 }
12613
12614 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012615 return PyUnicode_New(0, 0);
12616 } else if (start == 0 && step == 1 &&
12617 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000012618 PyUnicode_CheckExact(self)) {
12619 Py_INCREF(self);
12620 return (PyObject *)self;
12621 } else if (step == 1) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012622 return PyUnicode_Substring((PyObject*)self,
12623 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012624 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012625 /* General case */
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012626 max_char = 0;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012627 src_kind = PyUnicode_KIND(self);
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012628 kind_limit = kind_maxchar_limit(src_kind);
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012629 src_data = PyUnicode_DATA(self);
12630 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
12631 ch = PyUnicode_READ(src_kind, src_data, cur);
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012632 if (ch > max_char) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012633 max_char = ch;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012634 if (max_char >= kind_limit)
12635 break;
12636 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012637 }
12638 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012639 if (result == NULL)
12640 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012641 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012642 dest_data = PyUnicode_DATA(result);
12643
12644 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012645 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
12646 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012647 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012648 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012649 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012650 } else {
12651 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
12652 return NULL;
12653 }
12654}
12655
12656static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012657 (lenfunc)unicode_length, /* mp_length */
12658 (binaryfunc)unicode_subscript, /* mp_subscript */
12659 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012660};
12661
Guido van Rossumd57fd912000-03-10 22:53:23 +000012662
Guido van Rossumd57fd912000-03-10 22:53:23 +000012663/* Helpers for PyUnicode_Format() */
12664
12665static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000012666getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012667{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012668 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012669 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012670 (*p_argidx)++;
12671 if (arglen < 0)
12672 return args;
12673 else
12674 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012675 }
12676 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012677 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012678 return NULL;
12679}
12680
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012681/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012682
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012683static PyObject *
12684formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012685{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012686 char *p;
12687 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012688 double x;
Tim Petersced69f82003-09-16 20:30:58 +000012689
Guido van Rossumd57fd912000-03-10 22:53:23 +000012690 x = PyFloat_AsDouble(v);
12691 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012692 return NULL;
12693
Guido van Rossumd57fd912000-03-10 22:53:23 +000012694 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012695 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000012696
Eric Smith0923d1d2009-04-16 20:16:10 +000012697 p = PyOS_double_to_string(x, type, prec,
12698 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012699 if (p == NULL)
12700 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012701 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000012702 PyMem_Free(p);
12703 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012704}
12705
Tim Peters38fd5b62000-09-21 05:43:11 +000012706static PyObject*
12707formatlong(PyObject *val, int flags, int prec, int type)
12708{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012709 char *buf;
12710 int len;
12711 PyObject *str; /* temporary string object. */
12712 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000012713
Benjamin Peterson14339b62009-01-31 16:36:08 +000012714 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
12715 if (!str)
12716 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012717 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012718 Py_DECREF(str);
12719 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000012720}
12721
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012722static Py_UCS4
12723formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012724{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000012725 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012726 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012727 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012728 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000012729 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012730 goto onError;
12731 }
12732 else {
12733 /* Integer input truncated to a character */
12734 long x;
12735 x = PyLong_AsLong(v);
12736 if (x == -1 && PyErr_Occurred())
12737 goto onError;
12738
12739 if (x < 0 || x > 0x10ffff) {
12740 PyErr_SetString(PyExc_OverflowError,
12741 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012742 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000012743 }
12744
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012745 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012746 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000012747
Benjamin Peterson29060642009-01-31 22:14:21 +000012748 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012749 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012750 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012751 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012752}
12753
Antoine Pitrou978b9d22011-10-07 12:35:48 +020012754static int
12755repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
12756{
12757 int r;
12758 assert(count > 0);
12759 assert(PyUnicode_Check(obj));
12760 if (count > 5) {
12761 PyObject *repeated = unicode_repeat((PyUnicodeObject *) obj, count);
12762 if (repeated == NULL)
12763 return -1;
12764 r = _PyAccu_Accumulate(acc, repeated);
12765 Py_DECREF(repeated);
12766 return r;
12767 }
12768 else {
12769 do {
12770 if (_PyAccu_Accumulate(acc, obj))
12771 return -1;
12772 } while (--count);
12773 return 0;
12774 }
12775}
12776
Alexander Belopolsky40018472011-02-26 01:02:56 +000012777PyObject *
12778PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012779{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012780 void *fmt;
12781 int fmtkind;
12782 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012783 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012784 int r;
12785 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012786 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012787 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012788 PyObject *temp = NULL;
12789 PyObject *second = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012790 PyUnicodeObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012791 _PyAccu acc;
12792 static PyObject *plus, *minus, *blank, *zero, *percent;
12793
12794 if (!plus && !(plus = get_latin1_char('+')))
12795 return NULL;
12796 if (!minus && !(minus = get_latin1_char('-')))
12797 return NULL;
12798 if (!blank && !(blank = get_latin1_char(' ')))
12799 return NULL;
12800 if (!zero && !(zero = get_latin1_char('0')))
12801 return NULL;
12802 if (!percent && !(percent = get_latin1_char('%')))
12803 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000012804
Guido van Rossumd57fd912000-03-10 22:53:23 +000012805 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012806 PyErr_BadInternalCall();
12807 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012808 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012809 uformat = (PyUnicodeObject*)PyUnicode_FromObject(format);
12810 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012811 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012812 if (_PyAccu_Init(&acc))
12813 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012814 fmt = PyUnicode_DATA(uformat);
12815 fmtkind = PyUnicode_KIND(uformat);
12816 fmtcnt = PyUnicode_GET_LENGTH(uformat);
12817 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012818
Guido van Rossumd57fd912000-03-10 22:53:23 +000012819 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012820 arglen = PyTuple_Size(args);
12821 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012822 }
12823 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012824 arglen = -1;
12825 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012826 }
Christian Heimes90aa7642007-12-19 02:45:37 +000012827 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000012828 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000012829 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012830
12831 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012832 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012833 PyObject *nonfmt;
12834 Py_ssize_t nonfmtpos;
12835 nonfmtpos = fmtpos++;
12836 while (fmtcnt >= 0 &&
12837 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
12838 fmtpos++;
12839 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012840 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012841 nonfmt = PyUnicode_Substring((PyObject *) uformat, nonfmtpos, fmtpos);
12842 if (nonfmt == NULL)
12843 goto onError;
12844 r = _PyAccu_Accumulate(&acc, nonfmt);
12845 Py_DECREF(nonfmt);
12846 if (r)
12847 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012848 }
12849 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012850 /* Got a format specifier */
12851 int flags = 0;
12852 Py_ssize_t width = -1;
12853 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012854 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012855 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000012856 int isnumok;
12857 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012858 void *pbuf = NULL;
12859 Py_ssize_t pindex, len;
12860 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012861
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012862 fmtpos++;
12863 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
12864 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000012865 Py_ssize_t keylen;
12866 PyObject *key;
12867 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000012868
Benjamin Peterson29060642009-01-31 22:14:21 +000012869 if (dict == NULL) {
12870 PyErr_SetString(PyExc_TypeError,
12871 "format requires a mapping");
12872 goto onError;
12873 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012874 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000012875 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012876 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000012877 /* Skip over balanced parentheses */
12878 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012879 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000012880 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012881 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000012882 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012883 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000012884 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012885 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000012886 if (fmtcnt < 0 || pcount > 0) {
12887 PyErr_SetString(PyExc_ValueError,
12888 "incomplete format key");
12889 goto onError;
12890 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020012891 key = PyUnicode_Substring((PyObject*)uformat,
12892 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000012893 if (key == NULL)
12894 goto onError;
12895 if (args_owned) {
12896 Py_DECREF(args);
12897 args_owned = 0;
12898 }
12899 args = PyObject_GetItem(dict, key);
12900 Py_DECREF(key);
12901 if (args == NULL) {
12902 goto onError;
12903 }
12904 args_owned = 1;
12905 arglen = -1;
12906 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012907 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012908 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012909 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012910 case '-': flags |= F_LJUST; continue;
12911 case '+': flags |= F_SIGN; continue;
12912 case ' ': flags |= F_BLANK; continue;
12913 case '#': flags |= F_ALT; continue;
12914 case '0': flags |= F_ZERO; continue;
12915 }
12916 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012917 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012918 if (c == '*') {
12919 v = getnextarg(args, arglen, &argidx);
12920 if (v == NULL)
12921 goto onError;
12922 if (!PyLong_Check(v)) {
12923 PyErr_SetString(PyExc_TypeError,
12924 "* wants int");
12925 goto onError;
12926 }
12927 width = PyLong_AsLong(v);
12928 if (width == -1 && PyErr_Occurred())
12929 goto onError;
12930 if (width < 0) {
12931 flags |= F_LJUST;
12932 width = -width;
12933 }
12934 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012935 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012936 }
12937 else if (c >= '0' && c <= '9') {
12938 width = c - '0';
12939 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012940 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012941 if (c < '0' || c > '9')
12942 break;
12943 if ((width*10) / 10 != width) {
12944 PyErr_SetString(PyExc_ValueError,
12945 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000012946 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000012947 }
12948 width = width*10 + (c - '0');
12949 }
12950 }
12951 if (c == '.') {
12952 prec = 0;
12953 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012954 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012955 if (c == '*') {
12956 v = getnextarg(args, arglen, &argidx);
12957 if (v == NULL)
12958 goto onError;
12959 if (!PyLong_Check(v)) {
12960 PyErr_SetString(PyExc_TypeError,
12961 "* wants int");
12962 goto onError;
12963 }
12964 prec = PyLong_AsLong(v);
12965 if (prec == -1 && PyErr_Occurred())
12966 goto onError;
12967 if (prec < 0)
12968 prec = 0;
12969 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012970 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012971 }
12972 else if (c >= '0' && c <= '9') {
12973 prec = c - '0';
12974 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012975 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012976 if (c < '0' || c > '9')
12977 break;
12978 if ((prec*10) / 10 != prec) {
12979 PyErr_SetString(PyExc_ValueError,
12980 "prec too big");
12981 goto onError;
12982 }
12983 prec = prec*10 + (c - '0');
12984 }
12985 }
12986 } /* prec */
12987 if (fmtcnt >= 0) {
12988 if (c == 'h' || c == 'l' || c == 'L') {
12989 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012990 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012991 }
12992 }
12993 if (fmtcnt < 0) {
12994 PyErr_SetString(PyExc_ValueError,
12995 "incomplete format");
12996 goto onError;
12997 }
12998 if (c != '%') {
12999 v = getnextarg(args, arglen, &argidx);
13000 if (v == NULL)
13001 goto onError;
13002 }
13003 sign = 0;
13004 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013005 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013006 switch (c) {
13007
13008 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013009 _PyAccu_Accumulate(&acc, percent);
13010 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013011
13012 case 's':
13013 case 'r':
13014 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013015 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013016 temp = v;
13017 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013018 }
13019 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013020 if (c == 's')
13021 temp = PyObject_Str(v);
13022 else if (c == 'r')
13023 temp = PyObject_Repr(v);
13024 else
13025 temp = PyObject_ASCII(v);
13026 if (temp == NULL)
13027 goto onError;
13028 if (PyUnicode_Check(temp))
13029 /* nothing to do */;
13030 else {
13031 Py_DECREF(temp);
13032 PyErr_SetString(PyExc_TypeError,
13033 "%s argument has non-string str()");
13034 goto onError;
13035 }
13036 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013037 if (PyUnicode_READY(temp) == -1) {
13038 Py_CLEAR(temp);
13039 goto onError;
13040 }
13041 pbuf = PyUnicode_DATA(temp);
13042 kind = PyUnicode_KIND(temp);
13043 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013044 if (prec >= 0 && len > prec)
13045 len = prec;
13046 break;
13047
13048 case 'i':
13049 case 'd':
13050 case 'u':
13051 case 'o':
13052 case 'x':
13053 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013054 isnumok = 0;
13055 if (PyNumber_Check(v)) {
13056 PyObject *iobj=NULL;
13057
13058 if (PyLong_Check(v)) {
13059 iobj = v;
13060 Py_INCREF(iobj);
13061 }
13062 else {
13063 iobj = PyNumber_Long(v);
13064 }
13065 if (iobj!=NULL) {
13066 if (PyLong_Check(iobj)) {
13067 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013068 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013069 Py_DECREF(iobj);
13070 if (!temp)
13071 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013072 if (PyUnicode_READY(temp) == -1) {
13073 Py_CLEAR(temp);
13074 goto onError;
13075 }
13076 pbuf = PyUnicode_DATA(temp);
13077 kind = PyUnicode_KIND(temp);
13078 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013079 sign = 1;
13080 }
13081 else {
13082 Py_DECREF(iobj);
13083 }
13084 }
13085 }
13086 if (!isnumok) {
13087 PyErr_Format(PyExc_TypeError,
13088 "%%%c format: a number is required, "
13089 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13090 goto onError;
13091 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013092 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013093 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013094 fillobj = zero;
13095 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013096 break;
13097
13098 case 'e':
13099 case 'E':
13100 case 'f':
13101 case 'F':
13102 case 'g':
13103 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013104 temp = formatfloat(v, flags, prec, c);
13105 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013106 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013107 if (PyUnicode_READY(temp) == -1) {
13108 Py_CLEAR(temp);
13109 goto onError;
13110 }
13111 pbuf = PyUnicode_DATA(temp);
13112 kind = PyUnicode_KIND(temp);
13113 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013114 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013115 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013116 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013117 fillobj = zero;
13118 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013119 break;
13120
13121 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013122 {
13123 Py_UCS4 ch = formatchar(v);
13124 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013125 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013126 temp = _PyUnicode_FromUCS4(&ch, 1);
13127 if (temp == NULL)
13128 goto onError;
13129 pbuf = PyUnicode_DATA(temp);
13130 kind = PyUnicode_KIND(temp);
13131 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013132 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013133 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013134
13135 default:
13136 PyErr_Format(PyExc_ValueError,
13137 "unsupported format character '%c' (0x%x) "
13138 "at index %zd",
13139 (31<=c && c<=126) ? (char)c : '?',
13140 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013141 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013142 goto onError;
13143 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013144 /* pbuf is initialized here. */
13145 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013146 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013147 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13148 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013149 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013150 pindex++;
13151 }
13152 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13153 signobj = plus;
13154 len--;
13155 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013156 }
13157 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013158 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013159 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013160 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013161 else
13162 sign = 0;
13163 }
13164 if (width < len)
13165 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013166 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013167 if (fill != ' ') {
13168 assert(signobj != NULL);
13169 if (_PyAccu_Accumulate(&acc, signobj))
13170 goto onError;
13171 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013172 if (width > len)
13173 width--;
13174 }
13175 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013176 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013177 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013178 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013179 second = get_latin1_char(
13180 PyUnicode_READ(kind, pbuf, pindex + 1));
13181 pindex += 2;
13182 if (second == NULL ||
13183 _PyAccu_Accumulate(&acc, zero) ||
13184 _PyAccu_Accumulate(&acc, second))
13185 goto onError;
13186 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013187 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013188 width -= 2;
13189 if (width < 0)
13190 width = 0;
13191 len -= 2;
13192 }
13193 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013194 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013195 if (repeat_accumulate(&acc, fillobj, width - len))
13196 goto onError;
13197 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013198 }
13199 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013200 if (sign) {
13201 assert(signobj != NULL);
13202 if (_PyAccu_Accumulate(&acc, signobj))
13203 goto onError;
13204 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013205 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013206 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13207 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013208 second = get_latin1_char(
13209 PyUnicode_READ(kind, pbuf, pindex + 1));
13210 pindex += 2;
13211 if (second == NULL ||
13212 _PyAccu_Accumulate(&acc, zero) ||
13213 _PyAccu_Accumulate(&acc, second))
13214 goto onError;
13215 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013216 }
13217 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013218 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013219 if (temp != NULL) {
13220 assert(pbuf == PyUnicode_DATA(temp));
13221 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013222 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013223 else {
13224 const char *p = (const char *) pbuf;
13225 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013226 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013227 v = PyUnicode_FromKindAndData(kind, p, len);
13228 }
13229 if (v == NULL)
13230 goto onError;
13231 r = _PyAccu_Accumulate(&acc, v);
13232 Py_DECREF(v);
13233 if (r)
13234 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013235 if (width > len && repeat_accumulate(&acc, blank, width - len))
13236 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013237 if (dict && (argidx < arglen) && c != '%') {
13238 PyErr_SetString(PyExc_TypeError,
13239 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013240 goto onError;
13241 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013242 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013243 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013244 } /* until end */
13245 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013246 PyErr_SetString(PyExc_TypeError,
13247 "not all arguments converted during string formatting");
13248 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013249 }
13250
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013251 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013252 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013253 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013254 }
13255 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013256 Py_XDECREF(temp);
13257 Py_XDECREF(second);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013258 return (PyObject *)result;
13259
Benjamin Peterson29060642009-01-31 22:14:21 +000013260 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013261 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013262 Py_XDECREF(temp);
13263 Py_XDECREF(second);
13264 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013265 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013266 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013267 }
13268 return NULL;
13269}
13270
Jeremy Hylton938ace62002-07-17 16:30:39 +000013271static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013272unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13273
Tim Peters6d6c1a32001-08-02 04:15:00 +000013274static PyObject *
13275unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13276{
Benjamin Peterson29060642009-01-31 22:14:21 +000013277 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013278 static char *kwlist[] = {"object", "encoding", "errors", 0};
13279 char *encoding = NULL;
13280 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013281
Benjamin Peterson14339b62009-01-31 16:36:08 +000013282 if (type != &PyUnicode_Type)
13283 return unicode_subtype_new(type, args, kwds);
13284 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013285 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013286 return NULL;
13287 if (x == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013288 return (PyObject *)PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013289 if (encoding == NULL && errors == NULL)
13290 return PyObject_Str(x);
13291 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013292 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013293}
13294
Guido van Rossume023fe02001-08-30 03:12:59 +000013295static PyObject *
13296unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13297{
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013298 PyUnicodeObject *unicode, *self;
13299 Py_ssize_t length, char_size;
13300 int share_wstr, share_utf8;
13301 unsigned int kind;
13302 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013303
Benjamin Peterson14339b62009-01-31 16:36:08 +000013304 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013305
13306 unicode = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
13307 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013308 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013309 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013310 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013311 return NULL;
13312
13313 self = (PyUnicodeObject *) type->tp_alloc(type, 0);
13314 if (self == NULL) {
13315 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013316 return NULL;
13317 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013318 kind = PyUnicode_KIND(unicode);
13319 length = PyUnicode_GET_LENGTH(unicode);
13320
13321 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013322#ifdef Py_DEBUG
13323 _PyUnicode_HASH(self) = -1;
13324#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013325 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013326#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013327 _PyUnicode_STATE(self).interned = 0;
13328 _PyUnicode_STATE(self).kind = kind;
13329 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013330 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013331 _PyUnicode_STATE(self).ready = 1;
13332 _PyUnicode_WSTR(self) = NULL;
13333 _PyUnicode_UTF8_LENGTH(self) = 0;
13334 _PyUnicode_UTF8(self) = NULL;
13335 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013336 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013337
13338 share_utf8 = 0;
13339 share_wstr = 0;
13340 if (kind == PyUnicode_1BYTE_KIND) {
13341 char_size = 1;
13342 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13343 share_utf8 = 1;
13344 }
13345 else if (kind == PyUnicode_2BYTE_KIND) {
13346 char_size = 2;
13347 if (sizeof(wchar_t) == 2)
13348 share_wstr = 1;
13349 }
13350 else {
13351 assert(kind == PyUnicode_4BYTE_KIND);
13352 char_size = 4;
13353 if (sizeof(wchar_t) == 4)
13354 share_wstr = 1;
13355 }
13356
13357 /* Ensure we won't overflow the length. */
13358 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13359 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013360 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013361 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013362 data = PyObject_MALLOC((length + 1) * char_size);
13363 if (data == NULL) {
13364 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013365 goto onError;
13366 }
13367
Victor Stinnerc3c74152011-10-02 20:39:55 +020013368 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013369 if (share_utf8) {
13370 _PyUnicode_UTF8_LENGTH(self) = length;
13371 _PyUnicode_UTF8(self) = data;
13372 }
13373 if (share_wstr) {
13374 _PyUnicode_WSTR_LENGTH(self) = length;
13375 _PyUnicode_WSTR(self) = (wchar_t *)data;
13376 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013377
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013378 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013379 kind * (length + 1));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013380 Py_DECREF(unicode);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013381 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013382#ifdef Py_DEBUG
13383 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13384#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013385 return (PyObject *)self;
13386
13387onError:
13388 Py_DECREF(unicode);
13389 Py_DECREF(self);
13390 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013391}
13392
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013393PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013394 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013395\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013396Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013397encoding defaults to the current default string encoding.\n\
13398errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013399
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013400static PyObject *unicode_iter(PyObject *seq);
13401
Guido van Rossumd57fd912000-03-10 22:53:23 +000013402PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013403 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013404 "str", /* tp_name */
13405 sizeof(PyUnicodeObject), /* tp_size */
13406 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013407 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013408 (destructor)unicode_dealloc, /* tp_dealloc */
13409 0, /* tp_print */
13410 0, /* tp_getattr */
13411 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013412 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013413 unicode_repr, /* tp_repr */
13414 &unicode_as_number, /* tp_as_number */
13415 &unicode_as_sequence, /* tp_as_sequence */
13416 &unicode_as_mapping, /* tp_as_mapping */
13417 (hashfunc) unicode_hash, /* tp_hash*/
13418 0, /* tp_call*/
13419 (reprfunc) unicode_str, /* tp_str */
13420 PyObject_GenericGetAttr, /* tp_getattro */
13421 0, /* tp_setattro */
13422 0, /* tp_as_buffer */
13423 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013424 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013425 unicode_doc, /* tp_doc */
13426 0, /* tp_traverse */
13427 0, /* tp_clear */
13428 PyUnicode_RichCompare, /* tp_richcompare */
13429 0, /* tp_weaklistoffset */
13430 unicode_iter, /* tp_iter */
13431 0, /* tp_iternext */
13432 unicode_methods, /* tp_methods */
13433 0, /* tp_members */
13434 0, /* tp_getset */
13435 &PyBaseObject_Type, /* tp_base */
13436 0, /* tp_dict */
13437 0, /* tp_descr_get */
13438 0, /* tp_descr_set */
13439 0, /* tp_dictoffset */
13440 0, /* tp_init */
13441 0, /* tp_alloc */
13442 unicode_new, /* tp_new */
13443 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013444};
13445
13446/* Initialize the Unicode implementation */
13447
Thomas Wouters78890102000-07-22 19:25:51 +000013448void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013449{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013450 int i;
13451
Thomas Wouters477c8d52006-05-27 19:21:47 +000013452 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013453 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013454 0x000A, /* LINE FEED */
13455 0x000D, /* CARRIAGE RETURN */
13456 0x001C, /* FILE SEPARATOR */
13457 0x001D, /* GROUP SEPARATOR */
13458 0x001E, /* RECORD SEPARATOR */
13459 0x0085, /* NEXT LINE */
13460 0x2028, /* LINE SEPARATOR */
13461 0x2029, /* PARAGRAPH SEPARATOR */
13462 };
13463
Fred Drakee4315f52000-05-09 19:53:39 +000013464 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013465 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013466 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013467 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013468 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013469
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013470 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013471 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013472 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013473 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013474
13475 /* initialize the linebreak bloom filter */
13476 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013477 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013478 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013479
13480 PyType_Ready(&EncodingMapType);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013481}
13482
13483/* Finalize the Unicode implementation */
13484
Christian Heimesa156e092008-02-16 07:38:31 +000013485int
13486PyUnicode_ClearFreeList(void)
13487{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013488 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013489}
13490
Guido van Rossumd57fd912000-03-10 22:53:23 +000013491void
Thomas Wouters78890102000-07-22 19:25:51 +000013492_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013493{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013494 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013495
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013496 Py_XDECREF(unicode_empty);
13497 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013498
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013499 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013500 if (unicode_latin1[i]) {
13501 Py_DECREF(unicode_latin1[i]);
13502 unicode_latin1[i] = NULL;
13503 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013504 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020013505 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000013506 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013507}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013508
Walter Dörwald16807132007-05-25 13:52:07 +000013509void
13510PyUnicode_InternInPlace(PyObject **p)
13511{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013512 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
13513 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013514#ifdef Py_DEBUG
13515 assert(s != NULL);
13516 assert(_PyUnicode_CHECK(s));
13517#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013518 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013519 return;
13520#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013521 /* If it's a subclass, we don't really know what putting
13522 it in the interned dict might do. */
13523 if (!PyUnicode_CheckExact(s))
13524 return;
13525 if (PyUnicode_CHECK_INTERNED(s))
13526 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013527 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013528 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013529 return;
13530 }
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013531 s = (PyUnicodeObject *)(*p);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013532 if (interned == NULL) {
13533 interned = PyDict_New();
13534 if (interned == NULL) {
13535 PyErr_Clear(); /* Don't leave an exception */
13536 return;
13537 }
13538 }
13539 /* It might be that the GetItem call fails even
13540 though the key is present in the dictionary,
13541 namely when this happens during a stack overflow. */
13542 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000013543 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013544 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013545
Benjamin Peterson29060642009-01-31 22:14:21 +000013546 if (t) {
13547 Py_INCREF(t);
13548 Py_DECREF(*p);
13549 *p = t;
13550 return;
13551 }
Walter Dörwald16807132007-05-25 13:52:07 +000013552
Benjamin Peterson14339b62009-01-31 16:36:08 +000013553 PyThreadState_GET()->recursion_critical = 1;
13554 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
13555 PyErr_Clear();
13556 PyThreadState_GET()->recursion_critical = 0;
13557 return;
13558 }
13559 PyThreadState_GET()->recursion_critical = 0;
13560 /* The two references in interned are not counted by refcnt.
13561 The deallocator will take care of this */
13562 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013563 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013564}
13565
13566void
13567PyUnicode_InternImmortal(PyObject **p)
13568{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013569 PyUnicodeObject *u = (PyUnicodeObject *)*p;
13570
Benjamin Peterson14339b62009-01-31 16:36:08 +000013571 PyUnicode_InternInPlace(p);
13572 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013573 _PyUnicode_STATE(u).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013574 Py_INCREF(*p);
13575 }
Walter Dörwald16807132007-05-25 13:52:07 +000013576}
13577
13578PyObject *
13579PyUnicode_InternFromString(const char *cp)
13580{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013581 PyObject *s = PyUnicode_FromString(cp);
13582 if (s == NULL)
13583 return NULL;
13584 PyUnicode_InternInPlace(&s);
13585 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000013586}
13587
Alexander Belopolsky40018472011-02-26 01:02:56 +000013588void
13589_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000013590{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013591 PyObject *keys;
13592 PyUnicodeObject *s;
13593 Py_ssize_t i, n;
13594 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000013595
Benjamin Peterson14339b62009-01-31 16:36:08 +000013596 if (interned == NULL || !PyDict_Check(interned))
13597 return;
13598 keys = PyDict_Keys(interned);
13599 if (keys == NULL || !PyList_Check(keys)) {
13600 PyErr_Clear();
13601 return;
13602 }
Walter Dörwald16807132007-05-25 13:52:07 +000013603
Benjamin Peterson14339b62009-01-31 16:36:08 +000013604 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
13605 detector, interned unicode strings are not forcibly deallocated;
13606 rather, we give them their stolen references back, and then clear
13607 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000013608
Benjamin Peterson14339b62009-01-31 16:36:08 +000013609 n = PyList_GET_SIZE(keys);
13610 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000013611 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013612 for (i = 0; i < n; i++) {
13613 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013614 if (PyUnicode_READY(s) == -1) {
13615 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013616 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013617 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013618 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013619 case SSTATE_NOT_INTERNED:
13620 /* XXX Shouldn't happen */
13621 break;
13622 case SSTATE_INTERNED_IMMORTAL:
13623 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013624 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013625 break;
13626 case SSTATE_INTERNED_MORTAL:
13627 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013628 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013629 break;
13630 default:
13631 Py_FatalError("Inconsistent interned string state.");
13632 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013633 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013634 }
13635 fprintf(stderr, "total size of all interned strings: "
13636 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
13637 "mortal/immortal\n", mortal_size, immortal_size);
13638 Py_DECREF(keys);
13639 PyDict_Clear(interned);
13640 Py_DECREF(interned);
13641 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000013642}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013643
13644
13645/********************* Unicode Iterator **************************/
13646
13647typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013648 PyObject_HEAD
13649 Py_ssize_t it_index;
13650 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013651} unicodeiterobject;
13652
13653static void
13654unicodeiter_dealloc(unicodeiterobject *it)
13655{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013656 _PyObject_GC_UNTRACK(it);
13657 Py_XDECREF(it->it_seq);
13658 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013659}
13660
13661static int
13662unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
13663{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013664 Py_VISIT(it->it_seq);
13665 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013666}
13667
13668static PyObject *
13669unicodeiter_next(unicodeiterobject *it)
13670{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013671 PyUnicodeObject *seq;
13672 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013673
Benjamin Peterson14339b62009-01-31 16:36:08 +000013674 assert(it != NULL);
13675 seq = it->it_seq;
13676 if (seq == NULL)
13677 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013678 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013679
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013680 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
13681 int kind = PyUnicode_KIND(seq);
13682 void *data = PyUnicode_DATA(seq);
13683 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
13684 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013685 if (item != NULL)
13686 ++it->it_index;
13687 return item;
13688 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013689
Benjamin Peterson14339b62009-01-31 16:36:08 +000013690 Py_DECREF(seq);
13691 it->it_seq = NULL;
13692 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013693}
13694
13695static PyObject *
13696unicodeiter_len(unicodeiterobject *it)
13697{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013698 Py_ssize_t len = 0;
13699 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013700 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013701 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013702}
13703
13704PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
13705
13706static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013707 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000013708 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000013709 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013710};
13711
13712PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013713 PyVarObject_HEAD_INIT(&PyType_Type, 0)
13714 "str_iterator", /* tp_name */
13715 sizeof(unicodeiterobject), /* tp_basicsize */
13716 0, /* tp_itemsize */
13717 /* methods */
13718 (destructor)unicodeiter_dealloc, /* tp_dealloc */
13719 0, /* tp_print */
13720 0, /* tp_getattr */
13721 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013722 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013723 0, /* tp_repr */
13724 0, /* tp_as_number */
13725 0, /* tp_as_sequence */
13726 0, /* tp_as_mapping */
13727 0, /* tp_hash */
13728 0, /* tp_call */
13729 0, /* tp_str */
13730 PyObject_GenericGetAttr, /* tp_getattro */
13731 0, /* tp_setattro */
13732 0, /* tp_as_buffer */
13733 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
13734 0, /* tp_doc */
13735 (traverseproc)unicodeiter_traverse, /* tp_traverse */
13736 0, /* tp_clear */
13737 0, /* tp_richcompare */
13738 0, /* tp_weaklistoffset */
13739 PyObject_SelfIter, /* tp_iter */
13740 (iternextfunc)unicodeiter_next, /* tp_iternext */
13741 unicodeiter_methods, /* tp_methods */
13742 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013743};
13744
13745static PyObject *
13746unicode_iter(PyObject *seq)
13747{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013748 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013749
Benjamin Peterson14339b62009-01-31 16:36:08 +000013750 if (!PyUnicode_Check(seq)) {
13751 PyErr_BadInternalCall();
13752 return NULL;
13753 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013754 if (PyUnicode_READY(seq) == -1)
13755 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013756 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
13757 if (it == NULL)
13758 return NULL;
13759 it->it_index = 0;
13760 Py_INCREF(seq);
13761 it->it_seq = (PyUnicodeObject *)seq;
13762 _PyObject_GC_TRACK(it);
13763 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013764}
13765
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013766#define UNIOP(x) Py_UNICODE_##x
13767#define UNIOP_t Py_UNICODE
13768#include "uniops.h"
13769#undef UNIOP
13770#undef UNIOP_t
13771#define UNIOP(x) Py_UCS4_##x
13772#define UNIOP_t Py_UCS4
13773#include "uniops.h"
13774#undef UNIOP
13775#undef UNIOP_t
Victor Stinner331ea922010-08-10 16:37:20 +000013776
Victor Stinner71133ff2010-09-01 23:43:53 +000013777Py_UNICODE*
Victor Stinner46408602010-09-03 16:18:00 +000013778PyUnicode_AsUnicodeCopy(PyObject *object)
Victor Stinner71133ff2010-09-01 23:43:53 +000013779{
13780 PyUnicodeObject *unicode = (PyUnicodeObject *)object;
Victor Stinner577db2c2011-10-11 22:12:48 +020013781 Py_UNICODE *u, *copy;
Victor Stinner71133ff2010-09-01 23:43:53 +000013782 Py_ssize_t size;
13783
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013784 if (!PyUnicode_Check(unicode)) {
13785 PyErr_BadArgument();
13786 return NULL;
13787 }
Victor Stinner577db2c2011-10-11 22:12:48 +020013788 u = PyUnicode_AsUnicode(object);
13789 if (u == NULL)
13790 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000013791 /* Ensure we won't overflow the size. */
13792 if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
13793 PyErr_NoMemory();
13794 return NULL;
13795 }
13796 size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
13797 size *= sizeof(Py_UNICODE);
13798 copy = PyMem_Malloc(size);
13799 if (copy == NULL) {
13800 PyErr_NoMemory();
13801 return NULL;
13802 }
Victor Stinner577db2c2011-10-11 22:12:48 +020013803 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000013804 return copy;
13805}
Martin v. Löwis5b222132007-06-10 09:51:05 +000013806
Georg Brandl66c221e2010-10-14 07:04:07 +000013807/* A _string module, to export formatter_parser and formatter_field_name_split
13808 to the string.Formatter class implemented in Python. */
13809
13810static PyMethodDef _string_methods[] = {
13811 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
13812 METH_O, PyDoc_STR("split the argument as a field name")},
13813 {"formatter_parser", (PyCFunction) formatter_parser,
13814 METH_O, PyDoc_STR("parse the argument as a format string")},
13815 {NULL, NULL}
13816};
13817
13818static struct PyModuleDef _string_module = {
13819 PyModuleDef_HEAD_INIT,
13820 "_string",
13821 PyDoc_STR("string helper module"),
13822 0,
13823 _string_methods,
13824 NULL,
13825 NULL,
13826 NULL,
13827 NULL
13828};
13829
13830PyMODINIT_FUNC
13831PyInit__string(void)
13832{
13833 return PyModule_Create(&_string_module);
13834}
13835
13836
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013837#ifdef __cplusplus
13838}
13839#endif