blob: 8608776b5ddad958e2b18600544992b2dab27f4a [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 { \
180 const from_type *iter_; to_type *to_; \
181 for (iter_ = (begin), to_ = (to_type *)(to); \
182 iter_ < (end); \
183 ++iter_, ++to_) { \
184 *to_ = (to_type)*iter_; \
185 } \
186 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200187
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200188/* The Unicode string has been modified: reset the hash */
189#define _PyUnicode_DIRTY(op) do { _PyUnicode_HASH(op) = -1; } while (0)
190
Walter Dörwald16807132007-05-25 13:52:07 +0000191/* This dictionary holds all interned unicode strings. Note that references
192 to strings in this dictionary are *not* counted in the string's ob_refcnt.
193 When the interned string reaches a refcnt of 0 the string deallocation
194 function will delete the reference from this dictionary.
195
196 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000197 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000198*/
199static PyObject *interned;
200
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000201/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200202static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000203
204/* Single character Unicode strings in the Latin-1 range are being
205 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200206static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000207
Christian Heimes190d79e2008-01-30 11:58:22 +0000208/* Fast detection of the most frequent whitespace characters */
209const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000210 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000211/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000212/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000213/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000214/* case 0x000C: * FORM FEED */
215/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000216 0, 1, 1, 1, 1, 1, 0, 0,
217 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000218/* case 0x001C: * FILE SEPARATOR */
219/* case 0x001D: * GROUP SEPARATOR */
220/* case 0x001E: * RECORD SEPARATOR */
221/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000222 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000223/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000224 1, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0,
226 0, 0, 0, 0, 0, 0, 0, 0,
227 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000228
Benjamin Peterson14339b62009-01-31 16:36:08 +0000229 0, 0, 0, 0, 0, 0, 0, 0,
230 0, 0, 0, 0, 0, 0, 0, 0,
231 0, 0, 0, 0, 0, 0, 0, 0,
232 0, 0, 0, 0, 0, 0, 0, 0,
233 0, 0, 0, 0, 0, 0, 0, 0,
234 0, 0, 0, 0, 0, 0, 0, 0,
235 0, 0, 0, 0, 0, 0, 0, 0,
236 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000237};
238
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200239/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200240static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200241static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200242static void copy_characters(
243 PyObject *to, Py_ssize_t to_start,
244 PyObject *from, Py_ssize_t from_start,
245 Py_ssize_t how_many);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200246#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200247static int unicode_is_singleton(PyObject *unicode);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200248#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200249
Alexander Belopolsky40018472011-02-26 01:02:56 +0000250static PyObject *
251unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000252 PyObject **errorHandler,const char *encoding, const char *reason,
253 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
254 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
255
Alexander Belopolsky40018472011-02-26 01:02:56 +0000256static void
257raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300258 const char *encoding,
259 const Py_UNICODE *unicode, Py_ssize_t size,
260 Py_ssize_t startpos, Py_ssize_t endpos,
261 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000262
Christian Heimes190d79e2008-01-30 11:58:22 +0000263/* Same for linebreaks */
264static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000265 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000266/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000267/* 0x000B, * LINE TABULATION */
268/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000269/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000270 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000271 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000272/* 0x001C, * FILE SEPARATOR */
273/* 0x001D, * GROUP SEPARATOR */
274/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000275 0, 0, 0, 0, 1, 1, 1, 0,
276 0, 0, 0, 0, 0, 0, 0, 0,
277 0, 0, 0, 0, 0, 0, 0, 0,
278 0, 0, 0, 0, 0, 0, 0, 0,
279 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000280
Benjamin Peterson14339b62009-01-31 16:36:08 +0000281 0, 0, 0, 0, 0, 0, 0, 0,
282 0, 0, 0, 0, 0, 0, 0, 0,
283 0, 0, 0, 0, 0, 0, 0, 0,
284 0, 0, 0, 0, 0, 0, 0, 0,
285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0,
287 0, 0, 0, 0, 0, 0, 0, 0,
288 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000289};
290
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300291/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
292 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000293Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000294PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000295{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000296#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000297 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000298#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000299 /* This is actually an illegal character, so it should
300 not be passed to unichr. */
301 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000302#endif
303}
304
Victor Stinner910337b2011-10-03 03:20:16 +0200305#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200306int
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200307/* FIXME: use PyObject* type for op */
308_PyUnicode_CheckConsistency(void *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200309{
310 PyASCIIObject *ascii;
311 unsigned int kind;
312
313 assert(PyUnicode_Check(op));
314
315 ascii = (PyASCIIObject *)op;
316 kind = ascii->state.kind;
317
Victor Stinnera3b334d2011-10-03 13:53:37 +0200318 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200319 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200320 assert(ascii->state.ready == 1);
321 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200322 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200323 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200324 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200325
Victor Stinnera41463c2011-10-04 01:05:08 +0200326 if (ascii->state.compact == 1) {
327 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200328 assert(kind == PyUnicode_1BYTE_KIND
329 || kind == PyUnicode_2BYTE_KIND
330 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200331 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200332 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200333 assert (compact->utf8 != data);
334 } else {
335 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
336
337 data = unicode->data.any;
338 if (kind == PyUnicode_WCHAR_KIND) {
339 assert(ascii->state.compact == 0);
340 assert(ascii->state.ascii == 0);
341 assert(ascii->state.ready == 0);
342 assert(ascii->wstr != NULL);
343 assert(data == NULL);
344 assert(compact->utf8 == NULL);
345 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
346 }
347 else {
348 assert(kind == PyUnicode_1BYTE_KIND
349 || kind == PyUnicode_2BYTE_KIND
350 || kind == PyUnicode_4BYTE_KIND);
351 assert(ascii->state.compact == 0);
352 assert(ascii->state.ready == 1);
353 assert(data != NULL);
354 if (ascii->state.ascii) {
355 assert (compact->utf8 == data);
356 assert (compact->utf8_length == ascii->length);
357 }
358 else
359 assert (compact->utf8 != data);
360 }
361 }
362 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200363 if (
364#if SIZEOF_WCHAR_T == 2
365 kind == PyUnicode_2BYTE_KIND
366#else
367 kind == PyUnicode_4BYTE_KIND
368#endif
369 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200370 {
371 assert(ascii->wstr == data);
372 assert(compact->wstr_length == ascii->length);
373 } else
374 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200375 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200376
377 if (compact->utf8 == NULL)
378 assert(compact->utf8_length == 0);
379 if (ascii->wstr == NULL)
380 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200381 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200382 /* check that the best kind is used */
383 if (check_content && kind != PyUnicode_WCHAR_KIND)
384 {
385 Py_ssize_t i;
386 Py_UCS4 maxchar = 0;
387 void *data = PyUnicode_DATA(ascii);
388 for (i=0; i < ascii->length; i++)
389 {
390 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
391 if (ch > maxchar)
392 maxchar = ch;
393 }
394 if (kind == PyUnicode_1BYTE_KIND) {
395 if (ascii->state.ascii == 0)
396 assert(maxchar >= 128);
397 else
398 assert(maxchar < 128);
399 }
400 else if (kind == PyUnicode_2BYTE_KIND)
401 assert(maxchar >= 0x100);
402 else
403 assert(maxchar >= 0x10000);
404 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200405 if (check_content && !unicode_is_singleton((PyObject*)ascii))
406 assert(ascii->hash == -1);
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400407 return 1;
408}
Victor Stinner910337b2011-10-03 03:20:16 +0200409#endif
410
Thomas Wouters477c8d52006-05-27 19:21:47 +0000411/* --- Bloom Filters ----------------------------------------------------- */
412
413/* stuff to implement simple "bloom filters" for Unicode characters.
414 to keep things simple, we use a single bitmask, using the least 5
415 bits from each unicode characters as the bit index. */
416
417/* the linebreak mask is set up by Unicode_Init below */
418
Antoine Pitrouf068f942010-01-13 14:19:12 +0000419#if LONG_BIT >= 128
420#define BLOOM_WIDTH 128
421#elif LONG_BIT >= 64
422#define BLOOM_WIDTH 64
423#elif LONG_BIT >= 32
424#define BLOOM_WIDTH 32
425#else
426#error "LONG_BIT is smaller than 32"
427#endif
428
Thomas Wouters477c8d52006-05-27 19:21:47 +0000429#define BLOOM_MASK unsigned long
430
431static BLOOM_MASK bloom_linebreak;
432
Antoine Pitrouf068f942010-01-13 14:19:12 +0000433#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
434#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000435
Benjamin Peterson29060642009-01-31 22:14:21 +0000436#define BLOOM_LINEBREAK(ch) \
437 ((ch) < 128U ? ascii_linebreak[(ch)] : \
438 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000439
Alexander Belopolsky40018472011-02-26 01:02:56 +0000440Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200441make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000442{
443 /* calculate simple bloom-style bitmask for a given unicode string */
444
Antoine Pitrouf068f942010-01-13 14:19:12 +0000445 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000446 Py_ssize_t i;
447
448 mask = 0;
449 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200450 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000451
452 return mask;
453}
454
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200455#define BLOOM_MEMBER(mask, chr, str) \
456 (BLOOM(mask, chr) \
457 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000458
Guido van Rossumd57fd912000-03-10 22:53:23 +0000459/* --- Unicode Object ----------------------------------------------------- */
460
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200461static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200462fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200463
464Py_LOCAL_INLINE(char *) findchar(void *s, int kind,
465 Py_ssize_t size, Py_UCS4 ch,
466 int direction)
467{
468 /* like wcschr, but doesn't stop at NULL characters */
469 Py_ssize_t i;
470 if (direction == 1) {
471 for(i = 0; i < size; i++)
472 if (PyUnicode_READ(kind, s, i) == ch)
473 return (char*)s + PyUnicode_KIND_SIZE(kind, i);
474 }
475 else {
476 for(i = size-1; i >= 0; i--)
477 if (PyUnicode_READ(kind, s, i) == ch)
478 return (char*)s + PyUnicode_KIND_SIZE(kind, i);
479 }
480 return NULL;
481}
482
Victor Stinnerfe226c02011-10-03 03:52:20 +0200483static PyObject*
484resize_compact(PyObject *unicode, Py_ssize_t length)
485{
486 Py_ssize_t char_size;
487 Py_ssize_t struct_size;
488 Py_ssize_t new_size;
489 int share_wstr;
490
491 assert(PyUnicode_IS_READY(unicode));
492 char_size = PyUnicode_CHARACTER_SIZE(unicode);
493 if (PyUnicode_IS_COMPACT_ASCII(unicode))
494 struct_size = sizeof(PyASCIIObject);
495 else
496 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200497 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200498
499 _Py_DEC_REFTOTAL;
500 _Py_ForgetReference(unicode);
501
502 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
503 PyErr_NoMemory();
504 return NULL;
505 }
506 new_size = (struct_size + (length + 1) * char_size);
507
508 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
509 if (unicode == NULL) {
510 PyObject_Del(unicode);
511 PyErr_NoMemory();
512 return NULL;
513 }
514 _Py_NewReference(unicode);
515 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200516 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200517 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200518 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
519 _PyUnicode_WSTR_LENGTH(unicode) = length;
520 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200521 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
522 length, 0);
523 return unicode;
524}
525
Alexander Belopolsky40018472011-02-26 01:02:56 +0000526static int
Victor Stinner95663112011-10-04 01:03:50 +0200527resize_inplace(PyUnicodeObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000528{
Victor Stinner95663112011-10-04 01:03:50 +0200529 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200530 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200531 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000532
Victor Stinner95663112011-10-04 01:03:50 +0200533 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200534
535 if (PyUnicode_IS_READY(unicode)) {
536 Py_ssize_t char_size;
537 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200538 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200539 void *data;
540
541 data = _PyUnicode_DATA_ANY(unicode);
542 assert(data != NULL);
543 char_size = PyUnicode_CHARACTER_SIZE(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200544 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
545 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200546 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
547 {
548 PyObject_DEL(_PyUnicode_UTF8(unicode));
549 _PyUnicode_UTF8(unicode) = NULL;
550 _PyUnicode_UTF8_LENGTH(unicode) = 0;
551 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200552
553 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
554 PyErr_NoMemory();
555 return -1;
556 }
557 new_size = (length + 1) * char_size;
558
559 data = (PyObject *)PyObject_REALLOC(data, new_size);
560 if (data == NULL) {
561 PyErr_NoMemory();
562 return -1;
563 }
564 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200565 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200566 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200567 _PyUnicode_WSTR_LENGTH(unicode) = length;
568 }
569 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200570 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200571 _PyUnicode_UTF8_LENGTH(unicode) = length;
572 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200573 _PyUnicode_LENGTH(unicode) = length;
574 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200575 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200576 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200577 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200578 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200579 }
Victor Stinner95663112011-10-04 01:03:50 +0200580 assert(_PyUnicode_WSTR(unicode) != NULL);
581
582 /* check for integer overflow */
583 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
584 PyErr_NoMemory();
585 return -1;
586 }
587 wstr = _PyUnicode_WSTR(unicode);
588 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
589 if (!wstr) {
590 PyErr_NoMemory();
591 return -1;
592 }
593 _PyUnicode_WSTR(unicode) = wstr;
594 _PyUnicode_WSTR(unicode)[length] = 0;
595 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200596 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000597 return 0;
598}
599
Victor Stinnerfe226c02011-10-03 03:52:20 +0200600static PyObject*
601resize_copy(PyObject *unicode, Py_ssize_t length)
602{
603 Py_ssize_t copy_length;
604 if (PyUnicode_IS_COMPACT(unicode)) {
605 PyObject *copy;
606 assert(PyUnicode_IS_READY(unicode));
607
608 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
609 if (copy == NULL)
610 return NULL;
611
612 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200613 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200614 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200615 }
616 else {
Victor Stinner2fd82272011-10-03 04:06:05 +0200617 PyUnicodeObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200618 assert(_PyUnicode_WSTR(unicode) != NULL);
619 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner2fd82272011-10-03 04:06:05 +0200620 w = _PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200621 if (w == NULL)
622 return NULL;
623 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
624 copy_length = Py_MIN(copy_length, length);
625 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
626 copy_length);
627 return (PyObject*)w;
628 }
629}
630
Guido van Rossumd57fd912000-03-10 22:53:23 +0000631/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000632 Ux0000 terminated; some code (e.g. new_identifier)
633 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000634
635 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000636 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000637
638*/
639
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200640#ifdef Py_DEBUG
641int unicode_old_new_calls = 0;
642#endif
643
Alexander Belopolsky40018472011-02-26 01:02:56 +0000644static PyUnicodeObject *
645_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000646{
647 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200648 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000649
Thomas Wouters477c8d52006-05-27 19:21:47 +0000650 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000651 if (length == 0 && unicode_empty != NULL) {
652 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200653 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000654 }
655
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000656 /* Ensure we won't overflow the size. */
657 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
658 return (PyUnicodeObject *)PyErr_NoMemory();
659 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200660 if (length < 0) {
661 PyErr_SetString(PyExc_SystemError,
662 "Negative size passed to _PyUnicode_New");
663 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000664 }
665
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200666#ifdef Py_DEBUG
667 ++unicode_old_new_calls;
668#endif
669
670 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
671 if (unicode == NULL)
672 return NULL;
673 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
674 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
675 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000676 PyErr_NoMemory();
677 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000678 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200679
Jeremy Hyltond8082792003-09-16 19:41:39 +0000680 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000681 * the caller fails before initializing str -- unicode_resize()
682 * reads str[0], and the Keep-Alive optimization can keep memory
683 * allocated for str alive across a call to unicode_dealloc(unicode).
684 * We don't want unicode_resize to read uninitialized memory in
685 * that case.
686 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200687 _PyUnicode_WSTR(unicode)[0] = 0;
688 _PyUnicode_WSTR(unicode)[length] = 0;
689 _PyUnicode_WSTR_LENGTH(unicode) = length;
690 _PyUnicode_HASH(unicode) = -1;
691 _PyUnicode_STATE(unicode).interned = 0;
692 _PyUnicode_STATE(unicode).kind = 0;
693 _PyUnicode_STATE(unicode).compact = 0;
694 _PyUnicode_STATE(unicode).ready = 0;
695 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200696 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200697 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200698 _PyUnicode_UTF8(unicode) = NULL;
699 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000700 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000701
Benjamin Peterson29060642009-01-31 22:14:21 +0000702 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000703 /* XXX UNREF/NEWREF interface should be more symmetrical */
704 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000705 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000706 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000707 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000708}
709
Victor Stinnerf42dc442011-10-02 23:33:16 +0200710static const char*
711unicode_kind_name(PyObject *unicode)
712{
Victor Stinner42dfd712011-10-03 14:41:45 +0200713 /* don't check consistency: unicode_kind_name() is called from
714 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200715 if (!PyUnicode_IS_COMPACT(unicode))
716 {
717 if (!PyUnicode_IS_READY(unicode))
718 return "wstr";
719 switch(PyUnicode_KIND(unicode))
720 {
721 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200722 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200723 return "legacy ascii";
724 else
725 return "legacy latin1";
726 case PyUnicode_2BYTE_KIND:
727 return "legacy UCS2";
728 case PyUnicode_4BYTE_KIND:
729 return "legacy UCS4";
730 default:
731 return "<legacy invalid kind>";
732 }
733 }
734 assert(PyUnicode_IS_READY(unicode));
735 switch(PyUnicode_KIND(unicode))
736 {
737 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200738 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200739 return "ascii";
740 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200741 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200742 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200743 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200744 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200745 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200746 default:
747 return "<invalid compact kind>";
748 }
749}
750
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200751#ifdef Py_DEBUG
752int unicode_new_new_calls = 0;
753
754/* Functions wrapping macros for use in debugger */
755char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200756 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200757}
758
759void *_PyUnicode_compact_data(void *unicode) {
760 return _PyUnicode_COMPACT_DATA(unicode);
761}
762void *_PyUnicode_data(void *unicode){
763 printf("obj %p\n", unicode);
764 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
765 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
766 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
767 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
768 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
769 return PyUnicode_DATA(unicode);
770}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200771
772void
773_PyUnicode_Dump(PyObject *op)
774{
775 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200776 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
777 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
778 void *data;
779 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
780 if (ascii->state.compact)
781 data = (compact + 1);
782 else
783 data = unicode->data.any;
784 if (ascii->wstr == data)
785 printf("shared ");
786 printf("wstr=%p", ascii->wstr);
Victor Stinnera3b334d2011-10-03 13:53:37 +0200787 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200788 printf(" (%zu), ", compact->wstr_length);
789 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
790 printf("shared ");
791 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200792 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200793 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200794}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200795#endif
796
797PyObject *
798PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
799{
800 PyObject *obj;
801 PyCompactUnicodeObject *unicode;
802 void *data;
803 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200804 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200805 Py_ssize_t char_size;
806 Py_ssize_t struct_size;
807
808 /* Optimization for empty strings */
809 if (size == 0 && unicode_empty != NULL) {
810 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200811 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200812 }
813
814#ifdef Py_DEBUG
815 ++unicode_new_new_calls;
816#endif
817
Victor Stinner9e9d6892011-10-04 01:02:02 +0200818 is_ascii = 0;
819 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200820 struct_size = sizeof(PyCompactUnicodeObject);
821 if (maxchar < 128) {
822 kind_state = PyUnicode_1BYTE_KIND;
823 char_size = 1;
824 is_ascii = 1;
825 struct_size = sizeof(PyASCIIObject);
826 }
827 else if (maxchar < 256) {
828 kind_state = PyUnicode_1BYTE_KIND;
829 char_size = 1;
830 }
831 else if (maxchar < 65536) {
832 kind_state = PyUnicode_2BYTE_KIND;
833 char_size = 2;
834 if (sizeof(wchar_t) == 2)
835 is_sharing = 1;
836 }
837 else {
838 kind_state = PyUnicode_4BYTE_KIND;
839 char_size = 4;
840 if (sizeof(wchar_t) == 4)
841 is_sharing = 1;
842 }
843
844 /* Ensure we won't overflow the size. */
845 if (size < 0) {
846 PyErr_SetString(PyExc_SystemError,
847 "Negative size passed to PyUnicode_New");
848 return NULL;
849 }
850 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
851 return PyErr_NoMemory();
852
853 /* Duplicated allocation code from _PyObject_New() instead of a call to
854 * PyObject_New() so we are able to allocate space for the object and
855 * it's data buffer.
856 */
857 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
858 if (obj == NULL)
859 return PyErr_NoMemory();
860 obj = PyObject_INIT(obj, &PyUnicode_Type);
861 if (obj == NULL)
862 return NULL;
863
864 unicode = (PyCompactUnicodeObject *)obj;
865 if (is_ascii)
866 data = ((PyASCIIObject*)obj) + 1;
867 else
868 data = unicode + 1;
869 _PyUnicode_LENGTH(unicode) = size;
870 _PyUnicode_HASH(unicode) = -1;
871 _PyUnicode_STATE(unicode).interned = 0;
872 _PyUnicode_STATE(unicode).kind = kind_state;
873 _PyUnicode_STATE(unicode).compact = 1;
874 _PyUnicode_STATE(unicode).ready = 1;
875 _PyUnicode_STATE(unicode).ascii = is_ascii;
876 if (is_ascii) {
877 ((char*)data)[size] = 0;
878 _PyUnicode_WSTR(unicode) = NULL;
879 }
880 else if (kind_state == PyUnicode_1BYTE_KIND) {
881 ((char*)data)[size] = 0;
882 _PyUnicode_WSTR(unicode) = NULL;
883 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200884 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200885 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200886 }
887 else {
888 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200889 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200890 if (kind_state == PyUnicode_2BYTE_KIND)
891 ((Py_UCS2*)data)[size] = 0;
892 else /* kind_state == PyUnicode_4BYTE_KIND */
893 ((Py_UCS4*)data)[size] = 0;
894 if (is_sharing) {
895 _PyUnicode_WSTR_LENGTH(unicode) = size;
896 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
897 }
898 else {
899 _PyUnicode_WSTR_LENGTH(unicode) = 0;
900 _PyUnicode_WSTR(unicode) = NULL;
901 }
902 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200903 assert(_PyUnicode_CheckConsistency(unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200904 return obj;
905}
906
907#if SIZEOF_WCHAR_T == 2
908/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
909 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +0200910 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200911
912 This function assumes that unicode can hold one more code point than wstr
913 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +0200914static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200915unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
916 PyUnicodeObject *unicode)
917{
918 const wchar_t *iter;
919 Py_UCS4 *ucs4_out;
920
Victor Stinner910337b2011-10-03 03:20:16 +0200921 assert(unicode != NULL);
922 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200923 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
924 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
925
926 for (iter = begin; iter < end; ) {
927 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
928 _PyUnicode_GET_LENGTH(unicode)));
929 if (*iter >= 0xD800 && *iter <= 0xDBFF
930 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
931 {
932 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
933 iter += 2;
934 }
935 else {
936 *ucs4_out++ = *iter;
937 iter++;
938 }
939 }
940 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
941 _PyUnicode_GET_LENGTH(unicode)));
942
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200943}
944#endif
945
Victor Stinnercd9950f2011-10-02 00:34:53 +0200946static int
947_PyUnicode_Dirty(PyObject *unicode)
948{
Victor Stinner910337b2011-10-03 03:20:16 +0200949 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +0200950 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +0200951 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +0200952 "Cannot modify a string having more than 1 reference");
953 return -1;
954 }
955 _PyUnicode_DIRTY(unicode);
956 return 0;
957}
958
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200959static int
960_copy_characters(PyObject *to, Py_ssize_t to_start,
961 PyObject *from, Py_ssize_t from_start,
962 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200963{
Victor Stinnera0702ab2011-09-29 14:14:38 +0200964 unsigned int from_kind, to_kind;
965 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200966 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200967
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200968 assert(PyUnicode_Check(from));
969 assert(PyUnicode_Check(to));
970 assert(PyUnicode_IS_READY(from));
971 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200972
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200973 assert(PyUnicode_GET_LENGTH(from) >= how_many);
974 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
975 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200976
Victor Stinnerf5ca1a22011-09-28 23:54:59 +0200977 if (how_many == 0)
978 return 0;
979
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200980 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +0200981 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200982 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +0200983 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200984
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200985#ifdef Py_DEBUG
986 if (!check_maxchar
987 && (from_kind > to_kind
988 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200989 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200990 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
991 Py_UCS4 ch;
992 Py_ssize_t i;
993 for (i=0; i < how_many; i++) {
994 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
995 assert(ch <= to_maxchar);
996 }
997 }
998#endif
999 fast = (from_kind == to_kind);
1000 if (check_maxchar
1001 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1002 {
1003 /* deny latin1 => ascii */
1004 fast = 0;
1005 }
1006
1007 if (fast) {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001008 Py_MEMCPY((char*)to_data
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001009 + PyUnicode_KIND_SIZE(to_kind, to_start),
Victor Stinnera0702ab2011-09-29 14:14:38 +02001010 (char*)from_data
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001011 + PyUnicode_KIND_SIZE(from_kind, from_start),
1012 PyUnicode_KIND_SIZE(to_kind, how_many));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001013 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001014 else if (from_kind == PyUnicode_1BYTE_KIND
1015 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001016 {
1017 _PyUnicode_CONVERT_BYTES(
1018 Py_UCS1, Py_UCS2,
1019 PyUnicode_1BYTE_DATA(from) + from_start,
1020 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1021 PyUnicode_2BYTE_DATA(to) + to_start
1022 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001023 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001024 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001025 && to_kind == PyUnicode_4BYTE_KIND)
1026 {
1027 _PyUnicode_CONVERT_BYTES(
1028 Py_UCS1, Py_UCS4,
1029 PyUnicode_1BYTE_DATA(from) + from_start,
1030 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1031 PyUnicode_4BYTE_DATA(to) + to_start
1032 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001033 }
1034 else if (from_kind == PyUnicode_2BYTE_KIND
1035 && to_kind == PyUnicode_4BYTE_KIND)
1036 {
1037 _PyUnicode_CONVERT_BYTES(
1038 Py_UCS2, Py_UCS4,
1039 PyUnicode_2BYTE_DATA(from) + from_start,
1040 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1041 PyUnicode_4BYTE_DATA(to) + to_start
1042 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001043 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001044 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001045 /* check if max_char(from substring) <= max_char(to) */
1046 if (from_kind > to_kind
1047 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001048 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001049 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001050 /* slow path to check for character overflow */
1051 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001052 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001053 Py_ssize_t i;
1054
Victor Stinner56c161a2011-10-06 02:47:11 +02001055#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001056 for (i=0; i < how_many; i++) {
1057 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001058 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001059 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1060 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001061#else
1062 if (!check_maxchar) {
1063 for (i=0; i < how_many; i++) {
1064 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1065 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1066 }
1067 }
1068 else {
1069 for (i=0; i < how_many; i++) {
1070 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1071 if (ch > to_maxchar)
1072 return 1;
1073 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1074 }
1075 }
1076#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001077 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001078 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001079 assert(0 && "inconsistent state");
1080 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001081 }
1082 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001083 return 0;
1084}
1085
1086static void
1087copy_characters(PyObject *to, Py_ssize_t to_start,
1088 PyObject *from, Py_ssize_t from_start,
1089 Py_ssize_t how_many)
1090{
1091 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1092}
1093
1094Py_ssize_t
1095PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1096 PyObject *from, Py_ssize_t from_start,
1097 Py_ssize_t how_many)
1098{
1099 int err;
1100
1101 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1102 PyErr_BadInternalCall();
1103 return -1;
1104 }
1105
1106 if (PyUnicode_READY(from))
1107 return -1;
1108 if (PyUnicode_READY(to))
1109 return -1;
1110
1111 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1112 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1113 PyErr_Format(PyExc_SystemError,
1114 "Cannot write %zi characters at %zi "
1115 "in a string of %zi characters",
1116 how_many, to_start, PyUnicode_GET_LENGTH(to));
1117 return -1;
1118 }
1119
1120 if (how_many == 0)
1121 return 0;
1122
1123 if (_PyUnicode_Dirty(to))
1124 return -1;
1125
1126 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1127 if (err) {
1128 PyErr_Format(PyExc_SystemError,
1129 "Cannot copy %s characters "
1130 "into a string of %s characters",
1131 unicode_kind_name(from),
1132 unicode_kind_name(to));
1133 return -1;
1134 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001135 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001136}
1137
Victor Stinner17222162011-09-28 22:15:37 +02001138/* Find the maximum code point and count the number of surrogate pairs so a
1139 correct string length can be computed before converting a string to UCS4.
1140 This function counts single surrogates as a character and not as a pair.
1141
1142 Return 0 on success, or -1 on error. */
1143static int
1144find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1145 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001146{
1147 const wchar_t *iter;
1148
Victor Stinnerc53be962011-10-02 21:33:54 +02001149 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001150 *num_surrogates = 0;
1151 *maxchar = 0;
1152
1153 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001154 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001155 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001156#if SIZEOF_WCHAR_T != 2
1157 if (*maxchar >= 0x10000)
1158 return 0;
1159#endif
1160 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001161#if SIZEOF_WCHAR_T == 2
1162 if (*iter >= 0xD800 && *iter <= 0xDBFF
1163 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1164 {
1165 Py_UCS4 surrogate_val;
1166 surrogate_val = (((iter[0] & 0x3FF)<<10)
1167 | (iter[1] & 0x3FF)) + 0x10000;
1168 ++(*num_surrogates);
1169 if (surrogate_val > *maxchar)
1170 *maxchar = surrogate_val;
1171 iter += 2;
1172 }
1173 else
1174 iter++;
1175#else
1176 iter++;
1177#endif
1178 }
1179 return 0;
1180}
1181
1182#ifdef Py_DEBUG
1183int unicode_ready_calls = 0;
1184#endif
1185
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001186static int
1187unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001188{
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001189 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001190 wchar_t *end;
1191 Py_UCS4 maxchar = 0;
1192 Py_ssize_t num_surrogates;
1193#if SIZEOF_WCHAR_T == 2
1194 Py_ssize_t length_wo_surrogates;
1195#endif
1196
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001197 assert(p_obj != NULL);
1198 unicode = (PyUnicodeObject *)*p_obj;
1199
Georg Brandl7597add2011-10-05 16:36:47 +02001200 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001201 strings were created using _PyObject_New() and where no canonical
1202 representation (the str field) has been set yet aka strings
1203 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001204 assert(_PyUnicode_CHECK(unicode));
1205 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001206 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001207 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001208 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001209 /* Actually, it should neither be interned nor be anything else: */
1210 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001211
1212#ifdef Py_DEBUG
1213 ++unicode_ready_calls;
1214#endif
1215
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001216#ifdef Py_DEBUG
1217 assert(!replace || Py_REFCNT(unicode) == 1);
1218#else
1219 if (replace && Py_REFCNT(unicode) != 1)
1220 replace = 0;
1221#endif
1222 if (replace) {
1223 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1224 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1225 /* Optimization for empty strings */
1226 if (len == 0) {
1227 Py_INCREF(unicode_empty);
1228 Py_DECREF(*p_obj);
1229 *p_obj = unicode_empty;
1230 return 0;
1231 }
1232 if (len == 1 && wstr[0] < 256) {
1233 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1234 if (latin1_char == NULL)
1235 return -1;
1236 Py_DECREF(*p_obj);
1237 *p_obj = latin1_char;
1238 return 0;
1239 }
1240 }
1241
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001242 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001243 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001244 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001245 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001246
1247 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001248 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1249 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001250 PyErr_NoMemory();
1251 return -1;
1252 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001253 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001254 _PyUnicode_WSTR(unicode), end,
1255 PyUnicode_1BYTE_DATA(unicode));
1256 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1257 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1258 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1259 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001260 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001261 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001262 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001263 }
1264 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001265 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001266 _PyUnicode_UTF8(unicode) = NULL;
1267 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001268 }
1269 PyObject_FREE(_PyUnicode_WSTR(unicode));
1270 _PyUnicode_WSTR(unicode) = NULL;
1271 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1272 }
1273 /* In this case we might have to convert down from 4-byte native
1274 wchar_t to 2-byte unicode. */
1275 else if (maxchar < 65536) {
1276 assert(num_surrogates == 0 &&
1277 "FindMaxCharAndNumSurrogatePairs() messed up");
1278
Victor Stinner506f5922011-09-28 22:34:18 +02001279#if SIZEOF_WCHAR_T == 2
1280 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001281 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001282 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1283 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1284 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001285 _PyUnicode_UTF8(unicode) = NULL;
1286 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001287#else
1288 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001289 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001290 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001291 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001292 PyErr_NoMemory();
1293 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001294 }
Victor Stinner506f5922011-09-28 22:34:18 +02001295 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1296 _PyUnicode_WSTR(unicode), end,
1297 PyUnicode_2BYTE_DATA(unicode));
1298 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1299 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1300 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001301 _PyUnicode_UTF8(unicode) = NULL;
1302 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001303 PyObject_FREE(_PyUnicode_WSTR(unicode));
1304 _PyUnicode_WSTR(unicode) = NULL;
1305 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1306#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001307 }
1308 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1309 else {
1310#if SIZEOF_WCHAR_T == 2
1311 /* in case the native representation is 2-bytes, we need to allocate a
1312 new normalized 4-byte version. */
1313 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001314 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1315 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316 PyErr_NoMemory();
1317 return -1;
1318 }
1319 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1320 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001321 _PyUnicode_UTF8(unicode) = NULL;
1322 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001323 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1324 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001325 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001326 PyObject_FREE(_PyUnicode_WSTR(unicode));
1327 _PyUnicode_WSTR(unicode) = NULL;
1328 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1329#else
1330 assert(num_surrogates == 0);
1331
Victor Stinnerc3c74152011-10-02 20:39:55 +02001332 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001333 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001334 _PyUnicode_UTF8(unicode) = NULL;
1335 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001336 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1337#endif
1338 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1339 }
1340 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001341 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001342 return 0;
1343}
1344
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001345int
1346_PyUnicode_ReadyReplace(PyObject **op)
1347{
1348 return unicode_ready(op, 1);
1349}
1350
1351int
1352_PyUnicode_Ready(PyObject *op)
1353{
1354 return unicode_ready(&op, 0);
1355}
1356
Alexander Belopolsky40018472011-02-26 01:02:56 +00001357static void
1358unicode_dealloc(register PyUnicodeObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001359{
Walter Dörwald16807132007-05-25 13:52:07 +00001360 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001361 case SSTATE_NOT_INTERNED:
1362 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001363
Benjamin Peterson29060642009-01-31 22:14:21 +00001364 case SSTATE_INTERNED_MORTAL:
1365 /* revive dead object temporarily for DelItem */
1366 Py_REFCNT(unicode) = 3;
1367 if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
1368 Py_FatalError(
1369 "deletion of interned string failed");
1370 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001371
Benjamin Peterson29060642009-01-31 22:14:21 +00001372 case SSTATE_INTERNED_IMMORTAL:
1373 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001374
Benjamin Peterson29060642009-01-31 22:14:21 +00001375 default:
1376 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001377 }
1378
Victor Stinner03490912011-10-03 23:45:12 +02001379 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001380 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001381 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001382 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001383
1384 if (PyUnicode_IS_COMPACT(unicode)) {
1385 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001386 }
1387 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001388 if (_PyUnicode_DATA_ANY(unicode))
1389 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Benjamin Peterson29060642009-01-31 22:14:21 +00001390 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001391 }
1392}
1393
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001394#ifdef Py_DEBUG
1395static int
1396unicode_is_singleton(PyObject *unicode)
1397{
1398 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1399 if (unicode == unicode_empty)
1400 return 1;
1401 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1402 {
1403 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1404 if (ch < 256 && unicode_latin1[ch] == unicode)
1405 return 1;
1406 }
1407 return 0;
1408}
1409#endif
1410
Alexander Belopolsky40018472011-02-26 01:02:56 +00001411static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001412unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001413{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001414 if (Py_REFCNT(unicode) != 1)
1415 return 0;
1416 if (PyUnicode_CHECK_INTERNED(unicode))
1417 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001418#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001419 /* singleton refcount is greater than 1 */
1420 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001421#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001422 return 1;
1423}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001424
Victor Stinnerfe226c02011-10-03 03:52:20 +02001425static int
1426unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1427{
1428 PyObject *unicode;
1429 Py_ssize_t old_length;
1430
1431 assert(p_unicode != NULL);
1432 unicode = *p_unicode;
1433
1434 assert(unicode != NULL);
1435 assert(PyUnicode_Check(unicode));
1436 assert(0 <= length);
1437
Victor Stinner910337b2011-10-03 03:20:16 +02001438 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001439 old_length = PyUnicode_WSTR_LENGTH(unicode);
1440 else
1441 old_length = PyUnicode_GET_LENGTH(unicode);
1442 if (old_length == length)
1443 return 0;
1444
Victor Stinnerfe226c02011-10-03 03:52:20 +02001445 if (!unicode_resizable(unicode)) {
1446 PyObject *copy = resize_copy(unicode, length);
1447 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001448 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001449 Py_DECREF(*p_unicode);
1450 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001451 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001452 }
1453
Victor Stinnerfe226c02011-10-03 03:52:20 +02001454 if (PyUnicode_IS_COMPACT(unicode)) {
1455 *p_unicode = resize_compact(unicode, length);
1456 if (*p_unicode == NULL)
1457 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001458 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001459 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001460 }
1461 return resize_inplace((PyUnicodeObject*)unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001462}
1463
Alexander Belopolsky40018472011-02-26 01:02:56 +00001464int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001465PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001466{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001467 PyObject *unicode;
1468 if (p_unicode == NULL) {
1469 PyErr_BadInternalCall();
1470 return -1;
1471 }
1472 unicode = *p_unicode;
1473 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0
1474 || _PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND)
1475 {
1476 PyErr_BadInternalCall();
1477 return -1;
1478 }
1479 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001480}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001481
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001482static PyObject*
1483get_latin1_char(unsigned char ch)
1484{
Victor Stinnera464fc12011-10-02 20:39:30 +02001485 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001486 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001487 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001488 if (!unicode)
1489 return NULL;
1490 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001491 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001492 unicode_latin1[ch] = unicode;
1493 }
1494 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001495 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001496}
1497
Alexander Belopolsky40018472011-02-26 01:02:56 +00001498PyObject *
1499PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001500{
1501 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001502 Py_UCS4 maxchar = 0;
1503 Py_ssize_t num_surrogates;
1504
1505 if (u == NULL)
1506 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001507
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001508 /* If the Unicode data is known at construction time, we can apply
1509 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001510
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001511 /* Optimization for empty strings */
1512 if (size == 0 && unicode_empty != NULL) {
1513 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001514 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001515 }
Tim Petersced69f82003-09-16 20:30:58 +00001516
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001517 /* Single character Unicode objects in the Latin-1 range are
1518 shared when using this constructor */
1519 if (size == 1 && *u < 256)
1520 return get_latin1_char((unsigned char)*u);
1521
1522 /* If not empty and not single character, copy the Unicode data
1523 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001524 if (find_maxchar_surrogates(u, u + size,
1525 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001526 return NULL;
1527
1528 unicode = (PyUnicodeObject *) PyUnicode_New(size - num_surrogates,
1529 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001530 if (!unicode)
1531 return NULL;
1532
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001533 switch (PyUnicode_KIND(unicode)) {
1534 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001535 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001536 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1537 break;
1538 case PyUnicode_2BYTE_KIND:
1539#if Py_UNICODE_SIZE == 2
1540 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1541#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001542 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001543 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1544#endif
1545 break;
1546 case PyUnicode_4BYTE_KIND:
1547#if SIZEOF_WCHAR_T == 2
1548 /* This is the only case which has to process surrogates, thus
1549 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001550 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001551#else
1552 assert(num_surrogates == 0);
1553 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1554#endif
1555 break;
1556 default:
1557 assert(0 && "Impossible state");
1558 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001559
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001560 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001561 return (PyObject *)unicode;
1562}
1563
Alexander Belopolsky40018472011-02-26 01:02:56 +00001564PyObject *
1565PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001566{
1567 PyUnicodeObject *unicode;
Christian Heimes33fe8092008-04-13 13:53:33 +00001568
Benjamin Peterson14339b62009-01-31 16:36:08 +00001569 if (size < 0) {
1570 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001571 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001572 return NULL;
1573 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001574
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001575 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001576 some optimizations which share commonly used objects.
1577 Also, this means the input must be UTF-8, so fall back to the
1578 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001579 if (u != NULL) {
1580
Benjamin Peterson29060642009-01-31 22:14:21 +00001581 /* Optimization for empty strings */
1582 if (size == 0 && unicode_empty != NULL) {
1583 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001584 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001585 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001586
1587 /* Single characters are shared when using this constructor.
1588 Restrict to ASCII, since the input must be UTF-8. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001589 if (size == 1 && Py_CHARMASK(*u) < 128)
1590 return get_latin1_char(Py_CHARMASK(*u));
Martin v. Löwis9c121062007-08-05 20:26:11 +00001591
1592 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001593 }
1594
Walter Dörwald55507312007-05-18 13:12:10 +00001595 unicode = _PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001596 if (!unicode)
1597 return NULL;
1598
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001599 return (PyObject *)unicode;
1600}
1601
Alexander Belopolsky40018472011-02-26 01:02:56 +00001602PyObject *
1603PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001604{
1605 size_t size = strlen(u);
1606 if (size > PY_SSIZE_T_MAX) {
1607 PyErr_SetString(PyExc_OverflowError, "input too long");
1608 return NULL;
1609 }
1610
1611 return PyUnicode_FromStringAndSize(u, size);
1612}
1613
Victor Stinnere57b1c02011-09-28 22:20:48 +02001614static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001615unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001616{
Victor Stinner0617b6e2011-10-05 23:26:01 +02001617 PyObject *res;
1618#ifdef Py_DEBUG
1619 const unsigned char *p;
1620 const unsigned char *end = s + size;
1621 for (p=s; p < end; p++) {
1622 assert(*p < 128);
1623 }
1624#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001625 if (size == 1)
1626 return get_latin1_char(s[0]);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001627 res = PyUnicode_New(size, 127);
Victor Stinner702c7342011-10-05 13:50:52 +02001628 if (!res)
1629 return NULL;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001630 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
Victor Stinner702c7342011-10-05 13:50:52 +02001631 return res;
1632}
1633
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001634static Py_UCS4
1635kind_maxchar_limit(unsigned int kind)
1636{
1637 switch(kind) {
1638 case PyUnicode_1BYTE_KIND:
1639 return 0x80;
1640 case PyUnicode_2BYTE_KIND:
1641 return 0x100;
1642 case PyUnicode_4BYTE_KIND:
1643 return 0x10000;
1644 default:
1645 assert(0 && "invalid kind");
1646 return 0x10ffff;
1647 }
1648}
1649
Victor Stinner702c7342011-10-05 13:50:52 +02001650static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001651_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001652{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001653 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001654 unsigned char max_char = 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001655 Py_ssize_t i;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001656
1657 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001658 if (size == 1)
1659 return get_latin1_char(u[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001660 for (i = 0; i < size; i++) {
1661 if (u[i] & 0x80) {
Victor Stinnerb9275c12011-10-05 14:01:42 +02001662 max_char = 255;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001663 break;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001664 }
1665 }
Victor Stinnerb9275c12011-10-05 14:01:42 +02001666 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001667 if (!res)
1668 return NULL;
1669 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001670 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001671 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001672}
1673
Victor Stinnere57b1c02011-09-28 22:20:48 +02001674static PyObject*
1675_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001676{
1677 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001678 Py_UCS2 max_char = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001679 Py_ssize_t i;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001680
1681 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001682 if (size == 1 && u[0] < 256)
1683 return get_latin1_char(u[0]);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001684 for (i = 0; i < size; i++) {
1685 if (u[i] > max_char) {
1686 max_char = u[i];
1687 if (max_char >= 256)
1688 break;
1689 }
1690 }
1691 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001692 if (!res)
1693 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001694 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001695 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
1696 else
1697 for (i = 0; i < size; i++)
1698 PyUnicode_1BYTE_DATA(res)[i] = (Py_UCS1)u[i];
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001699 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001700 return res;
1701}
1702
Victor Stinnere57b1c02011-09-28 22:20:48 +02001703static PyObject*
1704_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001705{
1706 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001707 Py_UCS4 max_char = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001708 Py_ssize_t i;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001709
1710 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001711 if (size == 1 && u[0] < 256)
1712 return get_latin1_char(u[0]);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001713 for (i = 0; i < size; i++) {
1714 if (u[i] > max_char) {
1715 max_char = u[i];
1716 if (max_char >= 0x10000)
1717 break;
1718 }
1719 }
1720 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001721 if (!res)
1722 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001723 if (max_char >= 0x10000)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001724 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
1725 else {
1726 int kind = PyUnicode_KIND(res);
1727 void *data = PyUnicode_DATA(res);
1728 for (i = 0; i < size; i++)
1729 PyUnicode_WRITE(kind, data, i, u[i]);
1730 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001731 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001732 return res;
1733}
1734
1735PyObject*
1736PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1737{
1738 switch(kind) {
1739 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001740 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001741 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001742 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001743 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001744 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001745 default:
1746 assert(0 && "invalid kind");
1747 PyErr_SetString(PyExc_SystemError, "invalid kind");
1748 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001749 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001750}
1751
Victor Stinner25a4b292011-10-06 12:31:55 +02001752/* Ensure that a string uses the most efficient storage, if it is not the
1753 case: create a new string with of the right kind. Write NULL into *p_unicode
1754 on error. */
1755void
1756unicode_adjust_maxchar(PyObject **p_unicode)
1757{
1758 PyObject *unicode, *copy;
1759 Py_UCS4 max_char;
1760 Py_ssize_t i, len;
1761 unsigned int kind;
1762
1763 assert(p_unicode != NULL);
1764 unicode = *p_unicode;
1765 assert(PyUnicode_IS_READY(unicode));
1766 if (PyUnicode_IS_ASCII(unicode))
1767 return;
1768
1769 len = PyUnicode_GET_LENGTH(unicode);
1770 kind = PyUnicode_KIND(unicode);
1771 if (kind == PyUnicode_1BYTE_KIND) {
1772 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
1773 for (i = 0; i < len; i++) {
1774 if (u[i] & 0x80)
1775 return;
1776 }
1777 max_char = 127;
1778 }
1779 else if (kind == PyUnicode_2BYTE_KIND) {
1780 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
1781 max_char = 0;
1782 for (i = 0; i < len; i++) {
1783 if (u[i] > max_char) {
1784 max_char = u[i];
1785 if (max_char >= 256)
1786 return;
1787 }
1788 }
1789 }
1790 else {
Antoine Pitrou15a66cf2011-10-06 15:25:32 +02001791 const Py_UCS4 *u;
Victor Stinner25a4b292011-10-06 12:31:55 +02001792 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitrou15a66cf2011-10-06 15:25:32 +02001793 u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001794 max_char = 0;
1795 for (i = 0; i < len; i++) {
1796 if (u[i] > max_char) {
1797 max_char = u[i];
1798 if (max_char >= 0x10000)
1799 return;
1800 }
1801 }
1802 }
Victor Stinner200f2132011-10-06 13:27:56 +02001803 assert(max_char < PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinner25a4b292011-10-06 12:31:55 +02001804 copy = PyUnicode_New(len, max_char);
1805 copy_characters(copy, 0, unicode, 0, len);
1806 Py_DECREF(unicode);
1807 *p_unicode = copy;
1808}
1809
Victor Stinner034f6cf2011-09-30 02:26:44 +02001810PyObject*
1811PyUnicode_Copy(PyObject *unicode)
1812{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001813 Py_ssize_t size;
1814 PyObject *copy;
1815 void *data;
1816
Victor Stinner034f6cf2011-09-30 02:26:44 +02001817 if (!PyUnicode_Check(unicode)) {
1818 PyErr_BadInternalCall();
1819 return NULL;
1820 }
1821 if (PyUnicode_READY(unicode))
1822 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001823
1824 size = PyUnicode_GET_LENGTH(unicode);
1825 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1826 if (!copy)
1827 return NULL;
1828 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1829
1830 data = PyUnicode_DATA(unicode);
1831 switch (PyUnicode_KIND(unicode))
1832 {
1833 case PyUnicode_1BYTE_KIND:
1834 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1835 break;
1836 case PyUnicode_2BYTE_KIND:
1837 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1838 break;
1839 case PyUnicode_4BYTE_KIND:
1840 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1841 break;
1842 default:
1843 assert(0);
1844 break;
1845 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001846 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001847 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001848}
1849
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001850
Victor Stinnerbc603d12011-10-02 01:00:40 +02001851/* Widen Unicode objects to larger buffers. Don't write terminating null
1852 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001853
1854void*
1855_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1856{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001857 Py_ssize_t len;
1858 void *result;
1859 unsigned int skind;
1860
1861 if (PyUnicode_READY(s))
1862 return NULL;
1863
1864 len = PyUnicode_GET_LENGTH(s);
1865 skind = PyUnicode_KIND(s);
1866 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001867 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001868 return NULL;
1869 }
1870 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001871 case PyUnicode_2BYTE_KIND:
1872 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1873 if (!result)
1874 return PyErr_NoMemory();
1875 assert(skind == PyUnicode_1BYTE_KIND);
1876 _PyUnicode_CONVERT_BYTES(
1877 Py_UCS1, Py_UCS2,
1878 PyUnicode_1BYTE_DATA(s),
1879 PyUnicode_1BYTE_DATA(s) + len,
1880 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001881 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001882 case PyUnicode_4BYTE_KIND:
1883 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1884 if (!result)
1885 return PyErr_NoMemory();
1886 if (skind == PyUnicode_2BYTE_KIND) {
1887 _PyUnicode_CONVERT_BYTES(
1888 Py_UCS2, Py_UCS4,
1889 PyUnicode_2BYTE_DATA(s),
1890 PyUnicode_2BYTE_DATA(s) + len,
1891 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001892 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001893 else {
1894 assert(skind == PyUnicode_1BYTE_KIND);
1895 _PyUnicode_CONVERT_BYTES(
1896 Py_UCS1, Py_UCS4,
1897 PyUnicode_1BYTE_DATA(s),
1898 PyUnicode_1BYTE_DATA(s) + len,
1899 result);
1900 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001901 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001902 default:
1903 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001904 }
Victor Stinner01698042011-10-04 00:04:26 +02001905 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001906 return NULL;
1907}
1908
1909static Py_UCS4*
1910as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1911 int copy_null)
1912{
1913 int kind;
1914 void *data;
1915 Py_ssize_t len, targetlen;
1916 if (PyUnicode_READY(string) == -1)
1917 return NULL;
1918 kind = PyUnicode_KIND(string);
1919 data = PyUnicode_DATA(string);
1920 len = PyUnicode_GET_LENGTH(string);
1921 targetlen = len;
1922 if (copy_null)
1923 targetlen++;
1924 if (!target) {
1925 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
1926 PyErr_NoMemory();
1927 return NULL;
1928 }
1929 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
1930 if (!target) {
1931 PyErr_NoMemory();
1932 return NULL;
1933 }
1934 }
1935 else {
1936 if (targetsize < targetlen) {
1937 PyErr_Format(PyExc_SystemError,
1938 "string is longer than the buffer");
1939 if (copy_null && 0 < targetsize)
1940 target[0] = 0;
1941 return NULL;
1942 }
1943 }
1944 if (kind != PyUnicode_4BYTE_KIND) {
1945 Py_ssize_t i;
1946 for (i = 0; i < len; i++)
1947 target[i] = PyUnicode_READ(kind, data, i);
1948 }
1949 else
1950 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
1951 if (copy_null)
1952 target[len] = 0;
1953 return target;
1954}
1955
1956Py_UCS4*
1957PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1958 int copy_null)
1959{
1960 if (target == NULL || targetsize < 1) {
1961 PyErr_BadInternalCall();
1962 return NULL;
1963 }
1964 return as_ucs4(string, target, targetsize, copy_null);
1965}
1966
1967Py_UCS4*
1968PyUnicode_AsUCS4Copy(PyObject *string)
1969{
1970 return as_ucs4(string, NULL, 0, 1);
1971}
1972
1973#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00001974
Alexander Belopolsky40018472011-02-26 01:02:56 +00001975PyObject *
1976PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001977{
Guido van Rossumd57fd912000-03-10 22:53:23 +00001978 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00001979 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001980 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00001981 PyErr_BadInternalCall();
1982 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001983 }
1984
Martin v. Löwis790465f2008-04-05 20:41:37 +00001985 if (size == -1) {
1986 size = wcslen(w);
1987 }
1988
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001989 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001990}
1991
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001992#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00001993
Walter Dörwald346737f2007-05-31 10:44:43 +00001994static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001995makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
1996 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00001997{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001998 *fmt++ = '%';
1999 if (width) {
2000 if (zeropad)
2001 *fmt++ = '0';
2002 fmt += sprintf(fmt, "%d", width);
2003 }
2004 if (precision)
2005 fmt += sprintf(fmt, ".%d", precision);
2006 if (longflag)
2007 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002008 else if (longlongflag) {
2009 /* longlongflag should only ever be nonzero on machines with
2010 HAVE_LONG_LONG defined */
2011#ifdef HAVE_LONG_LONG
2012 char *f = PY_FORMAT_LONG_LONG;
2013 while (*f)
2014 *fmt++ = *f++;
2015#else
2016 /* we shouldn't ever get here */
2017 assert(0);
2018 *fmt++ = 'l';
2019#endif
2020 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002021 else if (size_tflag) {
2022 char *f = PY_FORMAT_SIZE_T;
2023 while (*f)
2024 *fmt++ = *f++;
2025 }
2026 *fmt++ = c;
2027 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002028}
2029
Victor Stinner96865452011-03-01 23:44:09 +00002030/* helper for PyUnicode_FromFormatV() */
2031
2032static const char*
2033parse_format_flags(const char *f,
2034 int *p_width, int *p_precision,
2035 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2036{
2037 int width, precision, longflag, longlongflag, size_tflag;
2038
2039 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2040 f++;
2041 width = 0;
2042 while (Py_ISDIGIT((unsigned)*f))
2043 width = (width*10) + *f++ - '0';
2044 precision = 0;
2045 if (*f == '.') {
2046 f++;
2047 while (Py_ISDIGIT((unsigned)*f))
2048 precision = (precision*10) + *f++ - '0';
2049 if (*f == '%') {
2050 /* "%.3%s" => f points to "3" */
2051 f--;
2052 }
2053 }
2054 if (*f == '\0') {
2055 /* bogus format "%.1" => go backward, f points to "1" */
2056 f--;
2057 }
2058 if (p_width != NULL)
2059 *p_width = width;
2060 if (p_precision != NULL)
2061 *p_precision = precision;
2062
2063 /* Handle %ld, %lu, %lld and %llu. */
2064 longflag = 0;
2065 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002066 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002067
2068 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002069 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002070 longflag = 1;
2071 ++f;
2072 }
2073#ifdef HAVE_LONG_LONG
2074 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002075 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002076 longlongflag = 1;
2077 f += 2;
2078 }
2079#endif
2080 }
2081 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002082 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002083 size_tflag = 1;
2084 ++f;
2085 }
2086 if (p_longflag != NULL)
2087 *p_longflag = longflag;
2088 if (p_longlongflag != NULL)
2089 *p_longlongflag = longlongflag;
2090 if (p_size_tflag != NULL)
2091 *p_size_tflag = size_tflag;
2092 return f;
2093}
2094
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002095/* maximum number of characters required for output of %ld. 21 characters
2096 allows for 64-bit integers (in decimal) and an optional sign. */
2097#define MAX_LONG_CHARS 21
2098/* maximum number of characters required for output of %lld.
2099 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2100 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2101#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2102
Walter Dörwaldd2034312007-05-18 16:29:38 +00002103PyObject *
2104PyUnicode_FromFormatV(const char *format, va_list vargs)
2105{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002106 va_list count;
2107 Py_ssize_t callcount = 0;
2108 PyObject **callresults = NULL;
2109 PyObject **callresult = NULL;
2110 Py_ssize_t n = 0;
2111 int width = 0;
2112 int precision = 0;
2113 int zeropad;
2114 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002115 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002116 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002117 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002118 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2119 Py_UCS4 argmaxchar;
2120 Py_ssize_t numbersize = 0;
2121 char *numberresults = NULL;
2122 char *numberresult = NULL;
2123 Py_ssize_t i;
2124 int kind;
2125 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002126
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002127 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002128 /* step 1: count the number of %S/%R/%A/%s format specifications
2129 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2130 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002131 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002132 * also estimate a upper bound for all the number formats in the string,
2133 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002134 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002135 for (f = format; *f; f++) {
2136 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002137 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002138 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2139 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2140 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2141 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002142
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002143 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002144#ifdef HAVE_LONG_LONG
2145 if (longlongflag) {
2146 if (width < MAX_LONG_LONG_CHARS)
2147 width = MAX_LONG_LONG_CHARS;
2148 }
2149 else
2150#endif
2151 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2152 including sign. Decimal takes the most space. This
2153 isn't enough for octal. If a width is specified we
2154 need more (which we allocate later). */
2155 if (width < MAX_LONG_CHARS)
2156 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002157
2158 /* account for the size + '\0' to separate numbers
2159 inside of the numberresults buffer */
2160 numbersize += (width + 1);
2161 }
2162 }
2163 else if ((unsigned char)*f > 127) {
2164 PyErr_Format(PyExc_ValueError,
2165 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2166 "string, got a non-ASCII byte: 0x%02x",
2167 (unsigned char)*f);
2168 return NULL;
2169 }
2170 }
2171 /* step 2: allocate memory for the results of
2172 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2173 if (callcount) {
2174 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2175 if (!callresults) {
2176 PyErr_NoMemory();
2177 return NULL;
2178 }
2179 callresult = callresults;
2180 }
2181 /* step 2.5: allocate memory for the results of formating numbers */
2182 if (numbersize) {
2183 numberresults = PyObject_Malloc(numbersize);
2184 if (!numberresults) {
2185 PyErr_NoMemory();
2186 goto fail;
2187 }
2188 numberresult = numberresults;
2189 }
2190
2191 /* step 3: format numbers and figure out how large a buffer we need */
2192 for (f = format; *f; f++) {
2193 if (*f == '%') {
2194 const char* p;
2195 int longflag;
2196 int longlongflag;
2197 int size_tflag;
2198 int numprinted;
2199
2200 p = f;
2201 zeropad = (f[1] == '0');
2202 f = parse_format_flags(f, &width, &precision,
2203 &longflag, &longlongflag, &size_tflag);
2204 switch (*f) {
2205 case 'c':
2206 {
2207 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002208 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002209 n++;
2210 break;
2211 }
2212 case '%':
2213 n++;
2214 break;
2215 case 'i':
2216 case 'd':
2217 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2218 width, precision, *f);
2219 if (longflag)
2220 numprinted = sprintf(numberresult, fmt,
2221 va_arg(count, long));
2222#ifdef HAVE_LONG_LONG
2223 else if (longlongflag)
2224 numprinted = sprintf(numberresult, fmt,
2225 va_arg(count, PY_LONG_LONG));
2226#endif
2227 else if (size_tflag)
2228 numprinted = sprintf(numberresult, fmt,
2229 va_arg(count, Py_ssize_t));
2230 else
2231 numprinted = sprintf(numberresult, fmt,
2232 va_arg(count, int));
2233 n += numprinted;
2234 /* advance by +1 to skip over the '\0' */
2235 numberresult += (numprinted + 1);
2236 assert(*(numberresult - 1) == '\0');
2237 assert(*(numberresult - 2) != '\0');
2238 assert(numprinted >= 0);
2239 assert(numberresult <= numberresults + numbersize);
2240 break;
2241 case 'u':
2242 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2243 width, precision, 'u');
2244 if (longflag)
2245 numprinted = sprintf(numberresult, fmt,
2246 va_arg(count, unsigned long));
2247#ifdef HAVE_LONG_LONG
2248 else if (longlongflag)
2249 numprinted = sprintf(numberresult, fmt,
2250 va_arg(count, unsigned PY_LONG_LONG));
2251#endif
2252 else if (size_tflag)
2253 numprinted = sprintf(numberresult, fmt,
2254 va_arg(count, size_t));
2255 else
2256 numprinted = sprintf(numberresult, fmt,
2257 va_arg(count, unsigned int));
2258 n += numprinted;
2259 numberresult += (numprinted + 1);
2260 assert(*(numberresult - 1) == '\0');
2261 assert(*(numberresult - 2) != '\0');
2262 assert(numprinted >= 0);
2263 assert(numberresult <= numberresults + numbersize);
2264 break;
2265 case 'x':
2266 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2267 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2268 n += numprinted;
2269 numberresult += (numprinted + 1);
2270 assert(*(numberresult - 1) == '\0');
2271 assert(*(numberresult - 2) != '\0');
2272 assert(numprinted >= 0);
2273 assert(numberresult <= numberresults + numbersize);
2274 break;
2275 case 'p':
2276 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2277 /* %p is ill-defined: ensure leading 0x. */
2278 if (numberresult[1] == 'X')
2279 numberresult[1] = 'x';
2280 else if (numberresult[1] != 'x') {
2281 memmove(numberresult + 2, numberresult,
2282 strlen(numberresult) + 1);
2283 numberresult[0] = '0';
2284 numberresult[1] = 'x';
2285 numprinted += 2;
2286 }
2287 n += numprinted;
2288 numberresult += (numprinted + 1);
2289 assert(*(numberresult - 1) == '\0');
2290 assert(*(numberresult - 2) != '\0');
2291 assert(numprinted >= 0);
2292 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002293 break;
2294 case 's':
2295 {
2296 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002297 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002298 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2299 if (!str)
2300 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002301 /* since PyUnicode_DecodeUTF8 returns already flexible
2302 unicode objects, there is no need to call ready on them */
2303 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002304 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002305 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002306 /* Remember the str and switch to the next slot */
2307 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002308 break;
2309 }
2310 case 'U':
2311 {
2312 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002313 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002314 if (PyUnicode_READY(obj) == -1)
2315 goto fail;
2316 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002317 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002318 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002319 break;
2320 }
2321 case 'V':
2322 {
2323 PyObject *obj = va_arg(count, PyObject *);
2324 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002325 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002326 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002327 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002328 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002329 if (PyUnicode_READY(obj) == -1)
2330 goto fail;
2331 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002332 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002333 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002334 *callresult++ = NULL;
2335 }
2336 else {
2337 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2338 if (!str_obj)
2339 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002340 if (PyUnicode_READY(str_obj)) {
2341 Py_DECREF(str_obj);
2342 goto fail;
2343 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002344 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002345 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002346 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002347 *callresult++ = str_obj;
2348 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002349 break;
2350 }
2351 case 'S':
2352 {
2353 PyObject *obj = va_arg(count, PyObject *);
2354 PyObject *str;
2355 assert(obj);
2356 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002357 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002358 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002359 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002360 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002361 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002362 /* Remember the str and switch to the next slot */
2363 *callresult++ = str;
2364 break;
2365 }
2366 case 'R':
2367 {
2368 PyObject *obj = va_arg(count, PyObject *);
2369 PyObject *repr;
2370 assert(obj);
2371 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002372 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002373 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002374 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002375 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002376 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002377 /* Remember the repr and switch to the next slot */
2378 *callresult++ = repr;
2379 break;
2380 }
2381 case 'A':
2382 {
2383 PyObject *obj = va_arg(count, PyObject *);
2384 PyObject *ascii;
2385 assert(obj);
2386 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002387 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002388 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002389 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002390 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002391 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002392 /* Remember the repr and switch to the next slot */
2393 *callresult++ = ascii;
2394 break;
2395 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002396 default:
2397 /* if we stumble upon an unknown
2398 formatting code, copy the rest of
2399 the format string to the output
2400 string. (we cannot just skip the
2401 code, since there's no way to know
2402 what's in the argument list) */
2403 n += strlen(p);
2404 goto expand;
2405 }
2406 } else
2407 n++;
2408 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002409 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002410 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002411 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002412 we don't have to resize the string.
2413 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002414 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002415 if (!string)
2416 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002417 kind = PyUnicode_KIND(string);
2418 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002419 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002420 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002421
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002422 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002423 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002424 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002425
2426 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002427 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2428 /* checking for == because the last argument could be a empty
2429 string, which causes i to point to end, the assert at the end of
2430 the loop */
2431 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002432
Benjamin Peterson14339b62009-01-31 16:36:08 +00002433 switch (*f) {
2434 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002435 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002436 const int ordinal = va_arg(vargs, int);
2437 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002438 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002439 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002440 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002441 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002442 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002443 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002444 case 'p':
2445 /* unused, since we already have the result */
2446 if (*f == 'p')
2447 (void) va_arg(vargs, void *);
2448 else
2449 (void) va_arg(vargs, int);
2450 /* extract the result from numberresults and append. */
2451 for (; *numberresult; ++i, ++numberresult)
2452 PyUnicode_WRITE(kind, data, i, *numberresult);
2453 /* skip over the separating '\0' */
2454 assert(*numberresult == '\0');
2455 numberresult++;
2456 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002457 break;
2458 case 's':
2459 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002460 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002461 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002462 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002463 size = PyUnicode_GET_LENGTH(*callresult);
2464 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002465 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002466 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002467 /* We're done with the unicode()/repr() => forget it */
2468 Py_DECREF(*callresult);
2469 /* switch to next unicode()/repr() result */
2470 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002471 break;
2472 }
2473 case 'U':
2474 {
2475 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002476 Py_ssize_t size;
2477 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2478 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002479 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002480 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002481 break;
2482 }
2483 case 'V':
2484 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002485 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002486 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002487 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002488 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002489 size = PyUnicode_GET_LENGTH(obj);
2490 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002491 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002492 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002493 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002494 size = PyUnicode_GET_LENGTH(*callresult);
2495 assert(PyUnicode_KIND(*callresult) <=
2496 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002497 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002498 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002499 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002500 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002501 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002502 break;
2503 }
2504 case 'S':
2505 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002506 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002507 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002508 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002509 /* unused, since we already have the result */
2510 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002511 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002512 copy_characters(string, i, *callresult, 0, size);
2513 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002514 /* We're done with the unicode()/repr() => forget it */
2515 Py_DECREF(*callresult);
2516 /* switch to next unicode()/repr() result */
2517 ++callresult;
2518 break;
2519 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002520 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002521 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002522 break;
2523 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002524 for (; *p; ++p, ++i)
2525 PyUnicode_WRITE(kind, data, i, *p);
2526 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002527 goto end;
2528 }
Victor Stinner1205f272010-09-11 00:54:47 +00002529 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002530 else {
2531 assert(i < PyUnicode_GET_LENGTH(string));
2532 PyUnicode_WRITE(kind, data, i++, *f);
2533 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002534 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002535 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002536
Benjamin Peterson29060642009-01-31 22:14:21 +00002537 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002538 if (callresults)
2539 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002540 if (numberresults)
2541 PyObject_Free(numberresults);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002542 assert(_PyUnicode_CheckConsistency(string, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002543 return (PyObject *)string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002544 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002545 if (callresults) {
2546 PyObject **callresult2 = callresults;
2547 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002548 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002549 ++callresult2;
2550 }
2551 PyObject_Free(callresults);
2552 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002553 if (numberresults)
2554 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002555 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002556}
2557
Walter Dörwaldd2034312007-05-18 16:29:38 +00002558PyObject *
2559PyUnicode_FromFormat(const char *format, ...)
2560{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002561 PyObject* ret;
2562 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002563
2564#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002565 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002566#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002567 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002568#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002569 ret = PyUnicode_FromFormatV(format, vargs);
2570 va_end(vargs);
2571 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002572}
2573
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002574#ifdef HAVE_WCHAR_H
2575
Victor Stinner5593d8a2010-10-02 11:11:27 +00002576/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2577 convert a Unicode object to a wide character string.
2578
Victor Stinnerd88d9832011-09-06 02:00:05 +02002579 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002580 character) required to convert the unicode object. Ignore size argument.
2581
Victor Stinnerd88d9832011-09-06 02:00:05 +02002582 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002583 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002584 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002585static Py_ssize_t
Victor Stinner137c34c2010-09-29 10:25:54 +00002586unicode_aswidechar(PyUnicodeObject *unicode,
2587 wchar_t *w,
2588 Py_ssize_t size)
2589{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002590 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002591 const wchar_t *wstr;
2592
2593 wstr = PyUnicode_AsUnicodeAndSize((PyObject *)unicode, &res);
2594 if (wstr == NULL)
2595 return -1;
2596
Victor Stinner5593d8a2010-10-02 11:11:27 +00002597 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002598 if (size > res)
2599 size = res + 1;
2600 else
2601 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002602 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002603 return res;
2604 }
2605 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002606 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002607}
2608
2609Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002610PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002611 wchar_t *w,
2612 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002613{
2614 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002615 PyErr_BadInternalCall();
2616 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002617 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002618 return unicode_aswidechar((PyUnicodeObject*)unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002619}
2620
Victor Stinner137c34c2010-09-29 10:25:54 +00002621wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002622PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002623 Py_ssize_t *size)
2624{
2625 wchar_t* buffer;
2626 Py_ssize_t buflen;
2627
2628 if (unicode == NULL) {
2629 PyErr_BadInternalCall();
2630 return NULL;
2631 }
2632
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002633 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002634 if (buflen == -1)
2635 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002636 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002637 PyErr_NoMemory();
2638 return NULL;
2639 }
2640
Victor Stinner137c34c2010-09-29 10:25:54 +00002641 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2642 if (buffer == NULL) {
2643 PyErr_NoMemory();
2644 return NULL;
2645 }
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002646 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002647 if (buflen == -1)
2648 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002649 if (size != NULL)
2650 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002651 return buffer;
2652}
2653
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002654#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002655
Alexander Belopolsky40018472011-02-26 01:02:56 +00002656PyObject *
2657PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002658{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002659 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002660 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002661 PyErr_SetString(PyExc_ValueError,
2662 "chr() arg not in range(0x110000)");
2663 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002664 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002665
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002666 if (ordinal < 256)
2667 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002668
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002669 v = PyUnicode_New(1, ordinal);
2670 if (v == NULL)
2671 return NULL;
2672 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002673 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002674 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002675}
2676
Alexander Belopolsky40018472011-02-26 01:02:56 +00002677PyObject *
2678PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002679{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002680 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002681 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002682 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002683 if (PyUnicode_READY(obj))
2684 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002685 Py_INCREF(obj);
2686 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002687 }
2688 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002689 /* For a Unicode subtype that's not a Unicode object,
2690 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002691 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002692 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002693 PyErr_Format(PyExc_TypeError,
2694 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002695 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002696 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002697}
2698
Alexander Belopolsky40018472011-02-26 01:02:56 +00002699PyObject *
2700PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002701 const char *encoding,
2702 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002703{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002704 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002705 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002706
Guido van Rossumd57fd912000-03-10 22:53:23 +00002707 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002708 PyErr_BadInternalCall();
2709 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002710 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002711
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002712 /* Decoding bytes objects is the most common case and should be fast */
2713 if (PyBytes_Check(obj)) {
2714 if (PyBytes_GET_SIZE(obj) == 0) {
2715 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002716 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002717 }
2718 else {
2719 v = PyUnicode_Decode(
2720 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2721 encoding, errors);
2722 }
2723 return v;
2724 }
2725
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002726 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002727 PyErr_SetString(PyExc_TypeError,
2728 "decoding str is not supported");
2729 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002730 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002731
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002732 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2733 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2734 PyErr_Format(PyExc_TypeError,
2735 "coercing to str: need bytes, bytearray "
2736 "or buffer-like object, %.80s found",
2737 Py_TYPE(obj)->tp_name);
2738 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002739 }
Tim Petersced69f82003-09-16 20:30:58 +00002740
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002741 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002742 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002743 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002744 }
Tim Petersced69f82003-09-16 20:30:58 +00002745 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002746 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002747
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002748 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002749 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002750}
2751
Victor Stinner600d3be2010-06-10 12:00:55 +00002752/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002753 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2754 1 on success. */
2755static int
2756normalize_encoding(const char *encoding,
2757 char *lower,
2758 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002759{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002760 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002761 char *l;
2762 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002763
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002764 e = encoding;
2765 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002766 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002767 while (*e) {
2768 if (l == l_end)
2769 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002770 if (Py_ISUPPER(*e)) {
2771 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002772 }
2773 else if (*e == '_') {
2774 *l++ = '-';
2775 e++;
2776 }
2777 else {
2778 *l++ = *e++;
2779 }
2780 }
2781 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002782 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002783}
2784
Alexander Belopolsky40018472011-02-26 01:02:56 +00002785PyObject *
2786PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002787 Py_ssize_t size,
2788 const char *encoding,
2789 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002790{
2791 PyObject *buffer = NULL, *unicode;
2792 Py_buffer info;
2793 char lower[11]; /* Enough for any encoding shortcut */
2794
2795 if (encoding == NULL)
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002796 return PyUnicode_DecodeUTF8(s, size, errors);
Fred Drakee4315f52000-05-09 19:53:39 +00002797
2798 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002799 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002800 if ((strcmp(lower, "utf-8") == 0) ||
2801 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002802 return PyUnicode_DecodeUTF8(s, size, errors);
2803 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002804 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002805 (strcmp(lower, "iso-8859-1") == 0))
2806 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002807#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002808 else if (strcmp(lower, "mbcs") == 0)
2809 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002810#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002811 else if (strcmp(lower, "ascii") == 0)
2812 return PyUnicode_DecodeASCII(s, size, errors);
2813 else if (strcmp(lower, "utf-16") == 0)
2814 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2815 else if (strcmp(lower, "utf-32") == 0)
2816 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2817 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002818
2819 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002820 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002821 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002822 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002823 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002824 if (buffer == NULL)
2825 goto onError;
2826 unicode = PyCodec_Decode(buffer, encoding, errors);
2827 if (unicode == NULL)
2828 goto onError;
2829 if (!PyUnicode_Check(unicode)) {
2830 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002831 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002832 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002833 Py_DECREF(unicode);
2834 goto onError;
2835 }
2836 Py_DECREF(buffer);
Victor Stinner17efeed2011-10-04 20:05:46 +02002837#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002838 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002839 Py_DECREF(unicode);
2840 return NULL;
2841 }
Victor Stinner17efeed2011-10-04 20:05:46 +02002842#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002843 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00002844 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002845
Benjamin Peterson29060642009-01-31 22:14:21 +00002846 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002847 Py_XDECREF(buffer);
2848 return NULL;
2849}
2850
Alexander Belopolsky40018472011-02-26 01:02:56 +00002851PyObject *
2852PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002853 const char *encoding,
2854 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002855{
2856 PyObject *v;
2857
2858 if (!PyUnicode_Check(unicode)) {
2859 PyErr_BadArgument();
2860 goto onError;
2861 }
2862
2863 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002864 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002865
2866 /* Decode via the codec registry */
2867 v = PyCodec_Decode(unicode, encoding, errors);
2868 if (v == NULL)
2869 goto onError;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002870 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002871 return v;
2872
Benjamin Peterson29060642009-01-31 22:14:21 +00002873 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002874 return NULL;
2875}
2876
Alexander Belopolsky40018472011-02-26 01:02:56 +00002877PyObject *
2878PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002879 const char *encoding,
2880 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002881{
2882 PyObject *v;
2883
2884 if (!PyUnicode_Check(unicode)) {
2885 PyErr_BadArgument();
2886 goto onError;
2887 }
2888
2889 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002890 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002891
2892 /* Decode via the codec registry */
2893 v = PyCodec_Decode(unicode, encoding, errors);
2894 if (v == NULL)
2895 goto onError;
2896 if (!PyUnicode_Check(v)) {
2897 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002898 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002899 Py_TYPE(v)->tp_name);
2900 Py_DECREF(v);
2901 goto onError;
2902 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002903 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002904 return v;
2905
Benjamin Peterson29060642009-01-31 22:14:21 +00002906 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002907 return NULL;
2908}
2909
Alexander Belopolsky40018472011-02-26 01:02:56 +00002910PyObject *
2911PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002912 Py_ssize_t size,
2913 const char *encoding,
2914 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002915{
2916 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002917
Guido van Rossumd57fd912000-03-10 22:53:23 +00002918 unicode = PyUnicode_FromUnicode(s, size);
2919 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002920 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002921 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
2922 Py_DECREF(unicode);
2923 return v;
2924}
2925
Alexander Belopolsky40018472011-02-26 01:02:56 +00002926PyObject *
2927PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002928 const char *encoding,
2929 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002930{
2931 PyObject *v;
2932
2933 if (!PyUnicode_Check(unicode)) {
2934 PyErr_BadArgument();
2935 goto onError;
2936 }
2937
2938 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002939 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002940
2941 /* Encode via the codec registry */
2942 v = PyCodec_Encode(unicode, encoding, errors);
2943 if (v == NULL)
2944 goto onError;
2945 return v;
2946
Benjamin Peterson29060642009-01-31 22:14:21 +00002947 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002948 return NULL;
2949}
2950
Victor Stinnerad158722010-10-27 00:25:46 +00002951PyObject *
2952PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00002953{
Victor Stinner99b95382011-07-04 14:23:54 +02002954#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00002955 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
2956 PyUnicode_GET_SIZE(unicode),
2957 NULL);
2958#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002959 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00002960#else
Victor Stinner793b5312011-04-27 00:24:21 +02002961 PyInterpreterState *interp = PyThreadState_GET()->interp;
2962 /* Bootstrap check: if the filesystem codec is implemented in Python, we
2963 cannot use it to encode and decode filenames before it is loaded. Load
2964 the Python codec requires to encode at least its own filename. Use the C
2965 version of the locale codec until the codec registry is initialized and
2966 the Python codec is loaded.
2967
2968 Py_FileSystemDefaultEncoding is shared between all interpreters, we
2969 cannot only rely on it: check also interp->fscodec_initialized for
2970 subinterpreters. */
2971 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00002972 return PyUnicode_AsEncodedString(unicode,
2973 Py_FileSystemDefaultEncoding,
2974 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00002975 }
2976 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002977 /* locale encoding with surrogateescape */
2978 wchar_t *wchar;
2979 char *bytes;
2980 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00002981 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002982
2983 wchar = PyUnicode_AsWideCharString(unicode, NULL);
2984 if (wchar == NULL)
2985 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00002986 bytes = _Py_wchar2char(wchar, &error_pos);
2987 if (bytes == NULL) {
2988 if (error_pos != (size_t)-1) {
2989 char *errmsg = strerror(errno);
2990 PyObject *exc = NULL;
2991 if (errmsg == NULL)
2992 errmsg = "Py_wchar2char() failed";
2993 raise_encode_exception(&exc,
2994 "filesystemencoding",
2995 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
2996 error_pos, error_pos+1,
2997 errmsg);
2998 Py_XDECREF(exc);
2999 }
3000 else
3001 PyErr_NoMemory();
3002 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003003 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003004 }
3005 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003006
3007 bytes_obj = PyBytes_FromString(bytes);
3008 PyMem_Free(bytes);
3009 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003010 }
Victor Stinnerad158722010-10-27 00:25:46 +00003011#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003012}
3013
Alexander Belopolsky40018472011-02-26 01:02:56 +00003014PyObject *
3015PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003016 const char *encoding,
3017 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003018{
3019 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003020 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003021
Guido van Rossumd57fd912000-03-10 22:53:23 +00003022 if (!PyUnicode_Check(unicode)) {
3023 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003024 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003025 }
Fred Drakee4315f52000-05-09 19:53:39 +00003026
Victor Stinner2f283c22011-03-02 01:21:46 +00003027 if (encoding == NULL) {
3028 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003029 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003030 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003031 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner2f283c22011-03-02 01:21:46 +00003032 }
Fred Drakee4315f52000-05-09 19:53:39 +00003033
3034 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003035 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003036 if ((strcmp(lower, "utf-8") == 0) ||
3037 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003038 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003039 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003040 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003041 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003042 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003043 }
Victor Stinner37296e82010-06-10 13:36:23 +00003044 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003045 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003046 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003047 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003048#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003049 else if (strcmp(lower, "mbcs") == 0)
3050 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3051 PyUnicode_GET_SIZE(unicode),
3052 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003053#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003054 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003055 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003056 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003057
3058 /* Encode via the codec registry */
3059 v = PyCodec_Encode(unicode, encoding, errors);
3060 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003061 return NULL;
3062
3063 /* The normal path */
3064 if (PyBytes_Check(v))
3065 return v;
3066
3067 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003068 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003069 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003070 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003071
3072 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3073 "encoder %s returned bytearray instead of bytes",
3074 encoding);
3075 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003076 Py_DECREF(v);
3077 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003078 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003079
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003080 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3081 Py_DECREF(v);
3082 return b;
3083 }
3084
3085 PyErr_Format(PyExc_TypeError,
3086 "encoder did not return a bytes object (type=%.400s)",
3087 Py_TYPE(v)->tp_name);
3088 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003089 return NULL;
3090}
3091
Alexander Belopolsky40018472011-02-26 01:02:56 +00003092PyObject *
3093PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003094 const char *encoding,
3095 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003096{
3097 PyObject *v;
3098
3099 if (!PyUnicode_Check(unicode)) {
3100 PyErr_BadArgument();
3101 goto onError;
3102 }
3103
3104 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003105 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003106
3107 /* Encode via the codec registry */
3108 v = PyCodec_Encode(unicode, encoding, errors);
3109 if (v == NULL)
3110 goto onError;
3111 if (!PyUnicode_Check(v)) {
3112 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003113 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003114 Py_TYPE(v)->tp_name);
3115 Py_DECREF(v);
3116 goto onError;
3117 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003118 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003119
Benjamin Peterson29060642009-01-31 22:14:21 +00003120 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003121 return NULL;
3122}
3123
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003124PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003125PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003126 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003127 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3128}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003129
Christian Heimes5894ba72007-11-04 11:43:14 +00003130PyObject*
3131PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3132{
Victor Stinner99b95382011-07-04 14:23:54 +02003133#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003134 return PyUnicode_DecodeMBCS(s, size, NULL);
3135#elif defined(__APPLE__)
3136 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3137#else
Victor Stinner793b5312011-04-27 00:24:21 +02003138 PyInterpreterState *interp = PyThreadState_GET()->interp;
3139 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3140 cannot use it to encode and decode filenames before it is loaded. Load
3141 the Python codec requires to encode at least its own filename. Use the C
3142 version of the locale codec until the codec registry is initialized and
3143 the Python codec is loaded.
3144
3145 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3146 cannot only rely on it: check also interp->fscodec_initialized for
3147 subinterpreters. */
3148 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003149 return PyUnicode_Decode(s, size,
3150 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003151 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003152 }
3153 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003154 /* locale encoding with surrogateescape */
3155 wchar_t *wchar;
3156 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003157 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003158
3159 if (s[size] != '\0' || size != strlen(s)) {
3160 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3161 return NULL;
3162 }
3163
Victor Stinner168e1172010-10-16 23:16:16 +00003164 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003165 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003166 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003167
Victor Stinner168e1172010-10-16 23:16:16 +00003168 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003169 PyMem_Free(wchar);
3170 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003171 }
Victor Stinnerad158722010-10-27 00:25:46 +00003172#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003173}
3174
Martin v. Löwis011e8422009-05-05 04:43:17 +00003175
3176int
3177PyUnicode_FSConverter(PyObject* arg, void* addr)
3178{
3179 PyObject *output = NULL;
3180 Py_ssize_t size;
3181 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003182 if (arg == NULL) {
3183 Py_DECREF(*(PyObject**)addr);
3184 return 1;
3185 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003186 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003187 output = arg;
3188 Py_INCREF(output);
3189 }
3190 else {
3191 arg = PyUnicode_FromObject(arg);
3192 if (!arg)
3193 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003194 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003195 Py_DECREF(arg);
3196 if (!output)
3197 return 0;
3198 if (!PyBytes_Check(output)) {
3199 Py_DECREF(output);
3200 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3201 return 0;
3202 }
3203 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003204 size = PyBytes_GET_SIZE(output);
3205 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003206 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003207 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003208 Py_DECREF(output);
3209 return 0;
3210 }
3211 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003212 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003213}
3214
3215
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003216int
3217PyUnicode_FSDecoder(PyObject* arg, void* addr)
3218{
3219 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003220 if (arg == NULL) {
3221 Py_DECREF(*(PyObject**)addr);
3222 return 1;
3223 }
3224 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003225 if (PyUnicode_READY(arg))
3226 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003227 output = arg;
3228 Py_INCREF(output);
3229 }
3230 else {
3231 arg = PyBytes_FromObject(arg);
3232 if (!arg)
3233 return 0;
3234 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3235 PyBytes_GET_SIZE(arg));
3236 Py_DECREF(arg);
3237 if (!output)
3238 return 0;
3239 if (!PyUnicode_Check(output)) {
3240 Py_DECREF(output);
3241 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3242 return 0;
3243 }
3244 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003245 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
3246 PyUnicode_GET_LENGTH(output), 0, 1)) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003247 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3248 Py_DECREF(output);
3249 return 0;
3250 }
3251 *(PyObject**)addr = output;
3252 return Py_CLEANUP_SUPPORTED;
3253}
3254
3255
Martin v. Löwis5b222132007-06-10 09:51:05 +00003256char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003257PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003258{
Christian Heimesf3863112007-11-22 07:46:41 +00003259 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003260 PyUnicodeObject *u = (PyUnicodeObject *)unicode;
3261
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003262 if (!PyUnicode_Check(unicode)) {
3263 PyErr_BadArgument();
3264 return NULL;
3265 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003266 if (PyUnicode_READY(u) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003267 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003268
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003269 if (PyUnicode_UTF8(unicode) == NULL) {
3270 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003271 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3272 if (bytes == NULL)
3273 return NULL;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003274 _PyUnicode_UTF8(u) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3275 if (_PyUnicode_UTF8(u) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003276 Py_DECREF(bytes);
3277 return NULL;
3278 }
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003279 _PyUnicode_UTF8_LENGTH(u) = PyBytes_GET_SIZE(bytes);
3280 Py_MEMCPY(_PyUnicode_UTF8(u), PyBytes_AS_STRING(bytes), _PyUnicode_UTF8_LENGTH(u) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003281 Py_DECREF(bytes);
3282 }
3283
3284 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003285 *psize = PyUnicode_UTF8_LENGTH(unicode);
3286 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003287}
3288
3289char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003290PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003291{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003292 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3293}
3294
3295#ifdef Py_DEBUG
3296int unicode_as_unicode_calls = 0;
3297#endif
3298
3299
3300Py_UNICODE *
3301PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3302{
3303 PyUnicodeObject *u;
3304 const unsigned char *one_byte;
3305#if SIZEOF_WCHAR_T == 4
3306 const Py_UCS2 *two_bytes;
3307#else
3308 const Py_UCS4 *four_bytes;
3309 const Py_UCS4 *ucs4_end;
3310 Py_ssize_t num_surrogates;
3311#endif
3312 wchar_t *w;
3313 wchar_t *wchar_end;
3314
3315 if (!PyUnicode_Check(unicode)) {
3316 PyErr_BadArgument();
3317 return NULL;
3318 }
3319 u = (PyUnicodeObject*)unicode;
3320 if (_PyUnicode_WSTR(u) == NULL) {
3321 /* Non-ASCII compact unicode object */
3322 assert(_PyUnicode_KIND(u) != 0);
3323 assert(PyUnicode_IS_READY(u));
3324
3325#ifdef Py_DEBUG
3326 ++unicode_as_unicode_calls;
3327#endif
3328
3329 if (PyUnicode_KIND(u) == PyUnicode_4BYTE_KIND) {
3330#if SIZEOF_WCHAR_T == 2
3331 four_bytes = PyUnicode_4BYTE_DATA(u);
3332 ucs4_end = four_bytes + _PyUnicode_LENGTH(u);
3333 num_surrogates = 0;
3334
3335 for (; four_bytes < ucs4_end; ++four_bytes) {
3336 if (*four_bytes > 0xFFFF)
3337 ++num_surrogates;
3338 }
3339
3340 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(
3341 sizeof(wchar_t) * (_PyUnicode_LENGTH(u) + 1 + num_surrogates));
3342 if (!_PyUnicode_WSTR(u)) {
3343 PyErr_NoMemory();
3344 return NULL;
3345 }
3346 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u) + num_surrogates;
3347
3348 w = _PyUnicode_WSTR(u);
3349 wchar_end = w + _PyUnicode_WSTR_LENGTH(u);
3350 four_bytes = PyUnicode_4BYTE_DATA(u);
3351 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3352 if (*four_bytes > 0xFFFF) {
3353 /* encode surrogate pair in this case */
3354 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3355 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3356 }
3357 else
3358 *w = *four_bytes;
3359
3360 if (w > wchar_end) {
3361 assert(0 && "Miscalculated string end");
3362 }
3363 }
3364 *w = 0;
3365#else
3366 /* sizeof(wchar_t) == 4 */
3367 Py_FatalError("Impossible unicode object state, wstr and str "
3368 "should share memory already.");
3369 return NULL;
3370#endif
3371 }
3372 else {
3373 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3374 (_PyUnicode_LENGTH(u) + 1));
3375 if (!_PyUnicode_WSTR(u)) {
3376 PyErr_NoMemory();
3377 return NULL;
3378 }
3379 if (!PyUnicode_IS_COMPACT_ASCII(u))
3380 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u);
3381 w = _PyUnicode_WSTR(u);
3382 wchar_end = w + _PyUnicode_LENGTH(u);
3383
3384 if (PyUnicode_KIND(u) == PyUnicode_1BYTE_KIND) {
3385 one_byte = PyUnicode_1BYTE_DATA(u);
3386 for (; w < wchar_end; ++one_byte, ++w)
3387 *w = *one_byte;
3388 /* null-terminate the wstr */
3389 *w = 0;
3390 }
3391 else if (PyUnicode_KIND(u) == PyUnicode_2BYTE_KIND) {
3392#if SIZEOF_WCHAR_T == 4
3393 two_bytes = PyUnicode_2BYTE_DATA(u);
3394 for (; w < wchar_end; ++two_bytes, ++w)
3395 *w = *two_bytes;
3396 /* null-terminate the wstr */
3397 *w = 0;
3398#else
3399 /* sizeof(wchar_t) == 2 */
3400 PyObject_FREE(_PyUnicode_WSTR(u));
3401 _PyUnicode_WSTR(u) = NULL;
3402 Py_FatalError("Impossible unicode object state, wstr "
3403 "and str should share memory already.");
3404 return NULL;
3405#endif
3406 }
3407 else {
3408 assert(0 && "This should never happen.");
3409 }
3410 }
3411 }
3412 if (size != NULL)
3413 *size = PyUnicode_WSTR_LENGTH(u);
3414 return _PyUnicode_WSTR(u);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003415}
3416
Alexander Belopolsky40018472011-02-26 01:02:56 +00003417Py_UNICODE *
3418PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003419{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003420 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003421}
3422
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003423
Alexander Belopolsky40018472011-02-26 01:02:56 +00003424Py_ssize_t
3425PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003426{
3427 if (!PyUnicode_Check(unicode)) {
3428 PyErr_BadArgument();
3429 goto onError;
3430 }
3431 return PyUnicode_GET_SIZE(unicode);
3432
Benjamin Peterson29060642009-01-31 22:14:21 +00003433 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003434 return -1;
3435}
3436
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003437Py_ssize_t
3438PyUnicode_GetLength(PyObject *unicode)
3439{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003440 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003441 PyErr_BadArgument();
3442 return -1;
3443 }
3444
3445 return PyUnicode_GET_LENGTH(unicode);
3446}
3447
3448Py_UCS4
3449PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3450{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003451 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3452 PyErr_BadArgument();
3453 return (Py_UCS4)-1;
3454 }
3455 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3456 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003457 return (Py_UCS4)-1;
3458 }
3459 return PyUnicode_READ_CHAR(unicode, index);
3460}
3461
3462int
3463PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3464{
3465 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003466 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003467 return -1;
3468 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003469 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3470 PyErr_SetString(PyExc_IndexError, "string index out of range");
3471 return -1;
3472 }
3473 if (_PyUnicode_Dirty(unicode))
3474 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003475 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3476 index, ch);
3477 return 0;
3478}
3479
Alexander Belopolsky40018472011-02-26 01:02:56 +00003480const char *
3481PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003482{
Victor Stinner42cb4622010-09-01 19:39:01 +00003483 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003484}
3485
Victor Stinner554f3f02010-06-16 23:33:54 +00003486/* create or adjust a UnicodeDecodeError */
3487static void
3488make_decode_exception(PyObject **exceptionObject,
3489 const char *encoding,
3490 const char *input, Py_ssize_t length,
3491 Py_ssize_t startpos, Py_ssize_t endpos,
3492 const char *reason)
3493{
3494 if (*exceptionObject == NULL) {
3495 *exceptionObject = PyUnicodeDecodeError_Create(
3496 encoding, input, length, startpos, endpos, reason);
3497 }
3498 else {
3499 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3500 goto onError;
3501 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3502 goto onError;
3503 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3504 goto onError;
3505 }
3506 return;
3507
3508onError:
3509 Py_DECREF(*exceptionObject);
3510 *exceptionObject = NULL;
3511}
3512
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003513/* error handling callback helper:
3514 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003515 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003516 and adjust various state variables.
3517 return 0 on success, -1 on error
3518*/
3519
Alexander Belopolsky40018472011-02-26 01:02:56 +00003520static int
3521unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003522 const char *encoding, const char *reason,
3523 const char **input, const char **inend, Py_ssize_t *startinpos,
3524 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3525 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003526{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003527 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003528
3529 PyObject *restuple = NULL;
3530 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003531 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003532 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003533 Py_ssize_t requiredsize;
3534 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003535 const Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003536 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003537 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003538 int res = -1;
3539
3540 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003541 *errorHandler = PyCodec_LookupError(errors);
3542 if (*errorHandler == NULL)
3543 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003544 }
3545
Victor Stinner554f3f02010-06-16 23:33:54 +00003546 make_decode_exception(exceptionObject,
3547 encoding,
3548 *input, *inend - *input,
3549 *startinpos, *endinpos,
3550 reason);
3551 if (*exceptionObject == NULL)
3552 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003553
3554 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3555 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003556 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003557 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003558 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003559 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003560 }
3561 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003562 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003563
3564 /* Copy back the bytes variables, which might have been modified by the
3565 callback */
3566 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3567 if (!inputobj)
3568 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003569 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003570 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003571 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003572 *input = PyBytes_AS_STRING(inputobj);
3573 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003574 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003575 /* we can DECREF safely, as the exception has another reference,
3576 so the object won't go away. */
3577 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003578
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003579 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003580 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003581 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003582 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3583 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003584 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003585
3586 /* need more space? (at least enough for what we
3587 have+the replacement+the rest of the string (starting
3588 at the new input position), so we won't have to check space
3589 when there are no errors in the rest of the string) */
3590 repptr = PyUnicode_AS_UNICODE(repunicode);
3591 repsize = PyUnicode_GET_SIZE(repunicode);
3592 requiredsize = *outpos + repsize + insize-newpos;
3593 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003594 if (requiredsize<2*outsize)
3595 requiredsize = 2*outsize;
Victor Stinnerfe226c02011-10-03 03:52:20 +02003596 if (PyUnicode_Resize((PyObject**)output, requiredsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003597 goto onError;
3598 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003599 }
3600 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003601 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003602 Py_UNICODE_COPY(*outptr, repptr, repsize);
3603 *outptr += repsize;
3604 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003605
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003606 /* we made it! */
3607 res = 0;
3608
Benjamin Peterson29060642009-01-31 22:14:21 +00003609 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003610 Py_XDECREF(restuple);
3611 return res;
3612}
3613
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003614/* --- UTF-7 Codec -------------------------------------------------------- */
3615
Antoine Pitrou244651a2009-05-04 18:56:13 +00003616/* See RFC2152 for details. We encode conservatively and decode liberally. */
3617
3618/* Three simple macros defining base-64. */
3619
3620/* Is c a base-64 character? */
3621
3622#define IS_BASE64(c) \
3623 (((c) >= 'A' && (c) <= 'Z') || \
3624 ((c) >= 'a' && (c) <= 'z') || \
3625 ((c) >= '0' && (c) <= '9') || \
3626 (c) == '+' || (c) == '/')
3627
3628/* given that c is a base-64 character, what is its base-64 value? */
3629
3630#define FROM_BASE64(c) \
3631 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3632 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3633 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3634 (c) == '+' ? 62 : 63)
3635
3636/* What is the base-64 character of the bottom 6 bits of n? */
3637
3638#define TO_BASE64(n) \
3639 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3640
3641/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3642 * decoded as itself. We are permissive on decoding; the only ASCII
3643 * byte not decoding to itself is the + which begins a base64
3644 * string. */
3645
3646#define DECODE_DIRECT(c) \
3647 ((c) <= 127 && (c) != '+')
3648
3649/* The UTF-7 encoder treats ASCII characters differently according to
3650 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3651 * the above). See RFC2152. This array identifies these different
3652 * sets:
3653 * 0 : "Set D"
3654 * alphanumeric and '(),-./:?
3655 * 1 : "Set O"
3656 * !"#$%&*;<=>@[]^_`{|}
3657 * 2 : "whitespace"
3658 * ht nl cr sp
3659 * 3 : special (must be base64 encoded)
3660 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3661 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003662
Tim Petersced69f82003-09-16 20:30:58 +00003663static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003664char utf7_category[128] = {
3665/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3666 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3667/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3668 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3669/* sp ! " # $ % & ' ( ) * + , - . / */
3670 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3671/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3672 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3673/* @ A B C D E F G H I J K L M N O */
3674 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3675/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3676 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3677/* ` a b c d e f g h i j k l m n o */
3678 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3679/* p q r s t u v w x y z { | } ~ del */
3680 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003681};
3682
Antoine Pitrou244651a2009-05-04 18:56:13 +00003683/* ENCODE_DIRECT: this character should be encoded as itself. The
3684 * answer depends on whether we are encoding set O as itself, and also
3685 * on whether we are encoding whitespace as itself. RFC2152 makes it
3686 * clear that the answers to these questions vary between
3687 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003688
Antoine Pitrou244651a2009-05-04 18:56:13 +00003689#define ENCODE_DIRECT(c, directO, directWS) \
3690 ((c) < 128 && (c) > 0 && \
3691 ((utf7_category[(c)] == 0) || \
3692 (directWS && (utf7_category[(c)] == 2)) || \
3693 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003694
Alexander Belopolsky40018472011-02-26 01:02:56 +00003695PyObject *
3696PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003697 Py_ssize_t size,
3698 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003699{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003700 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3701}
3702
Antoine Pitrou244651a2009-05-04 18:56:13 +00003703/* The decoder. The only state we preserve is our read position,
3704 * i.e. how many characters we have consumed. So if we end in the
3705 * middle of a shift sequence we have to back off the read position
3706 * and the output to the beginning of the sequence, otherwise we lose
3707 * all the shift state (seen bits, number of bits seen, high
3708 * surrogate). */
3709
Alexander Belopolsky40018472011-02-26 01:02:56 +00003710PyObject *
3711PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003712 Py_ssize_t size,
3713 const char *errors,
3714 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003715{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003716 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003717 Py_ssize_t startinpos;
3718 Py_ssize_t endinpos;
3719 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003720 const char *e;
3721 PyUnicodeObject *unicode;
3722 Py_UNICODE *p;
3723 const char *errmsg = "";
3724 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003725 Py_UNICODE *shiftOutStart;
3726 unsigned int base64bits = 0;
3727 unsigned long base64buffer = 0;
3728 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003729 PyObject *errorHandler = NULL;
3730 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003731
3732 unicode = _PyUnicode_New(size);
3733 if (!unicode)
3734 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003735 if (size == 0) {
3736 if (consumed)
3737 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003738 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003739 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003740
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003741 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitrou244651a2009-05-04 18:56:13 +00003742 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003743 e = s + size;
3744
3745 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003746 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003747 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003748 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003749
Antoine Pitrou244651a2009-05-04 18:56:13 +00003750 if (inShift) { /* in a base-64 section */
3751 if (IS_BASE64(ch)) { /* consume a base-64 character */
3752 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3753 base64bits += 6;
3754 s++;
3755 if (base64bits >= 16) {
3756 /* we have enough bits for a UTF-16 value */
3757 Py_UNICODE outCh = (Py_UNICODE)
3758 (base64buffer >> (base64bits-16));
3759 base64bits -= 16;
3760 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3761 if (surrogate) {
3762 /* expecting a second surrogate */
3763 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3764#ifdef Py_UNICODE_WIDE
3765 *p++ = (((surrogate & 0x3FF)<<10)
3766 | (outCh & 0x3FF)) + 0x10000;
3767#else
3768 *p++ = surrogate;
3769 *p++ = outCh;
3770#endif
3771 surrogate = 0;
3772 }
3773 else {
3774 surrogate = 0;
3775 errmsg = "second surrogate missing";
3776 goto utf7Error;
3777 }
3778 }
3779 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3780 /* first surrogate */
3781 surrogate = outCh;
3782 }
3783 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3784 errmsg = "unexpected second surrogate";
3785 goto utf7Error;
3786 }
3787 else {
3788 *p++ = outCh;
3789 }
3790 }
3791 }
3792 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003793 inShift = 0;
3794 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003795 if (surrogate) {
3796 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003797 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003798 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003799 if (base64bits > 0) { /* left-over bits */
3800 if (base64bits >= 6) {
3801 /* We've seen at least one base-64 character */
3802 errmsg = "partial character in shift sequence";
3803 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003804 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003805 else {
3806 /* Some bits remain; they should be zero */
3807 if (base64buffer != 0) {
3808 errmsg = "non-zero padding bits in shift sequence";
3809 goto utf7Error;
3810 }
3811 }
3812 }
3813 if (ch != '-') {
3814 /* '-' is absorbed; other terminating
3815 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003816 *p++ = ch;
3817 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003818 }
3819 }
3820 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003821 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003822 s++; /* consume '+' */
3823 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003824 s++;
3825 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00003826 }
3827 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003828 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003829 shiftOutStart = p;
3830 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003831 }
3832 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003833 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003834 *p++ = ch;
3835 s++;
3836 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003837 else {
3838 startinpos = s-starts;
3839 s++;
3840 errmsg = "unexpected special character";
3841 goto utf7Error;
3842 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003843 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003844utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003845 outpos = p-PyUnicode_AS_UNICODE(unicode);
3846 endinpos = s-starts;
3847 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003848 errors, &errorHandler,
3849 "utf7", errmsg,
3850 &starts, &e, &startinpos, &endinpos, &exc, &s,
3851 &unicode, &outpos, &p))
3852 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003853 }
3854
Antoine Pitrou244651a2009-05-04 18:56:13 +00003855 /* end of string */
3856
3857 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3858 /* if we're in an inconsistent state, that's an error */
3859 if (surrogate ||
3860 (base64bits >= 6) ||
3861 (base64bits > 0 && base64buffer != 0)) {
3862 outpos = p-PyUnicode_AS_UNICODE(unicode);
3863 endinpos = size;
3864 if (unicode_decode_call_errorhandler(
3865 errors, &errorHandler,
3866 "utf7", "unterminated shift sequence",
3867 &starts, &e, &startinpos, &endinpos, &exc, &s,
3868 &unicode, &outpos, &p))
3869 goto onError;
3870 if (s < e)
3871 goto restart;
3872 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003873 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003874
3875 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003876 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003877 if (inShift) {
3878 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003879 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003880 }
3881 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003882 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003883 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003884 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003885
Victor Stinnerfe226c02011-10-03 03:52:20 +02003886 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003887 goto onError;
3888
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003889 Py_XDECREF(errorHandler);
3890 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02003891#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02003892 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003893 Py_DECREF(unicode);
3894 return NULL;
3895 }
Victor Stinner17efeed2011-10-04 20:05:46 +02003896#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003897 assert(_PyUnicode_CheckConsistency(unicode, 1));
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003898 return (PyObject *)unicode;
3899
Benjamin Peterson29060642009-01-31 22:14:21 +00003900 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003901 Py_XDECREF(errorHandler);
3902 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003903 Py_DECREF(unicode);
3904 return NULL;
3905}
3906
3907
Alexander Belopolsky40018472011-02-26 01:02:56 +00003908PyObject *
3909PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003910 Py_ssize_t size,
3911 int base64SetO,
3912 int base64WhiteSpace,
3913 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003914{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003915 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003916 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003917 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003918 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003919 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003920 unsigned int base64bits = 0;
3921 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003922 char * out;
3923 char * start;
3924
3925 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003926 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003927
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003928 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003929 return PyErr_NoMemory();
3930
Antoine Pitrou244651a2009-05-04 18:56:13 +00003931 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003932 if (v == NULL)
3933 return NULL;
3934
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003935 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003936 for (;i < size; ++i) {
3937 Py_UNICODE ch = s[i];
3938
Antoine Pitrou244651a2009-05-04 18:56:13 +00003939 if (inShift) {
3940 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
3941 /* shifting out */
3942 if (base64bits) { /* output remaining bits */
3943 *out++ = TO_BASE64(base64buffer << (6-base64bits));
3944 base64buffer = 0;
3945 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003946 }
3947 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003948 /* Characters not in the BASE64 set implicitly unshift the sequence
3949 so no '-' is required, except if the character is itself a '-' */
3950 if (IS_BASE64(ch) || ch == '-') {
3951 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003952 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003953 *out++ = (char) ch;
3954 }
3955 else {
3956 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00003957 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003958 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003959 else { /* not in a shift sequence */
3960 if (ch == '+') {
3961 *out++ = '+';
3962 *out++ = '-';
3963 }
3964 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
3965 *out++ = (char) ch;
3966 }
3967 else {
3968 *out++ = '+';
3969 inShift = 1;
3970 goto encode_char;
3971 }
3972 }
3973 continue;
3974encode_char:
3975#ifdef Py_UNICODE_WIDE
3976 if (ch >= 0x10000) {
3977 /* code first surrogate */
3978 base64bits += 16;
3979 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
3980 while (base64bits >= 6) {
3981 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
3982 base64bits -= 6;
3983 }
3984 /* prepare second surrogate */
3985 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
3986 }
3987#endif
3988 base64bits += 16;
3989 base64buffer = (base64buffer << 16) | ch;
3990 while (base64bits >= 6) {
3991 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
3992 base64bits -= 6;
3993 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00003994 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003995 if (base64bits)
3996 *out++= TO_BASE64(base64buffer << (6-base64bits) );
3997 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003998 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003999 if (_PyBytes_Resize(&v, out - start) < 0)
4000 return NULL;
4001 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004002}
4003
Antoine Pitrou244651a2009-05-04 18:56:13 +00004004#undef IS_BASE64
4005#undef FROM_BASE64
4006#undef TO_BASE64
4007#undef DECODE_DIRECT
4008#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004009
Guido van Rossumd57fd912000-03-10 22:53:23 +00004010/* --- UTF-8 Codec -------------------------------------------------------- */
4011
Tim Petersced69f82003-09-16 20:30:58 +00004012static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004013char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004014 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4015 illegal prefix. See RFC 3629 for details */
4016 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4017 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004018 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004019 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4020 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4021 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4022 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004023 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4024 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 +00004025 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4026 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004027 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4028 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4029 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4030 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4031 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 +00004032};
4033
Alexander Belopolsky40018472011-02-26 01:02:56 +00004034PyObject *
4035PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004036 Py_ssize_t size,
4037 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004038{
Walter Dörwald69652032004-09-07 20:24:22 +00004039 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4040}
4041
Antoine Pitrouab868312009-01-10 15:40:25 +00004042/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4043#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4044
4045/* Mask to quickly check whether a C 'long' contains a
4046 non-ASCII, UTF8-encoded char. */
4047#if (SIZEOF_LONG == 8)
4048# define ASCII_CHAR_MASK 0x8080808080808080L
4049#elif (SIZEOF_LONG == 4)
4050# define ASCII_CHAR_MASK 0x80808080L
4051#else
4052# error C 'long' size should be either 4 or 8!
4053#endif
4054
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004055/* Scans a UTF-8 string and returns the maximum character to be expected,
4056 the size of the decoded unicode string and if any major errors were
4057 encountered.
4058
4059 This function does check basic UTF-8 sanity, it does however NOT CHECK
4060 if the string contains surrogates, and if all continuation bytes are
4061 within the correct ranges, these checks are performed in
4062 PyUnicode_DecodeUTF8Stateful.
4063
4064 If it sets has_errors to 1, it means the value of unicode_size and max_char
4065 will be bogus and you should not rely on useful information in them.
4066 */
4067static Py_UCS4
4068utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
4069 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
4070 int *has_errors)
4071{
4072 Py_ssize_t n;
4073 Py_ssize_t char_count = 0;
4074 Py_UCS4 max_char = 127, new_max;
4075 Py_UCS4 upper_bound;
4076 const unsigned char *p = (const unsigned char *)s;
4077 const unsigned char *end = p + string_size;
4078 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
4079 int err = 0;
4080
4081 for (; p < end && !err; ++p, ++char_count) {
4082 /* Only check value if it's not a ASCII char... */
4083 if (*p < 0x80) {
4084 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4085 an explanation. */
4086 if (!((size_t) p & LONG_PTR_MASK)) {
4087 /* Help register allocation */
4088 register const unsigned char *_p = p;
4089 while (_p < aligned_end) {
4090 unsigned long value = *(unsigned long *) _p;
4091 if (value & ASCII_CHAR_MASK)
4092 break;
4093 _p += SIZEOF_LONG;
4094 char_count += SIZEOF_LONG;
4095 }
4096 p = _p;
4097 if (p == end)
4098 break;
4099 }
4100 }
4101 if (*p >= 0x80) {
4102 n = utf8_code_length[*p];
4103 new_max = max_char;
4104 switch (n) {
4105 /* invalid start byte */
4106 case 0:
4107 err = 1;
4108 break;
4109 case 2:
4110 /* Code points between 0x00FF and 0x07FF inclusive.
4111 Approximate the upper bound of the code point,
4112 if this flips over 255 we can be sure it will be more
4113 than 255 and the string will need 2 bytes per code coint,
4114 if it stays under or equal to 255, we can be sure 1 byte
4115 is enough.
4116 ((*p & 0b00011111) << 6) | 0b00111111 */
4117 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
4118 if (max_char < upper_bound)
4119 new_max = upper_bound;
4120 /* Ensure we track at least that we left ASCII space. */
4121 if (new_max < 128)
4122 new_max = 128;
4123 break;
4124 case 3:
4125 /* Between 0x0FFF and 0xFFFF inclusive, so values are
4126 always > 255 and <= 65535 and will always need 2 bytes. */
4127 if (max_char < 65535)
4128 new_max = 65535;
4129 break;
4130 case 4:
4131 /* Code point will be above 0xFFFF for sure in this case. */
4132 new_max = 65537;
4133 break;
4134 /* Internal error, this should be caught by the first if */
4135 case 1:
4136 default:
4137 assert(0 && "Impossible case in utf8_max_char_and_size");
4138 err = 1;
4139 }
4140 /* Instead of number of overall bytes for this code point,
Georg Brandl7597add2011-10-05 16:36:47 +02004141 n contains the number of following bytes: */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004142 --n;
4143 /* Check if the follow up chars are all valid continuation bytes */
4144 if (n >= 1) {
4145 const unsigned char *cont;
4146 if ((p + n) >= end) {
4147 if (consumed == 0)
4148 /* incomplete data, non-incremental decoding */
4149 err = 1;
4150 break;
4151 }
4152 for (cont = p + 1; cont < (p + n); ++cont) {
4153 if ((*cont & 0xc0) != 0x80) {
4154 err = 1;
4155 break;
4156 }
4157 }
4158 p += n;
4159 }
4160 else
4161 err = 1;
4162 max_char = new_max;
4163 }
4164 }
4165
4166 if (unicode_size)
4167 *unicode_size = char_count;
4168 if (has_errors)
4169 *has_errors = err;
4170 return max_char;
4171}
4172
4173/* Similar to PyUnicode_WRITE but can also write into wstr field
4174 of the legacy unicode representation */
4175#define WRITE_FLEXIBLE_OR_WSTR(kind, buf, index, value) \
4176 do { \
4177 const int k_ = (kind); \
4178 if (k_ == PyUnicode_WCHAR_KIND) \
4179 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
4180 else if (k_ == PyUnicode_1BYTE_KIND) \
4181 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
4182 else if (k_ == PyUnicode_2BYTE_KIND) \
4183 ((Py_UCS2 *)(buf))[(index)] = (Py_UCS2)(value); \
4184 else \
4185 ((Py_UCS4 *)(buf))[(index)] = (Py_UCS4)(value); \
4186 } while (0)
4187
Alexander Belopolsky40018472011-02-26 01:02:56 +00004188PyObject *
4189PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004190 Py_ssize_t size,
4191 const char *errors,
4192 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004193{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004194 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004195 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004196 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004197 Py_ssize_t startinpos;
4198 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004199 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004200 PyUnicodeObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004201 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004202 PyObject *errorHandler = NULL;
4203 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004204 Py_UCS4 maxchar = 0;
4205 Py_ssize_t unicode_size;
4206 Py_ssize_t i;
4207 int kind;
4208 void *data;
4209 int has_errors;
4210 Py_UNICODE *error_outptr;
4211#if SIZEOF_WCHAR_T == 2
4212 Py_ssize_t wchar_offset = 0;
4213#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004214
Walter Dörwald69652032004-09-07 20:24:22 +00004215 if (size == 0) {
4216 if (consumed)
4217 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004218 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004219 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004220 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
4221 consumed, &has_errors);
4222 if (has_errors) {
4223 unicode = _PyUnicode_New(size);
4224 if (!unicode)
4225 return NULL;
4226 kind = PyUnicode_WCHAR_KIND;
4227 data = PyUnicode_AS_UNICODE(unicode);
4228 assert(data != NULL);
4229 }
4230 else {
4231 unicode = (PyUnicodeObject *)PyUnicode_New(unicode_size, maxchar);
4232 if (!unicode)
4233 return NULL;
4234 /* When the string is ASCII only, just use memcpy and return.
4235 unicode_size may be != size if there is an incomplete UTF-8
4236 sequence at the end of the ASCII block. */
4237 if (maxchar < 128 && size == unicode_size) {
4238 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4239 return (PyObject *)unicode;
4240 }
4241 kind = PyUnicode_KIND(unicode);
4242 data = PyUnicode_DATA(unicode);
4243 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004244 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004245 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004246 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004247 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004248
4249 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004250 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004251
4252 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004253 /* Fast path for runs of ASCII characters. Given that common UTF-8
4254 input will consist of an overwhelming majority of ASCII
4255 characters, we try to optimize for this case by checking
4256 as many characters as a C 'long' can contain.
4257 First, check if we can do an aligned read, as most CPUs have
4258 a penalty for unaligned reads.
4259 */
4260 if (!((size_t) s & LONG_PTR_MASK)) {
4261 /* Help register allocation */
4262 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004263 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004264 while (_s < aligned_end) {
4265 /* Read a whole long at a time (either 4 or 8 bytes),
4266 and do a fast unrolled copy if it only contains ASCII
4267 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004268 unsigned long value = *(unsigned long *) _s;
4269 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004270 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004271 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+0, _s[0]);
4272 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+1, _s[1]);
4273 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+2, _s[2]);
4274 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004275#if (SIZEOF_LONG == 8)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004276 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+4, _s[4]);
4277 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+5, _s[5]);
4278 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+6, _s[6]);
4279 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004280#endif
4281 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004282 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004283 }
4284 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004285 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004286 if (s == e)
4287 break;
4288 ch = (unsigned char)*s;
4289 }
4290 }
4291
4292 if (ch < 0x80) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004293 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004294 s++;
4295 continue;
4296 }
4297
4298 n = utf8_code_length[ch];
4299
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004300 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004301 if (consumed)
4302 break;
4303 else {
4304 errmsg = "unexpected end of data";
4305 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004306 endinpos = startinpos+1;
4307 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4308 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004309 goto utf8Error;
4310 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004311 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004312
4313 switch (n) {
4314
4315 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004316 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004317 startinpos = s-starts;
4318 endinpos = startinpos+1;
4319 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004320
4321 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004322 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004323 startinpos = s-starts;
4324 endinpos = startinpos+1;
4325 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004326
4327 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004328 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004329 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004330 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004331 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004332 goto utf8Error;
4333 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004334 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004335 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004336 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004337 break;
4338
4339 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004340 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4341 will result in surrogates in range d800-dfff. Surrogates are
4342 not valid UTF-8 so they are rejected.
4343 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4344 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004345 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004346 (s[2] & 0xc0) != 0x80 ||
4347 ((unsigned char)s[0] == 0xE0 &&
4348 (unsigned char)s[1] < 0xA0) ||
4349 ((unsigned char)s[0] == 0xED &&
4350 (unsigned char)s[1] > 0x9F)) {
4351 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004352 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004353 endinpos = startinpos + 1;
4354
4355 /* if s[1] first two bits are 1 and 0, then the invalid
4356 continuation byte is s[2], so increment endinpos by 1,
4357 if not, s[1] is invalid and endinpos doesn't need to
4358 be incremented. */
4359 if ((s[1] & 0xC0) == 0x80)
4360 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004361 goto utf8Error;
4362 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004363 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004364 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004365 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004366 break;
4367
4368 case 4:
4369 if ((s[1] & 0xc0) != 0x80 ||
4370 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004371 (s[3] & 0xc0) != 0x80 ||
4372 ((unsigned char)s[0] == 0xF0 &&
4373 (unsigned char)s[1] < 0x90) ||
4374 ((unsigned char)s[0] == 0xF4 &&
4375 (unsigned char)s[1] > 0x8F)) {
4376 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004377 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004378 endinpos = startinpos + 1;
4379 if ((s[1] & 0xC0) == 0x80) {
4380 endinpos++;
4381 if ((s[2] & 0xC0) == 0x80)
4382 endinpos++;
4383 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004384 goto utf8Error;
4385 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004386 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004387 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4388 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4389
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004390 /* If the string is flexible or we have native UCS-4, write
4391 directly.. */
4392 if (sizeof(Py_UNICODE) > 2 || kind != PyUnicode_WCHAR_KIND)
4393 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Tim Petersced69f82003-09-16 20:30:58 +00004394
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004395 else {
4396 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00004397
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004398 /* translate from 10000..10FFFF to 0..FFFF */
4399 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00004400
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004401 /* high surrogate = top 10 bits added to D800 */
4402 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4403 (Py_UNICODE)(0xD800 + (ch >> 10)));
4404
4405 /* low surrogate = bottom 10 bits added to DC00 */
4406 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4407 (Py_UNICODE)(0xDC00 + (ch & 0x03FF)));
4408 }
4409#if SIZEOF_WCHAR_T == 2
4410 wchar_offset++;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004411#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004412 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004413 }
4414 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004415 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004416
Benjamin Peterson29060642009-01-31 22:14:21 +00004417 utf8Error:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004418 /* If this is not yet a resizable string, make it one.. */
4419 if (kind != PyUnicode_WCHAR_KIND) {
4420 const Py_UNICODE *u;
4421 PyUnicodeObject *new_unicode = _PyUnicode_New(size);
4422 if (!new_unicode)
4423 goto onError;
4424 u = PyUnicode_AsUnicode((PyObject *)unicode);
4425 if (!u)
4426 goto onError;
4427#if SIZEOF_WCHAR_T == 2
4428 i += wchar_offset;
4429#endif
4430 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(new_unicode), u, i);
4431 Py_DECREF(unicode);
4432 unicode = new_unicode;
4433 kind = 0;
4434 data = PyUnicode_AS_UNICODE(new_unicode);
4435 assert(data != NULL);
4436 }
4437 error_outptr = PyUnicode_AS_UNICODE(unicode) + i;
Benjamin Peterson29060642009-01-31 22:14:21 +00004438 if (unicode_decode_call_errorhandler(
4439 errors, &errorHandler,
4440 "utf8", errmsg,
4441 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004442 &unicode, &i, &error_outptr))
Benjamin Peterson29060642009-01-31 22:14:21 +00004443 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004444 /* Update data because unicode_decode_call_errorhandler might have
4445 re-created or resized the unicode object. */
4446 data = PyUnicode_AS_UNICODE(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004447 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004448 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004449 /* Ensure the unicode_size calculation above was correct: */
4450 assert(kind == PyUnicode_WCHAR_KIND || i == unicode_size);
4451
Walter Dörwald69652032004-09-07 20:24:22 +00004452 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004453 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004454
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004455 /* Adjust length and ready string when it contained errors and
4456 is of the old resizable kind. */
4457 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004458 if (PyUnicode_Resize((PyObject**)&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004459 goto onError;
4460 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004461
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004462 Py_XDECREF(errorHandler);
4463 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004464#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004465 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004466 Py_DECREF(unicode);
4467 return NULL;
4468 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004469#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004470 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00004471 return (PyObject *)unicode;
4472
Benjamin Peterson29060642009-01-31 22:14:21 +00004473 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004474 Py_XDECREF(errorHandler);
4475 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004476 Py_DECREF(unicode);
4477 return NULL;
4478}
4479
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004480#undef WRITE_FLEXIBLE_OR_WSTR
Antoine Pitrouab868312009-01-10 15:40:25 +00004481
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004482#ifdef __APPLE__
4483
4484/* Simplified UTF-8 decoder using surrogateescape error handler,
4485 used to decode the command line arguments on Mac OS X. */
4486
4487wchar_t*
4488_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4489{
4490 int n;
4491 const char *e;
4492 wchar_t *unicode, *p;
4493
4494 /* Note: size will always be longer than the resulting Unicode
4495 character count */
4496 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4497 PyErr_NoMemory();
4498 return NULL;
4499 }
4500 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4501 if (!unicode)
4502 return NULL;
4503
4504 /* Unpack UTF-8 encoded data */
4505 p = unicode;
4506 e = s + size;
4507 while (s < e) {
4508 Py_UCS4 ch = (unsigned char)*s;
4509
4510 if (ch < 0x80) {
4511 *p++ = (wchar_t)ch;
4512 s++;
4513 continue;
4514 }
4515
4516 n = utf8_code_length[ch];
4517 if (s + n > e) {
4518 goto surrogateescape;
4519 }
4520
4521 switch (n) {
4522 case 0:
4523 case 1:
4524 goto surrogateescape;
4525
4526 case 2:
4527 if ((s[1] & 0xc0) != 0x80)
4528 goto surrogateescape;
4529 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4530 assert ((ch > 0x007F) && (ch <= 0x07FF));
4531 *p++ = (wchar_t)ch;
4532 break;
4533
4534 case 3:
4535 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4536 will result in surrogates in range d800-dfff. Surrogates are
4537 not valid UTF-8 so they are rejected.
4538 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4539 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4540 if ((s[1] & 0xc0) != 0x80 ||
4541 (s[2] & 0xc0) != 0x80 ||
4542 ((unsigned char)s[0] == 0xE0 &&
4543 (unsigned char)s[1] < 0xA0) ||
4544 ((unsigned char)s[0] == 0xED &&
4545 (unsigned char)s[1] > 0x9F)) {
4546
4547 goto surrogateescape;
4548 }
4549 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4550 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004551 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004552 break;
4553
4554 case 4:
4555 if ((s[1] & 0xc0) != 0x80 ||
4556 (s[2] & 0xc0) != 0x80 ||
4557 (s[3] & 0xc0) != 0x80 ||
4558 ((unsigned char)s[0] == 0xF0 &&
4559 (unsigned char)s[1] < 0x90) ||
4560 ((unsigned char)s[0] == 0xF4 &&
4561 (unsigned char)s[1] > 0x8F)) {
4562 goto surrogateescape;
4563 }
4564 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4565 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4566 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4567
4568#if SIZEOF_WCHAR_T == 4
4569 *p++ = (wchar_t)ch;
4570#else
4571 /* compute and append the two surrogates: */
4572
4573 /* translate from 10000..10FFFF to 0..FFFF */
4574 ch -= 0x10000;
4575
4576 /* high surrogate = top 10 bits added to D800 */
4577 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4578
4579 /* low surrogate = bottom 10 bits added to DC00 */
4580 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4581#endif
4582 break;
4583 }
4584 s += n;
4585 continue;
4586
4587 surrogateescape:
4588 *p++ = 0xDC00 + ch;
4589 s++;
4590 }
4591 *p = L'\0';
4592 return unicode;
4593}
4594
4595#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004596
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004597/* Primary internal function which creates utf8 encoded bytes objects.
4598
4599 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004600 and allocate exactly as much space needed at the end. Else allocate the
4601 maximum possible needed (4 result bytes per Unicode character), and return
4602 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004603*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004604PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004605_PyUnicode_AsUTF8String(PyObject *obj, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004606{
Tim Peters602f7402002-04-27 18:03:26 +00004607#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004608
Guido van Rossum98297ee2007-11-06 21:34:58 +00004609 Py_ssize_t i; /* index into s of next input byte */
4610 PyObject *result; /* result string object */
4611 char *p; /* next free byte in output buffer */
4612 Py_ssize_t nallocated; /* number of result bytes allocated */
4613 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004614 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004615 PyObject *errorHandler = NULL;
4616 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004617 int kind;
4618 void *data;
4619 Py_ssize_t size;
4620 PyUnicodeObject *unicode = (PyUnicodeObject *)obj;
4621#if SIZEOF_WCHAR_T == 2
4622 Py_ssize_t wchar_offset = 0;
4623#endif
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004624
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004625 if (!PyUnicode_Check(unicode)) {
4626 PyErr_BadArgument();
4627 return NULL;
4628 }
4629
4630 if (PyUnicode_READY(unicode) == -1)
4631 return NULL;
4632
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004633 if (PyUnicode_UTF8(unicode))
4634 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4635 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004636
4637 kind = PyUnicode_KIND(unicode);
4638 data = PyUnicode_DATA(unicode);
4639 size = PyUnicode_GET_LENGTH(unicode);
4640
Tim Peters602f7402002-04-27 18:03:26 +00004641 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004642
Tim Peters602f7402002-04-27 18:03:26 +00004643 if (size <= MAX_SHORT_UNICHARS) {
4644 /* Write into the stack buffer; nallocated can't overflow.
4645 * At the end, we'll allocate exactly as much heap space as it
4646 * turns out we need.
4647 */
4648 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004649 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004650 p = stackbuf;
4651 }
4652 else {
4653 /* Overallocate on the heap, and give the excess back at the end. */
4654 nallocated = size * 4;
4655 if (nallocated / 4 != size) /* overflow! */
4656 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004657 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004658 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004659 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004660 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004661 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004662
Tim Peters602f7402002-04-27 18:03:26 +00004663 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004664 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004665
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004666 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004667 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004668 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004669
Guido van Rossumd57fd912000-03-10 22:53:23 +00004670 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004671 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004672 *p++ = (char)(0xc0 | (ch >> 6));
4673 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004674 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004675 Py_ssize_t newpos;
4676 PyObject *rep;
4677 Py_ssize_t repsize, k, startpos;
4678 startpos = i-1;
4679#if SIZEOF_WCHAR_T == 2
4680 startpos += wchar_offset;
Victor Stinner445a6232010-04-22 20:01:57 +00004681#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004682 rep = unicode_encode_call_errorhandler(
4683 errors, &errorHandler, "utf-8", "surrogates not allowed",
4684 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
4685 &exc, startpos, startpos+1, &newpos);
4686 if (!rep)
4687 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004688
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004689 if (PyBytes_Check(rep))
4690 repsize = PyBytes_GET_SIZE(rep);
4691 else
4692 repsize = PyUnicode_GET_SIZE(rep);
4693
4694 if (repsize > 4) {
4695 Py_ssize_t offset;
4696
4697 if (result == NULL)
4698 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004699 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004700 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004701
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004702 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4703 /* integer overflow */
4704 PyErr_NoMemory();
4705 goto error;
4706 }
4707 nallocated += repsize - 4;
4708 if (result != NULL) {
4709 if (_PyBytes_Resize(&result, nallocated) < 0)
4710 goto error;
4711 } else {
4712 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004713 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004714 goto error;
4715 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4716 }
4717 p = PyBytes_AS_STRING(result) + offset;
4718 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004719
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004720 if (PyBytes_Check(rep)) {
4721 char *prep = PyBytes_AS_STRING(rep);
4722 for(k = repsize; k > 0; k--)
4723 *p++ = *prep++;
4724 } else /* rep is unicode */ {
4725 const Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
4726 Py_UNICODE c;
4727
4728 for(k=0; k<repsize; k++) {
4729 c = prep[k];
4730 if (0x80 <= c) {
4731 raise_encode_exception(&exc, "utf-8",
4732 PyUnicode_AS_UNICODE(unicode),
4733 size, i-1, i,
4734 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004735 goto error;
4736 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004737 *p++ = (char)prep[k];
Victor Stinner31be90b2010-04-22 19:38:16 +00004738 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004739 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004740 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004741 } else if (ch < 0x10000) {
4742 *p++ = (char)(0xe0 | (ch >> 12));
4743 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4744 *p++ = (char)(0x80 | (ch & 0x3f));
4745 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004746 /* Encode UCS4 Unicode ordinals */
4747 *p++ = (char)(0xf0 | (ch >> 18));
4748 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4749 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4750 *p++ = (char)(0x80 | (ch & 0x3f));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004751#if SIZEOF_WCHAR_T == 2
4752 wchar_offset++;
4753#endif
Tim Peters602f7402002-04-27 18:03:26 +00004754 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004755 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004756
Guido van Rossum98297ee2007-11-06 21:34:58 +00004757 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004758 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004759 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004760 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004761 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004762 }
4763 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004764 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004765 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004766 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004767 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004768 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004769
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004770 Py_XDECREF(errorHandler);
4771 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004772 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004773 error:
4774 Py_XDECREF(errorHandler);
4775 Py_XDECREF(exc);
4776 Py_XDECREF(result);
4777 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004778
Tim Peters602f7402002-04-27 18:03:26 +00004779#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004780}
4781
Alexander Belopolsky40018472011-02-26 01:02:56 +00004782PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004783PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4784 Py_ssize_t size,
4785 const char *errors)
4786{
4787 PyObject *v, *unicode;
4788
4789 unicode = PyUnicode_FromUnicode(s, size);
4790 if (unicode == NULL)
4791 return NULL;
4792 v = _PyUnicode_AsUTF8String(unicode, errors);
4793 Py_DECREF(unicode);
4794 return v;
4795}
4796
4797PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004798PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004799{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004800 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004801}
4802
Walter Dörwald41980ca2007-08-16 21:55:45 +00004803/* --- UTF-32 Codec ------------------------------------------------------- */
4804
4805PyObject *
4806PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004807 Py_ssize_t size,
4808 const char *errors,
4809 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004810{
4811 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4812}
4813
4814PyObject *
4815PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004816 Py_ssize_t size,
4817 const char *errors,
4818 int *byteorder,
4819 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004820{
4821 const char *starts = s;
4822 Py_ssize_t startinpos;
4823 Py_ssize_t endinpos;
4824 Py_ssize_t outpos;
4825 PyUnicodeObject *unicode;
4826 Py_UNICODE *p;
4827#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004828 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004829 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004830#else
4831 const int pairs = 0;
4832#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00004833 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004834 int bo = 0; /* assume native ordering by default */
4835 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004836 /* Offsets from q for retrieving bytes in the right order. */
4837#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4838 int iorder[] = {0, 1, 2, 3};
4839#else
4840 int iorder[] = {3, 2, 1, 0};
4841#endif
4842 PyObject *errorHandler = NULL;
4843 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004844
Walter Dörwald41980ca2007-08-16 21:55:45 +00004845 q = (unsigned char *)s;
4846 e = q + size;
4847
4848 if (byteorder)
4849 bo = *byteorder;
4850
4851 /* Check for BOM marks (U+FEFF) in the input and adjust current
4852 byte order setting accordingly. In native mode, the leading BOM
4853 mark is skipped, in all other modes, it is copied to the output
4854 stream as-is (giving a ZWNBSP character). */
4855 if (bo == 0) {
4856 if (size >= 4) {
4857 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004858 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004859#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004860 if (bom == 0x0000FEFF) {
4861 q += 4;
4862 bo = -1;
4863 }
4864 else if (bom == 0xFFFE0000) {
4865 q += 4;
4866 bo = 1;
4867 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004868#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004869 if (bom == 0x0000FEFF) {
4870 q += 4;
4871 bo = 1;
4872 }
4873 else if (bom == 0xFFFE0000) {
4874 q += 4;
4875 bo = -1;
4876 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004877#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004878 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004879 }
4880
4881 if (bo == -1) {
4882 /* force LE */
4883 iorder[0] = 0;
4884 iorder[1] = 1;
4885 iorder[2] = 2;
4886 iorder[3] = 3;
4887 }
4888 else if (bo == 1) {
4889 /* force BE */
4890 iorder[0] = 3;
4891 iorder[1] = 2;
4892 iorder[2] = 1;
4893 iorder[3] = 0;
4894 }
4895
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004896 /* On narrow builds we split characters outside the BMP into two
4897 codepoints => count how much extra space we need. */
4898#ifndef Py_UNICODE_WIDE
4899 for (qq = q; qq < e; qq += 4)
4900 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
4901 pairs++;
4902#endif
4903
4904 /* This might be one to much, because of a BOM */
4905 unicode = _PyUnicode_New((size+3)/4+pairs);
4906 if (!unicode)
4907 return NULL;
4908 if (size == 0)
4909 return (PyObject *)unicode;
4910
4911 /* Unpack UTF-32 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004912 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004913
Walter Dörwald41980ca2007-08-16 21:55:45 +00004914 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004915 Py_UCS4 ch;
4916 /* remaining bytes at the end? (size should be divisible by 4) */
4917 if (e-q<4) {
4918 if (consumed)
4919 break;
4920 errmsg = "truncated data";
4921 startinpos = ((const char *)q)-starts;
4922 endinpos = ((const char *)e)-starts;
4923 goto utf32Error;
4924 /* The remaining input chars are ignored if the callback
4925 chooses to skip the input */
4926 }
4927 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
4928 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004929
Benjamin Peterson29060642009-01-31 22:14:21 +00004930 if (ch >= 0x110000)
4931 {
4932 errmsg = "codepoint not in range(0x110000)";
4933 startinpos = ((const char *)q)-starts;
4934 endinpos = startinpos+4;
4935 goto utf32Error;
4936 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004937#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004938 if (ch >= 0x10000)
4939 {
4940 *p++ = 0xD800 | ((ch-0x10000) >> 10);
4941 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
4942 }
4943 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00004944#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004945 *p++ = ch;
4946 q += 4;
4947 continue;
4948 utf32Error:
4949 outpos = p-PyUnicode_AS_UNICODE(unicode);
4950 if (unicode_decode_call_errorhandler(
4951 errors, &errorHandler,
4952 "utf32", errmsg,
4953 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
4954 &unicode, &outpos, &p))
4955 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004956 }
4957
4958 if (byteorder)
4959 *byteorder = bo;
4960
4961 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004962 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004963
4964 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02004965 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004966 goto onError;
4967
4968 Py_XDECREF(errorHandler);
4969 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004970#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004971 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004972 Py_DECREF(unicode);
4973 return NULL;
4974 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004975#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004976 assert(_PyUnicode_CheckConsistency(unicode, 1));
Walter Dörwald41980ca2007-08-16 21:55:45 +00004977 return (PyObject *)unicode;
4978
Benjamin Peterson29060642009-01-31 22:14:21 +00004979 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00004980 Py_DECREF(unicode);
4981 Py_XDECREF(errorHandler);
4982 Py_XDECREF(exc);
4983 return NULL;
4984}
4985
4986PyObject *
4987PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004988 Py_ssize_t size,
4989 const char *errors,
4990 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004991{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004992 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004993 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004994 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004995#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004996 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004997#else
4998 const int pairs = 0;
4999#endif
5000 /* Offsets from p for storing byte pairs in the right order. */
5001#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5002 int iorder[] = {0, 1, 2, 3};
5003#else
5004 int iorder[] = {3, 2, 1, 0};
5005#endif
5006
Benjamin Peterson29060642009-01-31 22:14:21 +00005007#define STORECHAR(CH) \
5008 do { \
5009 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5010 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5011 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5012 p[iorder[0]] = (CH) & 0xff; \
5013 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005014 } while(0)
5015
5016 /* In narrow builds we can output surrogate pairs as one codepoint,
5017 so we need less space. */
5018#ifndef Py_UNICODE_WIDE
5019 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005020 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
5021 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
5022 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005023#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005024 nsize = (size - pairs + (byteorder == 0));
5025 bytesize = nsize * 4;
5026 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005027 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005028 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005029 if (v == NULL)
5030 return NULL;
5031
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005032 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005033 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005034 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005035 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005036 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005037
5038 if (byteorder == -1) {
5039 /* force LE */
5040 iorder[0] = 0;
5041 iorder[1] = 1;
5042 iorder[2] = 2;
5043 iorder[3] = 3;
5044 }
5045 else if (byteorder == 1) {
5046 /* force BE */
5047 iorder[0] = 3;
5048 iorder[1] = 2;
5049 iorder[2] = 1;
5050 iorder[3] = 0;
5051 }
5052
5053 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005054 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005055#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005056 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
5057 Py_UCS4 ch2 = *s;
5058 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
5059 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
5060 s++;
5061 size--;
5062 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005063 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005064#endif
5065 STORECHAR(ch);
5066 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005067
5068 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005069 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005070#undef STORECHAR
5071}
5072
Alexander Belopolsky40018472011-02-26 01:02:56 +00005073PyObject *
5074PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005075{
5076 if (!PyUnicode_Check(unicode)) {
5077 PyErr_BadArgument();
5078 return NULL;
5079 }
5080 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005081 PyUnicode_GET_SIZE(unicode),
5082 NULL,
5083 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005084}
5085
Guido van Rossumd57fd912000-03-10 22:53:23 +00005086/* --- UTF-16 Codec ------------------------------------------------------- */
5087
Tim Peters772747b2001-08-09 22:21:55 +00005088PyObject *
5089PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005090 Py_ssize_t size,
5091 const char *errors,
5092 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005093{
Walter Dörwald69652032004-09-07 20:24:22 +00005094 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5095}
5096
Antoine Pitrouab868312009-01-10 15:40:25 +00005097/* Two masks for fast checking of whether a C 'long' may contain
5098 UTF16-encoded surrogate characters. This is an efficient heuristic,
5099 assuming that non-surrogate characters with a code point >= 0x8000 are
5100 rare in most input.
5101 FAST_CHAR_MASK is used when the input is in native byte ordering,
5102 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005103*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005104#if (SIZEOF_LONG == 8)
5105# define FAST_CHAR_MASK 0x8000800080008000L
5106# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5107#elif (SIZEOF_LONG == 4)
5108# define FAST_CHAR_MASK 0x80008000L
5109# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5110#else
5111# error C 'long' size should be either 4 or 8!
5112#endif
5113
Walter Dörwald69652032004-09-07 20:24:22 +00005114PyObject *
5115PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005116 Py_ssize_t size,
5117 const char *errors,
5118 int *byteorder,
5119 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005120{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005121 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005122 Py_ssize_t startinpos;
5123 Py_ssize_t endinpos;
5124 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005125 PyUnicodeObject *unicode;
5126 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00005127 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005128 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005129 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005130 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005131 /* Offsets from q for retrieving byte pairs in the right order. */
5132#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5133 int ihi = 1, ilo = 0;
5134#else
5135 int ihi = 0, ilo = 1;
5136#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005137 PyObject *errorHandler = NULL;
5138 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005139
5140 /* Note: size will always be longer than the resulting Unicode
5141 character count */
5142 unicode = _PyUnicode_New(size);
5143 if (!unicode)
5144 return NULL;
5145 if (size == 0)
5146 return (PyObject *)unicode;
5147
5148 /* Unpack UTF-16 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005149 p = PyUnicode_AS_UNICODE(unicode);
Tim Peters772747b2001-08-09 22:21:55 +00005150 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005151 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005152
5153 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005154 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005155
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005156 /* Check for BOM marks (U+FEFF) in the input and adjust current
5157 byte order setting accordingly. In native mode, the leading BOM
5158 mark is skipped, in all other modes, it is copied to the output
5159 stream as-is (giving a ZWNBSP character). */
5160 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005161 if (size >= 2) {
5162 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005163#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005164 if (bom == 0xFEFF) {
5165 q += 2;
5166 bo = -1;
5167 }
5168 else if (bom == 0xFFFE) {
5169 q += 2;
5170 bo = 1;
5171 }
Tim Petersced69f82003-09-16 20:30:58 +00005172#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005173 if (bom == 0xFEFF) {
5174 q += 2;
5175 bo = 1;
5176 }
5177 else if (bom == 0xFFFE) {
5178 q += 2;
5179 bo = -1;
5180 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005181#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005182 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005183 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005184
Tim Peters772747b2001-08-09 22:21:55 +00005185 if (bo == -1) {
5186 /* force LE */
5187 ihi = 1;
5188 ilo = 0;
5189 }
5190 else if (bo == 1) {
5191 /* force BE */
5192 ihi = 0;
5193 ilo = 1;
5194 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005195#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5196 native_ordering = ilo < ihi;
5197#else
5198 native_ordering = ilo > ihi;
5199#endif
Tim Peters772747b2001-08-09 22:21:55 +00005200
Antoine Pitrouab868312009-01-10 15:40:25 +00005201 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005202 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005203 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005204 /* First check for possible aligned read of a C 'long'. Unaligned
5205 reads are more expensive, better to defer to another iteration. */
5206 if (!((size_t) q & LONG_PTR_MASK)) {
5207 /* Fast path for runs of non-surrogate chars. */
5208 register const unsigned char *_q = q;
5209 Py_UNICODE *_p = p;
5210 if (native_ordering) {
5211 /* Native ordering is simple: as long as the input cannot
5212 possibly contain a surrogate char, do an unrolled copy
5213 of several 16-bit code points to the target object.
5214 The non-surrogate check is done on several input bytes
5215 at a time (as many as a C 'long' can contain). */
5216 while (_q < aligned_end) {
5217 unsigned long data = * (unsigned long *) _q;
5218 if (data & FAST_CHAR_MASK)
5219 break;
5220 _p[0] = ((unsigned short *) _q)[0];
5221 _p[1] = ((unsigned short *) _q)[1];
5222#if (SIZEOF_LONG == 8)
5223 _p[2] = ((unsigned short *) _q)[2];
5224 _p[3] = ((unsigned short *) _q)[3];
5225#endif
5226 _q += SIZEOF_LONG;
5227 _p += SIZEOF_LONG / 2;
5228 }
5229 }
5230 else {
5231 /* Byteswapped ordering is similar, but we must decompose
5232 the copy bytewise, and take care of zero'ing out the
5233 upper bytes if the target object is in 32-bit units
5234 (that is, in UCS-4 builds). */
5235 while (_q < aligned_end) {
5236 unsigned long data = * (unsigned long *) _q;
5237 if (data & SWAPPED_FAST_CHAR_MASK)
5238 break;
5239 /* Zero upper bytes in UCS-4 builds */
5240#if (Py_UNICODE_SIZE > 2)
5241 _p[0] = 0;
5242 _p[1] = 0;
5243#if (SIZEOF_LONG == 8)
5244 _p[2] = 0;
5245 _p[3] = 0;
5246#endif
5247#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005248 /* Issue #4916; UCS-4 builds on big endian machines must
5249 fill the two last bytes of each 4-byte unit. */
5250#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
5251# define OFF 2
5252#else
5253# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00005254#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005255 ((unsigned char *) _p)[OFF + 1] = _q[0];
5256 ((unsigned char *) _p)[OFF + 0] = _q[1];
5257 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
5258 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
5259#if (SIZEOF_LONG == 8)
5260 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
5261 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
5262 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
5263 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
5264#endif
5265#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00005266 _q += SIZEOF_LONG;
5267 _p += SIZEOF_LONG / 2;
5268 }
5269 }
5270 p = _p;
5271 q = _q;
5272 if (q >= e)
5273 break;
5274 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005275 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005276
Benjamin Peterson14339b62009-01-31 16:36:08 +00005277 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005278
5279 if (ch < 0xD800 || ch > 0xDFFF) {
5280 *p++ = ch;
5281 continue;
5282 }
5283
5284 /* UTF-16 code pair: */
5285 if (q > e) {
5286 errmsg = "unexpected end of data";
5287 startinpos = (((const char *)q) - 2) - starts;
5288 endinpos = ((const char *)e) + 1 - starts;
5289 goto utf16Error;
5290 }
5291 if (0xD800 <= ch && ch <= 0xDBFF) {
5292 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
5293 q += 2;
5294 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00005295#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005296 *p++ = ch;
5297 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005298#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005299 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005300#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005301 continue;
5302 }
5303 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005304 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005305 startinpos = (((const char *)q)-4)-starts;
5306 endinpos = startinpos+2;
5307 goto utf16Error;
5308 }
5309
Benjamin Peterson14339b62009-01-31 16:36:08 +00005310 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005311 errmsg = "illegal encoding";
5312 startinpos = (((const char *)q)-2)-starts;
5313 endinpos = startinpos+2;
5314 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005315
Benjamin Peterson29060642009-01-31 22:14:21 +00005316 utf16Error:
5317 outpos = p - PyUnicode_AS_UNICODE(unicode);
5318 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005319 errors,
5320 &errorHandler,
5321 "utf16", errmsg,
5322 &starts,
5323 (const char **)&e,
5324 &startinpos,
5325 &endinpos,
5326 &exc,
5327 (const char **)&q,
5328 &unicode,
5329 &outpos,
5330 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00005331 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005332 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005333 /* remaining byte at the end? (size should be even) */
5334 if (e == q) {
5335 if (!consumed) {
5336 errmsg = "truncated data";
5337 startinpos = ((const char *)q) - starts;
5338 endinpos = ((const char *)e) + 1 - starts;
5339 outpos = p - PyUnicode_AS_UNICODE(unicode);
5340 if (unicode_decode_call_errorhandler(
5341 errors,
5342 &errorHandler,
5343 "utf16", errmsg,
5344 &starts,
5345 (const char **)&e,
5346 &startinpos,
5347 &endinpos,
5348 &exc,
5349 (const char **)&q,
5350 &unicode,
5351 &outpos,
5352 &p))
5353 goto onError;
5354 /* The remaining input chars are ignored if the callback
5355 chooses to skip the input */
5356 }
5357 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005358
5359 if (byteorder)
5360 *byteorder = bo;
5361
Walter Dörwald69652032004-09-07 20:24:22 +00005362 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005363 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005364
Guido van Rossumd57fd912000-03-10 22:53:23 +00005365 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02005366 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005367 goto onError;
5368
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005369 Py_XDECREF(errorHandler);
5370 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005371#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005372 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005373 Py_DECREF(unicode);
5374 return NULL;
5375 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005376#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005377 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00005378 return (PyObject *)unicode;
5379
Benjamin Peterson29060642009-01-31 22:14:21 +00005380 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005381 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005382 Py_XDECREF(errorHandler);
5383 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005384 return NULL;
5385}
5386
Antoine Pitrouab868312009-01-10 15:40:25 +00005387#undef FAST_CHAR_MASK
5388#undef SWAPPED_FAST_CHAR_MASK
5389
Tim Peters772747b2001-08-09 22:21:55 +00005390PyObject *
5391PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005392 Py_ssize_t size,
5393 const char *errors,
5394 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005395{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005396 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005397 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005398 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005399#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005400 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005401#else
5402 const int pairs = 0;
5403#endif
Tim Peters772747b2001-08-09 22:21:55 +00005404 /* Offsets from p for storing byte pairs in the right order. */
5405#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5406 int ihi = 1, ilo = 0;
5407#else
5408 int ihi = 0, ilo = 1;
5409#endif
5410
Benjamin Peterson29060642009-01-31 22:14:21 +00005411#define STORECHAR(CH) \
5412 do { \
5413 p[ihi] = ((CH) >> 8) & 0xff; \
5414 p[ilo] = (CH) & 0xff; \
5415 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005416 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005417
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005418#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005419 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005420 if (s[i] >= 0x10000)
5421 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005422#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005423 /* 2 * (size + pairs + (byteorder == 0)) */
5424 if (size > PY_SSIZE_T_MAX ||
5425 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005426 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005427 nsize = size + pairs + (byteorder == 0);
5428 bytesize = nsize * 2;
5429 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005430 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005431 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005432 if (v == NULL)
5433 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005434
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005435 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005436 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005437 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005438 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005439 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005440
5441 if (byteorder == -1) {
5442 /* force LE */
5443 ihi = 1;
5444 ilo = 0;
5445 }
5446 else if (byteorder == 1) {
5447 /* force BE */
5448 ihi = 0;
5449 ilo = 1;
5450 }
5451
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005452 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005453 Py_UNICODE ch = *s++;
5454 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005455#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005456 if (ch >= 0x10000) {
5457 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5458 ch = 0xD800 | ((ch-0x10000) >> 10);
5459 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005460#endif
Tim Peters772747b2001-08-09 22:21:55 +00005461 STORECHAR(ch);
5462 if (ch2)
5463 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005464 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005465
5466 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005467 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005468#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005469}
5470
Alexander Belopolsky40018472011-02-26 01:02:56 +00005471PyObject *
5472PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005473{
5474 if (!PyUnicode_Check(unicode)) {
5475 PyErr_BadArgument();
5476 return NULL;
5477 }
5478 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005479 PyUnicode_GET_SIZE(unicode),
5480 NULL,
5481 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005482}
5483
5484/* --- Unicode Escape Codec ----------------------------------------------- */
5485
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005486/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5487 if all the escapes in the string make it still a valid ASCII string.
5488 Returns -1 if any escapes were found which cause the string to
5489 pop out of ASCII range. Otherwise returns the length of the
5490 required buffer to hold the string.
5491 */
5492Py_ssize_t
5493length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5494{
5495 const unsigned char *p = (const unsigned char *)s;
5496 const unsigned char *end = p + size;
5497 Py_ssize_t length = 0;
5498
5499 if (size < 0)
5500 return -1;
5501
5502 for (; p < end; ++p) {
5503 if (*p > 127) {
5504 /* Non-ASCII */
5505 return -1;
5506 }
5507 else if (*p != '\\') {
5508 /* Normal character */
5509 ++length;
5510 }
5511 else {
5512 /* Backslash-escape, check next char */
5513 ++p;
5514 /* Escape sequence reaches till end of string or
5515 non-ASCII follow-up. */
5516 if (p >= end || *p > 127)
5517 return -1;
5518 switch (*p) {
5519 case '\n':
5520 /* backslash + \n result in zero characters */
5521 break;
5522 case '\\': case '\'': case '\"':
5523 case 'b': case 'f': case 't':
5524 case 'n': case 'r': case 'v': case 'a':
5525 ++length;
5526 break;
5527 case '0': case '1': case '2': case '3':
5528 case '4': case '5': case '6': case '7':
5529 case 'x': case 'u': case 'U': case 'N':
5530 /* these do not guarantee ASCII characters */
5531 return -1;
5532 default:
5533 /* count the backslash + the other character */
5534 length += 2;
5535 }
5536 }
5537 }
5538 return length;
5539}
5540
5541/* Similar to PyUnicode_WRITE but either write into wstr field
5542 or treat string as ASCII. */
5543#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5544 do { \
5545 if ((kind) != PyUnicode_WCHAR_KIND) \
5546 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5547 else \
5548 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5549 } while (0)
5550
5551#define WRITE_WSTR(buf, index, value) \
5552 assert(kind == PyUnicode_WCHAR_KIND), \
5553 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5554
5555
Fredrik Lundh06d12682001-01-24 07:59:11 +00005556static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005557
Alexander Belopolsky40018472011-02-26 01:02:56 +00005558PyObject *
5559PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005560 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005561 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005562{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005563 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005564 Py_ssize_t startinpos;
5565 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005566 int j;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005567 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005568 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005569 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005570 char* message;
5571 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005572 PyObject *errorHandler = NULL;
5573 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005574 Py_ssize_t ascii_length;
5575 Py_ssize_t i;
5576 int kind;
5577 void *data;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005578
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005579 ascii_length = length_of_escaped_ascii_string(s, size);
5580
5581 /* After length_of_escaped_ascii_string() there are two alternatives,
5582 either the string is pure ASCII with named escapes like \n, etc.
5583 and we determined it's exact size (common case)
5584 or it contains \x, \u, ... escape sequences. then we create a
5585 legacy wchar string and resize it at the end of this function. */
5586 if (ascii_length >= 0) {
5587 v = (PyUnicodeObject *)PyUnicode_New(ascii_length, 127);
5588 if (!v)
5589 goto onError;
5590 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
5591 kind = PyUnicode_1BYTE_KIND;
5592 data = PyUnicode_DATA(v);
5593 }
5594 else {
5595 /* Escaped strings will always be longer than the resulting
5596 Unicode string, so we start with size here and then reduce the
5597 length after conversion to the true value.
5598 (but if the error callback returns a long replacement string
5599 we'll have to allocate more space) */
5600 v = _PyUnicode_New(size);
5601 if (!v)
5602 goto onError;
5603 kind = PyUnicode_WCHAR_KIND;
5604 data = PyUnicode_AS_UNICODE(v);
5605 }
5606
Guido van Rossumd57fd912000-03-10 22:53:23 +00005607 if (size == 0)
5608 return (PyObject *)v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005609 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005610 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005611
Guido van Rossumd57fd912000-03-10 22:53:23 +00005612 while (s < end) {
5613 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005614 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005615 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005616
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005617 if (kind == PyUnicode_WCHAR_KIND) {
5618 assert(i < _PyUnicode_WSTR_LENGTH(v));
5619 }
5620 else {
5621 /* The only case in which i == ascii_length is a backslash
5622 followed by a newline. */
5623 assert(i <= ascii_length);
5624 }
5625
Guido van Rossumd57fd912000-03-10 22:53:23 +00005626 /* Non-escape characters are interpreted as Unicode ordinals */
5627 if (*s != '\\') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005628 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char) *s++);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005629 continue;
5630 }
5631
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005632 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005633 /* \ - Escapes */
5634 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005635 c = *s++;
5636 if (s > end)
5637 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005638
5639 if (kind == PyUnicode_WCHAR_KIND) {
5640 assert(i < _PyUnicode_WSTR_LENGTH(v));
5641 }
5642 else {
5643 /* The only case in which i == ascii_length is a backslash
5644 followed by a newline. */
5645 assert(i < ascii_length || (i == ascii_length && c == '\n'));
5646 }
5647
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005648 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005649
Benjamin Peterson29060642009-01-31 22:14:21 +00005650 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005651 case '\n': break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005652 case '\\': WRITE_ASCII_OR_WSTR(kind, data, i++, '\\'); break;
5653 case '\'': WRITE_ASCII_OR_WSTR(kind, data, i++, '\''); break;
5654 case '\"': WRITE_ASCII_OR_WSTR(kind, data, i++, '\"'); break;
5655 case 'b': WRITE_ASCII_OR_WSTR(kind, data, i++, '\b'); break;
5656 /* FF */
5657 case 'f': WRITE_ASCII_OR_WSTR(kind, data, i++, '\014'); break;
5658 case 't': WRITE_ASCII_OR_WSTR(kind, data, i++, '\t'); break;
5659 case 'n': WRITE_ASCII_OR_WSTR(kind, data, i++, '\n'); break;
5660 case 'r': WRITE_ASCII_OR_WSTR(kind, data, i++, '\r'); break;
5661 /* VT */
5662 case 'v': WRITE_ASCII_OR_WSTR(kind, data, i++, '\013'); break;
5663 /* BEL, not classic C */
5664 case 'a': WRITE_ASCII_OR_WSTR(kind, data, i++, '\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005665
Benjamin Peterson29060642009-01-31 22:14:21 +00005666 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005667 case '0': case '1': case '2': case '3':
5668 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005669 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005670 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005671 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005672 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005673 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005674 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005675 WRITE_WSTR(data, i++, x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005676 break;
5677
Benjamin Peterson29060642009-01-31 22:14:21 +00005678 /* hex escapes */
5679 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005680 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005681 digits = 2;
5682 message = "truncated \\xXX escape";
5683 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005684
Benjamin Peterson29060642009-01-31 22:14:21 +00005685 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005686 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005687 digits = 4;
5688 message = "truncated \\uXXXX escape";
5689 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005690
Benjamin Peterson29060642009-01-31 22:14:21 +00005691 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005692 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005693 digits = 8;
5694 message = "truncated \\UXXXXXXXX escape";
5695 hexescape:
5696 chr = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005697 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005698 if (s+digits>end) {
5699 endinpos = size;
5700 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005701 errors, &errorHandler,
5702 "unicodeescape", "end of string in escape sequence",
5703 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005704 &v, &i, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005705 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005706 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005707 goto nextByte;
5708 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005709 for (j = 0; j < digits; ++j) {
5710 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005711 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005712 endinpos = (s+j+1)-starts;
5713 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005714 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005715 errors, &errorHandler,
5716 "unicodeescape", message,
5717 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005718 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005719 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005720 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005721 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005722 }
5723 chr = (chr<<4) & ~0xF;
5724 if (c >= '0' && c <= '9')
5725 chr += c - '0';
5726 else if (c >= 'a' && c <= 'f')
5727 chr += 10 + c - 'a';
5728 else
5729 chr += 10 + c - 'A';
5730 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005731 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005732 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005733 /* _decoding_error will have already written into the
5734 target buffer. */
5735 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005736 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005737 /* when we get here, chr is a 32-bit unicode character */
5738 if (chr <= 0xffff)
5739 /* UCS-2 character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005740 WRITE_WSTR(data, i++, chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005741 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005742 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00005743 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00005744#ifdef Py_UNICODE_WIDE
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005745 WRITE_WSTR(data, i++, chr);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005746#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00005747 chr -= 0x10000L;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005748 WRITE_WSTR(data, i++, 0xD800 + (Py_UNICODE) (chr >> 10));
5749 WRITE_WSTR(data, i++, 0xDC00 + (Py_UNICODE) (chr & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005750#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00005751 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005752 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005753 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005754 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005755 errors, &errorHandler,
5756 "unicodeescape", "illegal Unicode character",
5757 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005758 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005759 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005760 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005761 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005762 break;
5763
Benjamin Peterson29060642009-01-31 22:14:21 +00005764 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005765 case 'N':
5766 message = "malformed \\N character escape";
5767 if (ucnhash_CAPI == NULL) {
5768 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005769 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5770 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005771 if (ucnhash_CAPI == NULL)
5772 goto ucnhashError;
5773 }
5774 if (*s == '{') {
5775 const char *start = s+1;
5776 /* look for the closing brace */
5777 while (*s != '}' && s < end)
5778 s++;
5779 if (s > start && s < end && *s == '}') {
5780 /* found a name. look it up in the unicode database */
5781 message = "unknown Unicode character name";
5782 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005783 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
5784 &chr))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005785 goto store;
5786 }
5787 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005788 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005789 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005790 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005791 errors, &errorHandler,
5792 "unicodeescape", message,
5793 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005794 &v, &i, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005795 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005796 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005797 break;
5798
5799 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005800 if (s > end) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005801 assert(kind == PyUnicode_WCHAR_KIND);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005802 message = "\\ at end of string";
5803 s--;
5804 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005805 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005806 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005807 errors, &errorHandler,
5808 "unicodeescape", message,
5809 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005810 &v, &i, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00005811 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005812 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005813 }
5814 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005815 WRITE_ASCII_OR_WSTR(kind, data, i++, '\\');
5816 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005817 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005818 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005819 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005820 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005821 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005822 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005823 /* Ensure the length prediction worked in case of ASCII strings */
5824 assert(kind == PyUnicode_WCHAR_KIND || i == ascii_length);
5825
Victor Stinnerfe226c02011-10-03 03:52:20 +02005826 if (kind == PyUnicode_WCHAR_KIND)
5827 {
5828 if (PyUnicode_Resize((PyObject**)&v, i) < 0)
5829 goto onError;
Victor Stinnerfe226c02011-10-03 03:52:20 +02005830 }
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005831 Py_XDECREF(errorHandler);
5832 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005833#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005834 if (_PyUnicode_READY_REPLACE(&v)) {
5835 Py_DECREF(v);
5836 return NULL;
5837 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005838#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005839 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00005840 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005841
Benjamin Peterson29060642009-01-31 22:14:21 +00005842 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005843 PyErr_SetString(
5844 PyExc_UnicodeError,
5845 "\\N escapes not supported (can't load unicodedata module)"
5846 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005847 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005848 Py_XDECREF(errorHandler);
5849 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005850 return NULL;
5851
Benjamin Peterson29060642009-01-31 22:14:21 +00005852 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005853 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005854 Py_XDECREF(errorHandler);
5855 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005856 return NULL;
5857}
5858
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005859#undef WRITE_ASCII_OR_WSTR
5860#undef WRITE_WSTR
5861
Guido van Rossumd57fd912000-03-10 22:53:23 +00005862/* Return a Unicode-Escape string version of the Unicode object.
5863
5864 If quotes is true, the string is enclosed in u"" or u'' quotes as
5865 appropriate.
5866
5867*/
5868
Walter Dörwald79e913e2007-05-12 11:08:06 +00005869static const char *hexdigits = "0123456789abcdef";
5870
Alexander Belopolsky40018472011-02-26 01:02:56 +00005871PyObject *
5872PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005873 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005874{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005875 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005876 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005877
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005878#ifdef Py_UNICODE_WIDE
5879 const Py_ssize_t expandsize = 10;
5880#else
5881 const Py_ssize_t expandsize = 6;
5882#endif
5883
Thomas Wouters89f507f2006-12-13 04:49:30 +00005884 /* XXX(nnorwitz): rather than over-allocating, it would be
5885 better to choose a different scheme. Perhaps scan the
5886 first N-chars of the string and allocate based on that size.
5887 */
5888 /* Initial allocation is based on the longest-possible unichr
5889 escape.
5890
5891 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5892 unichr, so in this case it's the longest unichr escape. In
5893 narrow (UTF-16) builds this is five chars per source unichr
5894 since there are two unichrs in the surrogate pair, so in narrow
5895 (UTF-16) builds it's not the longest unichr escape.
5896
5897 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5898 so in the narrow (UTF-16) build case it's the longest unichr
5899 escape.
5900 */
5901
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005902 if (size == 0)
5903 return PyBytes_FromStringAndSize(NULL, 0);
5904
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005905 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005906 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005907
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005908 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005909 2
5910 + expandsize*size
5911 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005912 if (repr == NULL)
5913 return NULL;
5914
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005915 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005916
Guido van Rossumd57fd912000-03-10 22:53:23 +00005917 while (size-- > 0) {
5918 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005919
Walter Dörwald79e913e2007-05-12 11:08:06 +00005920 /* Escape backslashes */
5921 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005922 *p++ = '\\';
5923 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005924 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005925 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005926
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00005927#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005928 /* Map 21-bit characters to '\U00xxxxxx' */
5929 else if (ch >= 0x10000) {
5930 *p++ = '\\';
5931 *p++ = 'U';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005932 *p++ = hexdigits[(ch >> 28) & 0x0000000F];
5933 *p++ = hexdigits[(ch >> 24) & 0x0000000F];
5934 *p++ = hexdigits[(ch >> 20) & 0x0000000F];
5935 *p++ = hexdigits[(ch >> 16) & 0x0000000F];
5936 *p++ = hexdigits[(ch >> 12) & 0x0000000F];
5937 *p++ = hexdigits[(ch >> 8) & 0x0000000F];
5938 *p++ = hexdigits[(ch >> 4) & 0x0000000F];
5939 *p++ = hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005940 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005941 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005942#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005943 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
5944 else if (ch >= 0xD800 && ch < 0xDC00) {
5945 Py_UNICODE ch2;
5946 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00005947
Benjamin Peterson29060642009-01-31 22:14:21 +00005948 ch2 = *s++;
5949 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00005950 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005951 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
5952 *p++ = '\\';
5953 *p++ = 'U';
5954 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
5955 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
5956 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
5957 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
5958 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
5959 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
5960 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
5961 *p++ = hexdigits[ucs & 0x0000000F];
5962 continue;
5963 }
5964 /* Fall through: isolated surrogates are copied as-is */
5965 s--;
5966 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005967 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005968#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005969
Guido van Rossumd57fd912000-03-10 22:53:23 +00005970 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005971 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005972 *p++ = '\\';
5973 *p++ = 'u';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005974 *p++ = hexdigits[(ch >> 12) & 0x000F];
5975 *p++ = hexdigits[(ch >> 8) & 0x000F];
5976 *p++ = hexdigits[(ch >> 4) & 0x000F];
5977 *p++ = hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005978 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005979
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005980 /* Map special whitespace to '\t', \n', '\r' */
5981 else if (ch == '\t') {
5982 *p++ = '\\';
5983 *p++ = 't';
5984 }
5985 else if (ch == '\n') {
5986 *p++ = '\\';
5987 *p++ = 'n';
5988 }
5989 else if (ch == '\r') {
5990 *p++ = '\\';
5991 *p++ = 'r';
5992 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005993
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005994 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005995 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005996 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005997 *p++ = 'x';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005998 *p++ = hexdigits[(ch >> 4) & 0x000F];
5999 *p++ = hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006000 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006001
Guido van Rossumd57fd912000-03-10 22:53:23 +00006002 /* Copy everything else as-is */
6003 else
6004 *p++ = (char) ch;
6005 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006006
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006007 assert(p - PyBytes_AS_STRING(repr) > 0);
6008 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6009 return NULL;
6010 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006011}
6012
Alexander Belopolsky40018472011-02-26 01:02:56 +00006013PyObject *
6014PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006015{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006016 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006017 if (!PyUnicode_Check(unicode)) {
6018 PyErr_BadArgument();
6019 return NULL;
6020 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00006021 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6022 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006023 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006024}
6025
6026/* --- Raw Unicode Escape Codec ------------------------------------------- */
6027
Alexander Belopolsky40018472011-02-26 01:02:56 +00006028PyObject *
6029PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006030 Py_ssize_t size,
6031 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006032{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006033 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006034 Py_ssize_t startinpos;
6035 Py_ssize_t endinpos;
6036 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006037 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006038 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039 const char *end;
6040 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006041 PyObject *errorHandler = NULL;
6042 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006043
Guido van Rossumd57fd912000-03-10 22:53:23 +00006044 /* Escaped strings will always be longer than the resulting
6045 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006046 length after conversion to the true value. (But decoding error
6047 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006048 v = _PyUnicode_New(size);
6049 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006050 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006051 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006052 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006053 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006054 end = s + size;
6055 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006056 unsigned char c;
6057 Py_UCS4 x;
6058 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006059 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006060
Benjamin Peterson29060642009-01-31 22:14:21 +00006061 /* Non-escape characters are interpreted as Unicode ordinals */
6062 if (*s != '\\') {
6063 *p++ = (unsigned char)*s++;
6064 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006065 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006066 startinpos = s-starts;
6067
6068 /* \u-escapes are only interpreted iff the number of leading
6069 backslashes if odd */
6070 bs = s;
6071 for (;s < end;) {
6072 if (*s != '\\')
6073 break;
6074 *p++ = (unsigned char)*s++;
6075 }
6076 if (((s - bs) & 1) == 0 ||
6077 s >= end ||
6078 (*s != 'u' && *s != 'U')) {
6079 continue;
6080 }
6081 p--;
6082 count = *s=='u' ? 4 : 8;
6083 s++;
6084
6085 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
6086 outpos = p-PyUnicode_AS_UNICODE(v);
6087 for (x = 0, i = 0; i < count; ++i, ++s) {
6088 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006089 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006090 endinpos = s-starts;
6091 if (unicode_decode_call_errorhandler(
6092 errors, &errorHandler,
6093 "rawunicodeescape", "truncated \\uXXXX",
6094 &starts, &end, &startinpos, &endinpos, &exc, &s,
6095 &v, &outpos, &p))
6096 goto onError;
6097 goto nextByte;
6098 }
6099 x = (x<<4) & ~0xF;
6100 if (c >= '0' && c <= '9')
6101 x += c - '0';
6102 else if (c >= 'a' && c <= 'f')
6103 x += 10 + c - 'a';
6104 else
6105 x += 10 + c - 'A';
6106 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00006107 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00006108 /* UCS-2 character */
6109 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006110 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006111 /* UCS-4 character. Either store directly, or as
6112 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00006113#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006114 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006115#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006116 x -= 0x10000L;
6117 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
6118 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00006119#endif
6120 } else {
6121 endinpos = s-starts;
6122 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006123 if (unicode_decode_call_errorhandler(
6124 errors, &errorHandler,
6125 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006126 &starts, &end, &startinpos, &endinpos, &exc, &s,
6127 &v, &outpos, &p))
6128 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006129 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006130 nextByte:
6131 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006132 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02006133 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006134 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006135 Py_XDECREF(errorHandler);
6136 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006137#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006138 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006139 Py_DECREF(v);
6140 return NULL;
6141 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006142#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006143 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006144 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006145
Benjamin Peterson29060642009-01-31 22:14:21 +00006146 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006147 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006148 Py_XDECREF(errorHandler);
6149 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006150 return NULL;
6151}
6152
Alexander Belopolsky40018472011-02-26 01:02:56 +00006153PyObject *
6154PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006155 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006156{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006157 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006158 char *p;
6159 char *q;
6160
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006161#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006162 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006163#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006164 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006165#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00006166
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006167 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006168 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006169
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006170 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006171 if (repr == NULL)
6172 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00006173 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006174 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006175
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006176 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006177 while (size-- > 0) {
6178 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006179#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006180 /* Map 32-bit characters to '\Uxxxxxxxx' */
6181 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006182 *p++ = '\\';
6183 *p++ = 'U';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00006184 *p++ = hexdigits[(ch >> 28) & 0xf];
6185 *p++ = hexdigits[(ch >> 24) & 0xf];
6186 *p++ = hexdigits[(ch >> 20) & 0xf];
6187 *p++ = hexdigits[(ch >> 16) & 0xf];
6188 *p++ = hexdigits[(ch >> 12) & 0xf];
6189 *p++ = hexdigits[(ch >> 8) & 0xf];
6190 *p++ = hexdigits[(ch >> 4) & 0xf];
6191 *p++ = hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006192 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006193 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00006194#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006195 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
6196 if (ch >= 0xD800 && ch < 0xDC00) {
6197 Py_UNICODE ch2;
6198 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006199
Benjamin Peterson29060642009-01-31 22:14:21 +00006200 ch2 = *s++;
6201 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00006202 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006203 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
6204 *p++ = '\\';
6205 *p++ = 'U';
6206 *p++ = hexdigits[(ucs >> 28) & 0xf];
6207 *p++ = hexdigits[(ucs >> 24) & 0xf];
6208 *p++ = hexdigits[(ucs >> 20) & 0xf];
6209 *p++ = hexdigits[(ucs >> 16) & 0xf];
6210 *p++ = hexdigits[(ucs >> 12) & 0xf];
6211 *p++ = hexdigits[(ucs >> 8) & 0xf];
6212 *p++ = hexdigits[(ucs >> 4) & 0xf];
6213 *p++ = hexdigits[ucs & 0xf];
6214 continue;
6215 }
6216 /* Fall through: isolated surrogates are copied as-is */
6217 s--;
6218 size++;
6219 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006220#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006221 /* Map 16-bit characters to '\uxxxx' */
6222 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006223 *p++ = '\\';
6224 *p++ = 'u';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00006225 *p++ = hexdigits[(ch >> 12) & 0xf];
6226 *p++ = hexdigits[(ch >> 8) & 0xf];
6227 *p++ = hexdigits[(ch >> 4) & 0xf];
6228 *p++ = hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006229 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006230 /* Copy everything else as-is */
6231 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006232 *p++ = (char) ch;
6233 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006234 size = p - q;
6235
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006236 assert(size > 0);
6237 if (_PyBytes_Resize(&repr, size) < 0)
6238 return NULL;
6239 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006240}
6241
Alexander Belopolsky40018472011-02-26 01:02:56 +00006242PyObject *
6243PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006244{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006245 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006246 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00006247 PyErr_BadArgument();
6248 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006249 }
Walter Dörwald711005d2007-05-12 12:03:26 +00006250 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6251 PyUnicode_GET_SIZE(unicode));
6252
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006253 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006254}
6255
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006256/* --- Unicode Internal Codec ------------------------------------------- */
6257
Alexander Belopolsky40018472011-02-26 01:02:56 +00006258PyObject *
6259_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006260 Py_ssize_t size,
6261 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006262{
6263 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006264 Py_ssize_t startinpos;
6265 Py_ssize_t endinpos;
6266 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006267 PyUnicodeObject *v;
6268 Py_UNICODE *p;
6269 const char *end;
6270 const char *reason;
6271 PyObject *errorHandler = NULL;
6272 PyObject *exc = NULL;
6273
Neal Norwitzd43069c2006-01-08 01:12:10 +00006274#ifdef Py_UNICODE_WIDE
6275 Py_UNICODE unimax = PyUnicode_GetMax();
6276#endif
6277
Thomas Wouters89f507f2006-12-13 04:49:30 +00006278 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006279 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
6280 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006281 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006282 /* Intentionally PyUnicode_GET_SIZE instead of PyUnicode_GET_LENGTH
6283 as string was created with the old API. */
6284 if (PyUnicode_GET_SIZE(v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006285 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006286 p = PyUnicode_AS_UNICODE(v);
6287 end = s + size;
6288
6289 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006290 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006291 /* We have to sanity check the raw data, otherwise doom looms for
6292 some malformed UCS-4 data. */
6293 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006294#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006295 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006296#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006297 end-s < Py_UNICODE_SIZE
6298 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006299 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006300 startinpos = s - starts;
6301 if (end-s < Py_UNICODE_SIZE) {
6302 endinpos = end-starts;
6303 reason = "truncated input";
6304 }
6305 else {
6306 endinpos = s - starts + Py_UNICODE_SIZE;
6307 reason = "illegal code point (> 0x10FFFF)";
6308 }
6309 outpos = p - PyUnicode_AS_UNICODE(v);
6310 if (unicode_decode_call_errorhandler(
6311 errors, &errorHandler,
6312 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006313 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00006314 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006315 goto onError;
6316 }
6317 }
6318 else {
6319 p++;
6320 s += Py_UNICODE_SIZE;
6321 }
6322 }
6323
Victor Stinnerfe226c02011-10-03 03:52:20 +02006324 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006325 goto onError;
6326 Py_XDECREF(errorHandler);
6327 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006328#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006329 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006330 Py_DECREF(v);
6331 return NULL;
6332 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006333#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006334 assert(_PyUnicode_CheckConsistency(v, 1));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006335 return (PyObject *)v;
6336
Benjamin Peterson29060642009-01-31 22:14:21 +00006337 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006338 Py_XDECREF(v);
6339 Py_XDECREF(errorHandler);
6340 Py_XDECREF(exc);
6341 return NULL;
6342}
6343
Guido van Rossumd57fd912000-03-10 22:53:23 +00006344/* --- Latin-1 Codec ------------------------------------------------------ */
6345
Alexander Belopolsky40018472011-02-26 01:02:56 +00006346PyObject *
6347PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006348 Py_ssize_t size,
6349 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006350{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006351 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006352 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006353}
6354
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006355/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006356static void
6357make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006358 const char *encoding,
6359 const Py_UNICODE *unicode, Py_ssize_t size,
6360 Py_ssize_t startpos, Py_ssize_t endpos,
6361 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006362{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006363 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006364 *exceptionObject = PyUnicodeEncodeError_Create(
6365 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006366 }
6367 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006368 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6369 goto onError;
6370 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6371 goto onError;
6372 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6373 goto onError;
6374 return;
6375 onError:
6376 Py_DECREF(*exceptionObject);
6377 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006378 }
6379}
6380
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006381/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006382static void
6383raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006384 const char *encoding,
6385 const Py_UNICODE *unicode, Py_ssize_t size,
6386 Py_ssize_t startpos, Py_ssize_t endpos,
6387 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006388{
6389 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006390 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006391 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006392 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006393}
6394
6395/* error handling callback helper:
6396 build arguments, call the callback and check the arguments,
6397 put the result into newpos and return the replacement string, which
6398 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006399static PyObject *
6400unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006401 PyObject **errorHandler,
6402 const char *encoding, const char *reason,
6403 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
6404 Py_ssize_t startpos, Py_ssize_t endpos,
6405 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006406{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006407 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006408
6409 PyObject *restuple;
6410 PyObject *resunicode;
6411
6412 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006413 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006414 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006415 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006416 }
6417
6418 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006419 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006420 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006421 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006422
6423 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006424 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006425 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006426 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006427 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006428 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006429 Py_DECREF(restuple);
6430 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006431 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006432 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006433 &resunicode, newpos)) {
6434 Py_DECREF(restuple);
6435 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006436 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006437 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6438 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6439 Py_DECREF(restuple);
6440 return NULL;
6441 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006442 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006443 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006444 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006445 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6446 Py_DECREF(restuple);
6447 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006448 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006449 Py_INCREF(resunicode);
6450 Py_DECREF(restuple);
6451 return resunicode;
6452}
6453
Alexander Belopolsky40018472011-02-26 01:02:56 +00006454static PyObject *
6455unicode_encode_ucs1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006456 Py_ssize_t size,
6457 const char *errors,
6458 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006459{
6460 /* output object */
6461 PyObject *res;
6462 /* pointers to the beginning and end+1 of input */
6463 const Py_UNICODE *startp = p;
6464 const Py_UNICODE *endp = p + size;
6465 /* pointer to the beginning of the unencodable characters */
6466 /* const Py_UNICODE *badp = NULL; */
6467 /* pointer into the output */
6468 char *str;
6469 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006470 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006471 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6472 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006473 PyObject *errorHandler = NULL;
6474 PyObject *exc = NULL;
6475 /* the following variable is used for caching string comparisons
6476 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6477 int known_errorHandler = -1;
6478
6479 /* allocate enough for a simple encoding without
6480 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006481 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006482 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006483 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006484 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006485 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006486 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006487 ressize = size;
6488
6489 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006490 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006491
Benjamin Peterson29060642009-01-31 22:14:21 +00006492 /* can we encode this? */
6493 if (c<limit) {
6494 /* no overflow check, because we know that the space is enough */
6495 *str++ = (char)c;
6496 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006497 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006498 else {
6499 Py_ssize_t unicodepos = p-startp;
6500 Py_ssize_t requiredsize;
6501 PyObject *repunicode;
6502 Py_ssize_t repsize;
6503 Py_ssize_t newpos;
6504 Py_ssize_t respos;
6505 Py_UNICODE *uni2;
6506 /* startpos for collecting unencodable chars */
6507 const Py_UNICODE *collstart = p;
6508 const Py_UNICODE *collend = p;
6509 /* find all unecodable characters */
6510 while ((collend < endp) && ((*collend)>=limit))
6511 ++collend;
6512 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6513 if (known_errorHandler==-1) {
6514 if ((errors==NULL) || (!strcmp(errors, "strict")))
6515 known_errorHandler = 1;
6516 else if (!strcmp(errors, "replace"))
6517 known_errorHandler = 2;
6518 else if (!strcmp(errors, "ignore"))
6519 known_errorHandler = 3;
6520 else if (!strcmp(errors, "xmlcharrefreplace"))
6521 known_errorHandler = 4;
6522 else
6523 known_errorHandler = 0;
6524 }
6525 switch (known_errorHandler) {
6526 case 1: /* strict */
6527 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
6528 goto onError;
6529 case 2: /* replace */
6530 while (collstart++<collend)
6531 *str++ = '?'; /* fall through */
6532 case 3: /* ignore */
6533 p = collend;
6534 break;
6535 case 4: /* xmlcharrefreplace */
6536 respos = str - PyBytes_AS_STRING(res);
6537 /* determine replacement size (temporarily (mis)uses p) */
6538 for (p = collstart, repsize = 0; p < collend; ++p) {
6539 if (*p<10)
6540 repsize += 2+1+1;
6541 else if (*p<100)
6542 repsize += 2+2+1;
6543 else if (*p<1000)
6544 repsize += 2+3+1;
6545 else if (*p<10000)
6546 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006547#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006548 else
6549 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006550#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006551 else if (*p<100000)
6552 repsize += 2+5+1;
6553 else if (*p<1000000)
6554 repsize += 2+6+1;
6555 else
6556 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006557#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006558 }
6559 requiredsize = respos+repsize+(endp-collend);
6560 if (requiredsize > ressize) {
6561 if (requiredsize<2*ressize)
6562 requiredsize = 2*ressize;
6563 if (_PyBytes_Resize(&res, requiredsize))
6564 goto onError;
6565 str = PyBytes_AS_STRING(res) + respos;
6566 ressize = requiredsize;
6567 }
6568 /* generate replacement (temporarily (mis)uses p) */
6569 for (p = collstart; p < collend; ++p) {
6570 str += sprintf(str, "&#%d;", (int)*p);
6571 }
6572 p = collend;
6573 break;
6574 default:
6575 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
6576 encoding, reason, startp, size, &exc,
6577 collstart-startp, collend-startp, &newpos);
6578 if (repunicode == NULL)
6579 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006580 if (PyBytes_Check(repunicode)) {
6581 /* Directly copy bytes result to output. */
6582 repsize = PyBytes_Size(repunicode);
6583 if (repsize > 1) {
6584 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006585 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006586 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6587 Py_DECREF(repunicode);
6588 goto onError;
6589 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006590 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006591 ressize += repsize-1;
6592 }
6593 memcpy(str, PyBytes_AsString(repunicode), repsize);
6594 str += repsize;
6595 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006596 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006597 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006598 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006599 /* need more space? (at least enough for what we
6600 have+the replacement+the rest of the string, so
6601 we won't have to check space for encodable characters) */
6602 respos = str - PyBytes_AS_STRING(res);
6603 repsize = PyUnicode_GET_SIZE(repunicode);
6604 requiredsize = respos+repsize+(endp-collend);
6605 if (requiredsize > ressize) {
6606 if (requiredsize<2*ressize)
6607 requiredsize = 2*ressize;
6608 if (_PyBytes_Resize(&res, requiredsize)) {
6609 Py_DECREF(repunicode);
6610 goto onError;
6611 }
6612 str = PyBytes_AS_STRING(res) + respos;
6613 ressize = requiredsize;
6614 }
6615 /* check if there is anything unencodable in the replacement
6616 and copy it to the output */
6617 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
6618 c = *uni2;
6619 if (c >= limit) {
6620 raise_encode_exception(&exc, encoding, startp, size,
6621 unicodepos, unicodepos+1, reason);
6622 Py_DECREF(repunicode);
6623 goto onError;
6624 }
6625 *str = (char)c;
6626 }
6627 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006628 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006629 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006630 }
6631 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006632 /* Resize if we allocated to much */
6633 size = str - PyBytes_AS_STRING(res);
6634 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006635 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006636 if (_PyBytes_Resize(&res, size) < 0)
6637 goto onError;
6638 }
6639
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006640 Py_XDECREF(errorHandler);
6641 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006642 return res;
6643
6644 onError:
6645 Py_XDECREF(res);
6646 Py_XDECREF(errorHandler);
6647 Py_XDECREF(exc);
6648 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006649}
6650
Alexander Belopolsky40018472011-02-26 01:02:56 +00006651PyObject *
6652PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006653 Py_ssize_t size,
6654 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006655{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006656 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006657}
6658
Alexander Belopolsky40018472011-02-26 01:02:56 +00006659PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006660_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006661{
6662 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006663 PyErr_BadArgument();
6664 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006665 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006666 if (PyUnicode_READY(unicode) == -1)
6667 return NULL;
6668 /* Fast path: if it is a one-byte string, construct
6669 bytes object directly. */
6670 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6671 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6672 PyUnicode_GET_LENGTH(unicode));
6673 /* Non-Latin-1 characters present. Defer to above function to
6674 raise the exception. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006675 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006676 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006677 errors);
6678}
6679
6680PyObject*
6681PyUnicode_AsLatin1String(PyObject *unicode)
6682{
6683 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006684}
6685
6686/* --- 7-bit ASCII Codec -------------------------------------------------- */
6687
Alexander Belopolsky40018472011-02-26 01:02:56 +00006688PyObject *
6689PyUnicode_DecodeASCII(const char *s,
6690 Py_ssize_t size,
6691 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006692{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006693 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006694 PyUnicodeObject *v;
Victor Stinner702c7342011-10-05 13:50:52 +02006695 Py_UNICODE *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006696 Py_ssize_t startinpos;
6697 Py_ssize_t endinpos;
6698 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006699 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006700 int has_error;
6701 const unsigned char *p = (const unsigned char *)s;
6702 const unsigned char *end = p + size;
6703 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006704 PyObject *errorHandler = NULL;
6705 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006706
Guido van Rossumd57fd912000-03-10 22:53:23 +00006707 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006708 if (size == 1 && (unsigned char)s[0] < 128)
6709 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006710
Victor Stinner702c7342011-10-05 13:50:52 +02006711 has_error = 0;
6712 while (p < end && !has_error) {
6713 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6714 an explanation. */
6715 if (!((size_t) p & LONG_PTR_MASK)) {
6716 /* Help register allocation */
6717 register const unsigned char *_p = p;
6718 while (_p < aligned_end) {
6719 unsigned long value = *(unsigned long *) _p;
6720 if (value & ASCII_CHAR_MASK) {
6721 has_error = 1;
6722 break;
6723 }
6724 _p += SIZEOF_LONG;
6725 }
6726 if (_p == end)
6727 break;
6728 if (has_error)
6729 break;
6730 p = _p;
6731 }
6732 if (*p & 0x80) {
6733 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006734 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006735 }
6736 else {
6737 ++p;
6738 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006739 }
Victor Stinner702c7342011-10-05 13:50:52 +02006740 if (!has_error)
6741 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006742
Guido van Rossumd57fd912000-03-10 22:53:23 +00006743 v = _PyUnicode_New(size);
6744 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006745 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006746 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006747 return (PyObject *)v;
Victor Stinner702c7342011-10-05 13:50:52 +02006748 u = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006749 e = s + size;
6750 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006751 register unsigned char c = (unsigned char)*s;
6752 if (c < 128) {
Victor Stinner702c7342011-10-05 13:50:52 +02006753 *u++ = c;
Benjamin Peterson29060642009-01-31 22:14:21 +00006754 ++s;
6755 }
6756 else {
6757 startinpos = s-starts;
6758 endinpos = startinpos + 1;
Victor Stinner702c7342011-10-05 13:50:52 +02006759 outpos = u - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006760 if (unicode_decode_call_errorhandler(
6761 errors, &errorHandler,
6762 "ascii", "ordinal not in range(128)",
6763 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinner702c7342011-10-05 13:50:52 +02006764 &v, &outpos, &u))
Benjamin Peterson29060642009-01-31 22:14:21 +00006765 goto onError;
6766 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006767 }
Victor Stinner702c7342011-10-05 13:50:52 +02006768 if (u - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
6769 if (PyUnicode_Resize((PyObject**)&v, u - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006770 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006771 Py_XDECREF(errorHandler);
6772 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006773#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006774 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006775 Py_DECREF(v);
6776 return NULL;
6777 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006778#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006779 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006780 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006781
Benjamin Peterson29060642009-01-31 22:14:21 +00006782 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006783 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006784 Py_XDECREF(errorHandler);
6785 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006786 return NULL;
6787}
6788
Alexander Belopolsky40018472011-02-26 01:02:56 +00006789PyObject *
6790PyUnicode_EncodeASCII(const Py_UNICODE *p,
6791 Py_ssize_t size,
6792 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006793{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006794 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006795}
6796
Alexander Belopolsky40018472011-02-26 01:02:56 +00006797PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006798_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006799{
6800 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006801 PyErr_BadArgument();
6802 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006803 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006804 if (PyUnicode_READY(unicode) == -1)
6805 return NULL;
6806 /* Fast path: if it is an ASCII-only string, construct bytes object
6807 directly. Else defer to above function to raise the exception. */
6808 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6809 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6810 PyUnicode_GET_LENGTH(unicode));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006811 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006812 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006813 errors);
6814}
6815
6816PyObject *
6817PyUnicode_AsASCIIString(PyObject *unicode)
6818{
6819 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006820}
6821
Victor Stinner99b95382011-07-04 14:23:54 +02006822#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006823
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006824/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006825
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006826#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006827#define NEED_RETRY
6828#endif
6829
6830/* XXX This code is limited to "true" double-byte encodings, as
6831 a) it assumes an incomplete character consists of a single byte, and
6832 b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
Benjamin Peterson29060642009-01-31 22:14:21 +00006833 encodings, see IsDBCSLeadByteEx documentation. */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006834
Alexander Belopolsky40018472011-02-26 01:02:56 +00006835static int
6836is_dbcs_lead_byte(const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006837{
6838 const char *curr = s + offset;
6839
6840 if (IsDBCSLeadByte(*curr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006841 const char *prev = CharPrev(s, curr);
6842 return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006843 }
6844 return 0;
6845}
6846
6847/*
6848 * Decode MBCS string into unicode object. If 'final' is set, converts
6849 * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
6850 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006851static int
6852decode_mbcs(PyUnicodeObject **v,
6853 const char *s, /* MBCS string */
6854 int size, /* sizeof MBCS string */
6855 int final,
6856 const char *errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006857{
6858 Py_UNICODE *p;
Victor Stinner554f3f02010-06-16 23:33:54 +00006859 Py_ssize_t n;
6860 DWORD usize;
6861 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006862
6863 assert(size >= 0);
6864
Victor Stinner554f3f02010-06-16 23:33:54 +00006865 /* check and handle 'errors' arg */
6866 if (errors==NULL || strcmp(errors, "strict")==0)
6867 flags = MB_ERR_INVALID_CHARS;
6868 else if (strcmp(errors, "ignore")==0)
6869 flags = 0;
6870 else {
6871 PyErr_Format(PyExc_ValueError,
6872 "mbcs encoding does not support errors='%s'",
6873 errors);
6874 return -1;
6875 }
6876
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006877 /* Skip trailing lead-byte unless 'final' is set */
6878 if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006879 --size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006880
6881 /* First get the size of the result */
6882 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00006883 usize = MultiByteToWideChar(CP_ACP, flags, s, size, NULL, 0);
6884 if (usize==0)
6885 goto mbcs_decode_error;
6886 } else
6887 usize = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006888
6889 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006890 /* Create unicode object */
6891 *v = _PyUnicode_New(usize);
6892 if (*v == NULL)
6893 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00006894 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006895 }
6896 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006897 /* Extend unicode object */
6898 n = PyUnicode_GET_SIZE(*v);
Victor Stinner2fd82272011-10-03 04:06:05 +02006899 if (PyUnicode_Resize((PyObject**)v, n + usize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006900 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006901 }
6902
6903 /* Do the conversion */
Victor Stinner554f3f02010-06-16 23:33:54 +00006904 if (usize > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006905 p = PyUnicode_AS_UNICODE(*v) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00006906 if (0 == MultiByteToWideChar(CP_ACP, flags, s, size, p, usize)) {
6907 goto mbcs_decode_error;
Benjamin Peterson29060642009-01-31 22:14:21 +00006908 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006909 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006910 return size;
Victor Stinner554f3f02010-06-16 23:33:54 +00006911
6912mbcs_decode_error:
6913 /* If the last error was ERROR_NO_UNICODE_TRANSLATION, then
6914 we raise a UnicodeDecodeError - else it is a 'generic'
6915 windows error
6916 */
6917 if (GetLastError()==ERROR_NO_UNICODE_TRANSLATION) {
6918 /* Ideally, we should get reason from FormatMessage - this
6919 is the Windows 2000 English version of the message
6920 */
6921 PyObject *exc = NULL;
6922 const char *reason = "No mapping for the Unicode character exists "
6923 "in the target multi-byte code page.";
6924 make_decode_exception(&exc, "mbcs", s, size, 0, 0, reason);
6925 if (exc != NULL) {
6926 PyCodec_StrictErrors(exc);
6927 Py_DECREF(exc);
6928 }
6929 } else {
6930 PyErr_SetFromWindowsErrWithFilename(0, NULL);
6931 }
6932 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006933}
6934
Alexander Belopolsky40018472011-02-26 01:02:56 +00006935PyObject *
6936PyUnicode_DecodeMBCSStateful(const char *s,
6937 Py_ssize_t size,
6938 const char *errors,
6939 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006940{
6941 PyUnicodeObject *v = NULL;
6942 int done;
6943
6944 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006945 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006946
6947#ifdef NEED_RETRY
6948 retry:
6949 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00006950 done = decode_mbcs(&v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006951 else
6952#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00006953 done = decode_mbcs(&v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006954
6955 if (done < 0) {
6956 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006957 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006958 }
6959
6960 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006961 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006962
6963#ifdef NEED_RETRY
6964 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006965 s += done;
6966 size -= done;
6967 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006968 }
6969#endif
Victor Stinner17efeed2011-10-04 20:05:46 +02006970#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006971 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006972 Py_DECREF(v);
6973 return NULL;
6974 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006975#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006976 assert(_PyUnicode_CheckConsistency(v, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006977 return (PyObject *)v;
6978}
6979
Alexander Belopolsky40018472011-02-26 01:02:56 +00006980PyObject *
6981PyUnicode_DecodeMBCS(const char *s,
6982 Py_ssize_t size,
6983 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006984{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006985 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
6986}
6987
6988/*
6989 * Convert unicode into string object (MBCS).
6990 * Returns 0 if succeed, -1 otherwise.
6991 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006992static int
6993encode_mbcs(PyObject **repr,
6994 const Py_UNICODE *p, /* unicode */
6995 int size, /* size of unicode */
6996 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006997{
Victor Stinner554f3f02010-06-16 23:33:54 +00006998 BOOL usedDefaultChar = FALSE;
6999 BOOL *pusedDefaultChar;
7000 int mbcssize;
7001 Py_ssize_t n;
7002 PyObject *exc = NULL;
7003 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007004
7005 assert(size >= 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007006
Victor Stinner554f3f02010-06-16 23:33:54 +00007007 /* check and handle 'errors' arg */
7008 if (errors==NULL || strcmp(errors, "strict")==0) {
7009 flags = WC_NO_BEST_FIT_CHARS;
7010 pusedDefaultChar = &usedDefaultChar;
7011 } else if (strcmp(errors, "replace")==0) {
7012 flags = 0;
7013 pusedDefaultChar = NULL;
7014 } else {
7015 PyErr_Format(PyExc_ValueError,
7016 "mbcs encoding does not support errors='%s'",
7017 errors);
7018 return -1;
7019 }
7020
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007021 /* First get the size of the result */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007022 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00007023 mbcssize = WideCharToMultiByte(CP_ACP, flags, p, size, NULL, 0,
7024 NULL, pusedDefaultChar);
Benjamin Peterson29060642009-01-31 22:14:21 +00007025 if (mbcssize == 0) {
7026 PyErr_SetFromWindowsErrWithFilename(0, NULL);
7027 return -1;
7028 }
Victor Stinner554f3f02010-06-16 23:33:54 +00007029 /* If we used a default char, then we failed! */
7030 if (pusedDefaultChar && *pusedDefaultChar)
7031 goto mbcs_encode_error;
7032 } else {
7033 mbcssize = 0;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007034 }
7035
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007036 if (*repr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007037 /* Create string object */
7038 *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
7039 if (*repr == NULL)
7040 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00007041 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007042 }
7043 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007044 /* Extend string object */
7045 n = PyBytes_Size(*repr);
7046 if (_PyBytes_Resize(repr, n + mbcssize) < 0)
7047 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007048 }
7049
7050 /* Do the conversion */
7051 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007052 char *s = PyBytes_AS_STRING(*repr) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00007053 if (0 == WideCharToMultiByte(CP_ACP, flags, p, size, s, mbcssize,
7054 NULL, pusedDefaultChar)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007055 PyErr_SetFromWindowsErrWithFilename(0, NULL);
7056 return -1;
7057 }
Victor Stinner554f3f02010-06-16 23:33:54 +00007058 if (pusedDefaultChar && *pusedDefaultChar)
7059 goto mbcs_encode_error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007060 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007061 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007062
7063mbcs_encode_error:
7064 raise_encode_exception(&exc, "mbcs", p, size, 0, 0, "invalid character");
7065 Py_XDECREF(exc);
7066 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007067}
7068
Alexander Belopolsky40018472011-02-26 01:02:56 +00007069PyObject *
7070PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7071 Py_ssize_t size,
7072 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007073{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007074 PyObject *repr = NULL;
7075 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00007076
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007077#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00007078 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007079 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00007080 ret = encode_mbcs(&repr, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081 else
7082#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00007083 ret = encode_mbcs(&repr, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007084
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007085 if (ret < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007086 Py_XDECREF(repr);
7087 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007088 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007089
7090#ifdef NEED_RETRY
7091 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007092 p += INT_MAX;
7093 size -= INT_MAX;
7094 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007095 }
7096#endif
7097
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007098 return repr;
7099}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007100
Alexander Belopolsky40018472011-02-26 01:02:56 +00007101PyObject *
7102PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007103{
7104 if (!PyUnicode_Check(unicode)) {
7105 PyErr_BadArgument();
7106 return NULL;
7107 }
7108 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00007109 PyUnicode_GET_SIZE(unicode),
7110 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007111}
7112
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007113#undef NEED_RETRY
7114
Victor Stinner99b95382011-07-04 14:23:54 +02007115#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007116
Guido van Rossumd57fd912000-03-10 22:53:23 +00007117/* --- Character Mapping Codec -------------------------------------------- */
7118
Alexander Belopolsky40018472011-02-26 01:02:56 +00007119PyObject *
7120PyUnicode_DecodeCharmap(const char *s,
7121 Py_ssize_t size,
7122 PyObject *mapping,
7123 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007124{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007125 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007126 Py_ssize_t startinpos;
7127 Py_ssize_t endinpos;
7128 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007129 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007130 PyUnicodeObject *v;
7131 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007132 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007133 PyObject *errorHandler = NULL;
7134 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007135 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007136 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00007137
Guido van Rossumd57fd912000-03-10 22:53:23 +00007138 /* Default to Latin-1 */
7139 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007140 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007141
7142 v = _PyUnicode_New(size);
7143 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007144 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007145 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007146 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007147 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007148 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007149 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007150 mapstring = PyUnicode_AS_UNICODE(mapping);
7151 maplen = PyUnicode_GET_SIZE(mapping);
7152 while (s < e) {
7153 unsigned char ch = *s;
7154 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007155
Benjamin Peterson29060642009-01-31 22:14:21 +00007156 if (ch < maplen)
7157 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00007158
Benjamin Peterson29060642009-01-31 22:14:21 +00007159 if (x == 0xfffe) {
7160 /* undefined mapping */
7161 outpos = p-PyUnicode_AS_UNICODE(v);
7162 startinpos = s-starts;
7163 endinpos = startinpos+1;
7164 if (unicode_decode_call_errorhandler(
7165 errors, &errorHandler,
7166 "charmap", "character maps to <undefined>",
7167 &starts, &e, &startinpos, &endinpos, &exc, &s,
7168 &v, &outpos, &p)) {
7169 goto onError;
7170 }
7171 continue;
7172 }
7173 *p++ = x;
7174 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007175 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007176 }
7177 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007178 while (s < e) {
7179 unsigned char ch = *s;
7180 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007181
Benjamin Peterson29060642009-01-31 22:14:21 +00007182 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7183 w = PyLong_FromLong((long)ch);
7184 if (w == NULL)
7185 goto onError;
7186 x = PyObject_GetItem(mapping, w);
7187 Py_DECREF(w);
7188 if (x == NULL) {
7189 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7190 /* No mapping found means: mapping is undefined. */
7191 PyErr_Clear();
7192 x = Py_None;
7193 Py_INCREF(x);
7194 } else
7195 goto onError;
7196 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007197
Benjamin Peterson29060642009-01-31 22:14:21 +00007198 /* Apply mapping */
7199 if (PyLong_Check(x)) {
7200 long value = PyLong_AS_LONG(x);
7201 if (value < 0 || value > 65535) {
7202 PyErr_SetString(PyExc_TypeError,
7203 "character mapping must be in range(65536)");
7204 Py_DECREF(x);
7205 goto onError;
7206 }
7207 *p++ = (Py_UNICODE)value;
7208 }
7209 else if (x == Py_None) {
7210 /* undefined mapping */
7211 outpos = p-PyUnicode_AS_UNICODE(v);
7212 startinpos = s-starts;
7213 endinpos = startinpos+1;
7214 if (unicode_decode_call_errorhandler(
7215 errors, &errorHandler,
7216 "charmap", "character maps to <undefined>",
7217 &starts, &e, &startinpos, &endinpos, &exc, &s,
7218 &v, &outpos, &p)) {
7219 Py_DECREF(x);
7220 goto onError;
7221 }
7222 Py_DECREF(x);
7223 continue;
7224 }
7225 else if (PyUnicode_Check(x)) {
7226 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007227
Benjamin Peterson29060642009-01-31 22:14:21 +00007228 if (targetsize == 1)
7229 /* 1-1 mapping */
7230 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007231
Benjamin Peterson29060642009-01-31 22:14:21 +00007232 else if (targetsize > 1) {
7233 /* 1-n mapping */
7234 if (targetsize > extrachars) {
7235 /* resize first */
7236 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
7237 Py_ssize_t needed = (targetsize - extrachars) + \
7238 (targetsize << 2);
7239 extrachars += needed;
7240 /* XXX overflow detection missing */
Victor Stinnerfe226c02011-10-03 03:52:20 +02007241 if (PyUnicode_Resize((PyObject**)&v,
Benjamin Peterson29060642009-01-31 22:14:21 +00007242 PyUnicode_GET_SIZE(v) + needed) < 0) {
7243 Py_DECREF(x);
7244 goto onError;
7245 }
7246 p = PyUnicode_AS_UNICODE(v) + oldpos;
7247 }
7248 Py_UNICODE_COPY(p,
7249 PyUnicode_AS_UNICODE(x),
7250 targetsize);
7251 p += targetsize;
7252 extrachars -= targetsize;
7253 }
7254 /* 1-0 mapping: skip the character */
7255 }
7256 else {
7257 /* wrong return value */
7258 PyErr_SetString(PyExc_TypeError,
7259 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007260 Py_DECREF(x);
7261 goto onError;
7262 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007263 Py_DECREF(x);
7264 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007265 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007266 }
7267 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Victor Stinnerfe226c02011-10-03 03:52:20 +02007268 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007269 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007270 Py_XDECREF(errorHandler);
7271 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02007272#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007273 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007274 Py_DECREF(v);
7275 return NULL;
7276 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007277#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007278 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007279 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00007280
Benjamin Peterson29060642009-01-31 22:14:21 +00007281 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007282 Py_XDECREF(errorHandler);
7283 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007284 Py_XDECREF(v);
7285 return NULL;
7286}
7287
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007288/* Charmap encoding: the lookup table */
7289
Alexander Belopolsky40018472011-02-26 01:02:56 +00007290struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007291 PyObject_HEAD
7292 unsigned char level1[32];
7293 int count2, count3;
7294 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007295};
7296
7297static PyObject*
7298encoding_map_size(PyObject *obj, PyObject* args)
7299{
7300 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007301 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007302 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007303}
7304
7305static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007306 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007307 PyDoc_STR("Return the size (in bytes) of this object") },
7308 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007309};
7310
7311static void
7312encoding_map_dealloc(PyObject* o)
7313{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007314 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007315}
7316
7317static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007318 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007319 "EncodingMap", /*tp_name*/
7320 sizeof(struct encoding_map), /*tp_basicsize*/
7321 0, /*tp_itemsize*/
7322 /* methods */
7323 encoding_map_dealloc, /*tp_dealloc*/
7324 0, /*tp_print*/
7325 0, /*tp_getattr*/
7326 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007327 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007328 0, /*tp_repr*/
7329 0, /*tp_as_number*/
7330 0, /*tp_as_sequence*/
7331 0, /*tp_as_mapping*/
7332 0, /*tp_hash*/
7333 0, /*tp_call*/
7334 0, /*tp_str*/
7335 0, /*tp_getattro*/
7336 0, /*tp_setattro*/
7337 0, /*tp_as_buffer*/
7338 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7339 0, /*tp_doc*/
7340 0, /*tp_traverse*/
7341 0, /*tp_clear*/
7342 0, /*tp_richcompare*/
7343 0, /*tp_weaklistoffset*/
7344 0, /*tp_iter*/
7345 0, /*tp_iternext*/
7346 encoding_map_methods, /*tp_methods*/
7347 0, /*tp_members*/
7348 0, /*tp_getset*/
7349 0, /*tp_base*/
7350 0, /*tp_dict*/
7351 0, /*tp_descr_get*/
7352 0, /*tp_descr_set*/
7353 0, /*tp_dictoffset*/
7354 0, /*tp_init*/
7355 0, /*tp_alloc*/
7356 0, /*tp_new*/
7357 0, /*tp_free*/
7358 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007359};
7360
7361PyObject*
7362PyUnicode_BuildEncodingMap(PyObject* string)
7363{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007364 PyObject *result;
7365 struct encoding_map *mresult;
7366 int i;
7367 int need_dict = 0;
7368 unsigned char level1[32];
7369 unsigned char level2[512];
7370 unsigned char *mlevel1, *mlevel2, *mlevel3;
7371 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007372 int kind;
7373 void *data;
7374 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007375
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007376 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007377 PyErr_BadArgument();
7378 return NULL;
7379 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007380 kind = PyUnicode_KIND(string);
7381 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007382 memset(level1, 0xFF, sizeof level1);
7383 memset(level2, 0xFF, sizeof level2);
7384
7385 /* If there isn't a one-to-one mapping of NULL to \0,
7386 or if there are non-BMP characters, we need to use
7387 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007388 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007389 need_dict = 1;
7390 for (i = 1; i < 256; i++) {
7391 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007392 ch = PyUnicode_READ(kind, data, i);
7393 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007394 need_dict = 1;
7395 break;
7396 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007397 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007398 /* unmapped character */
7399 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007400 l1 = ch >> 11;
7401 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007402 if (level1[l1] == 0xFF)
7403 level1[l1] = count2++;
7404 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007405 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007406 }
7407
7408 if (count2 >= 0xFF || count3 >= 0xFF)
7409 need_dict = 1;
7410
7411 if (need_dict) {
7412 PyObject *result = PyDict_New();
7413 PyObject *key, *value;
7414 if (!result)
7415 return NULL;
7416 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007417 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007418 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007419 if (!key || !value)
7420 goto failed1;
7421 if (PyDict_SetItem(result, key, value) == -1)
7422 goto failed1;
7423 Py_DECREF(key);
7424 Py_DECREF(value);
7425 }
7426 return result;
7427 failed1:
7428 Py_XDECREF(key);
7429 Py_XDECREF(value);
7430 Py_DECREF(result);
7431 return NULL;
7432 }
7433
7434 /* Create a three-level trie */
7435 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7436 16*count2 + 128*count3 - 1);
7437 if (!result)
7438 return PyErr_NoMemory();
7439 PyObject_Init(result, &EncodingMapType);
7440 mresult = (struct encoding_map*)result;
7441 mresult->count2 = count2;
7442 mresult->count3 = count3;
7443 mlevel1 = mresult->level1;
7444 mlevel2 = mresult->level23;
7445 mlevel3 = mresult->level23 + 16*count2;
7446 memcpy(mlevel1, level1, 32);
7447 memset(mlevel2, 0xFF, 16*count2);
7448 memset(mlevel3, 0, 128*count3);
7449 count3 = 0;
7450 for (i = 1; i < 256; i++) {
7451 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007452 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007453 /* unmapped character */
7454 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007455 o1 = PyUnicode_READ(kind, data, i)>>11;
7456 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007457 i2 = 16*mlevel1[o1] + o2;
7458 if (mlevel2[i2] == 0xFF)
7459 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007460 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007461 i3 = 128*mlevel2[i2] + o3;
7462 mlevel3[i3] = i;
7463 }
7464 return result;
7465}
7466
7467static int
7468encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
7469{
7470 struct encoding_map *map = (struct encoding_map*)mapping;
7471 int l1 = c>>11;
7472 int l2 = (c>>7) & 0xF;
7473 int l3 = c & 0x7F;
7474 int i;
7475
7476#ifdef Py_UNICODE_WIDE
7477 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007478 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007479 }
7480#endif
7481 if (c == 0)
7482 return 0;
7483 /* level 1*/
7484 i = map->level1[l1];
7485 if (i == 0xFF) {
7486 return -1;
7487 }
7488 /* level 2*/
7489 i = map->level23[16*i+l2];
7490 if (i == 0xFF) {
7491 return -1;
7492 }
7493 /* level 3 */
7494 i = map->level23[16*map->count2 + 128*i + l3];
7495 if (i == 0) {
7496 return -1;
7497 }
7498 return i;
7499}
7500
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007501/* Lookup the character ch in the mapping. If the character
7502 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007503 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007504static PyObject *
7505charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007506{
Christian Heimes217cfd12007-12-02 14:31:20 +00007507 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007508 PyObject *x;
7509
7510 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007511 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007512 x = PyObject_GetItem(mapping, w);
7513 Py_DECREF(w);
7514 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007515 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7516 /* No mapping found means: mapping is undefined. */
7517 PyErr_Clear();
7518 x = Py_None;
7519 Py_INCREF(x);
7520 return x;
7521 } else
7522 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007523 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007524 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007525 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007526 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007527 long value = PyLong_AS_LONG(x);
7528 if (value < 0 || value > 255) {
7529 PyErr_SetString(PyExc_TypeError,
7530 "character mapping must be in range(256)");
7531 Py_DECREF(x);
7532 return NULL;
7533 }
7534 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007535 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007536 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007537 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007538 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007539 /* wrong return value */
7540 PyErr_Format(PyExc_TypeError,
7541 "character mapping must return integer, bytes or None, not %.400s",
7542 x->ob_type->tp_name);
7543 Py_DECREF(x);
7544 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007545 }
7546}
7547
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007548static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007549charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007550{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007551 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7552 /* exponentially overallocate to minimize reallocations */
7553 if (requiredsize < 2*outsize)
7554 requiredsize = 2*outsize;
7555 if (_PyBytes_Resize(outobj, requiredsize))
7556 return -1;
7557 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007558}
7559
Benjamin Peterson14339b62009-01-31 16:36:08 +00007560typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007561 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007562} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007563/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007564 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007565 space is available. Return a new reference to the object that
7566 was put in the output buffer, or Py_None, if the mapping was undefined
7567 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007568 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007569static charmapencode_result
7570charmapencode_output(Py_UNICODE c, PyObject *mapping,
7571 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007572{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007573 PyObject *rep;
7574 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007575 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007576
Christian Heimes90aa7642007-12-19 02:45:37 +00007577 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007578 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007579 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007580 if (res == -1)
7581 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007582 if (outsize<requiredsize)
7583 if (charmapencode_resize(outobj, outpos, requiredsize))
7584 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007585 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007586 outstart[(*outpos)++] = (char)res;
7587 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007588 }
7589
7590 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007591 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007592 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007593 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007594 Py_DECREF(rep);
7595 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007596 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007597 if (PyLong_Check(rep)) {
7598 Py_ssize_t requiredsize = *outpos+1;
7599 if (outsize<requiredsize)
7600 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7601 Py_DECREF(rep);
7602 return enc_EXCEPTION;
7603 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007604 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007605 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007606 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007607 else {
7608 const char *repchars = PyBytes_AS_STRING(rep);
7609 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7610 Py_ssize_t requiredsize = *outpos+repsize;
7611 if (outsize<requiredsize)
7612 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7613 Py_DECREF(rep);
7614 return enc_EXCEPTION;
7615 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007616 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007617 memcpy(outstart + *outpos, repchars, repsize);
7618 *outpos += repsize;
7619 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007620 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007621 Py_DECREF(rep);
7622 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007623}
7624
7625/* handle an error in PyUnicode_EncodeCharmap
7626 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007627static int
7628charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00007629 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007630 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007631 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007632 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007633{
7634 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007635 Py_ssize_t repsize;
7636 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007637 Py_UNICODE *uni2;
7638 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007639 Py_ssize_t collstartpos = *inpos;
7640 Py_ssize_t collendpos = *inpos+1;
7641 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007642 char *encoding = "charmap";
7643 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007644 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007645
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007646 /* find all unencodable characters */
7647 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007648 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007649 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007650 int res = encoding_map_lookup(p[collendpos], mapping);
7651 if (res != -1)
7652 break;
7653 ++collendpos;
7654 continue;
7655 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007656
Benjamin Peterson29060642009-01-31 22:14:21 +00007657 rep = charmapencode_lookup(p[collendpos], mapping);
7658 if (rep==NULL)
7659 return -1;
7660 else if (rep!=Py_None) {
7661 Py_DECREF(rep);
7662 break;
7663 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007664 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007665 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007666 }
7667 /* cache callback name lookup
7668 * (if not done yet, i.e. it's the first error) */
7669 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007670 if ((errors==NULL) || (!strcmp(errors, "strict")))
7671 *known_errorHandler = 1;
7672 else if (!strcmp(errors, "replace"))
7673 *known_errorHandler = 2;
7674 else if (!strcmp(errors, "ignore"))
7675 *known_errorHandler = 3;
7676 else if (!strcmp(errors, "xmlcharrefreplace"))
7677 *known_errorHandler = 4;
7678 else
7679 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007680 }
7681 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007682 case 1: /* strict */
7683 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7684 return -1;
7685 case 2: /* replace */
7686 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007687 x = charmapencode_output('?', mapping, res, respos);
7688 if (x==enc_EXCEPTION) {
7689 return -1;
7690 }
7691 else if (x==enc_FAILED) {
7692 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7693 return -1;
7694 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007695 }
7696 /* fall through */
7697 case 3: /* ignore */
7698 *inpos = collendpos;
7699 break;
7700 case 4: /* xmlcharrefreplace */
7701 /* generate replacement (temporarily (mis)uses p) */
7702 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007703 char buffer[2+29+1+1];
7704 char *cp;
7705 sprintf(buffer, "&#%d;", (int)p[collpos]);
7706 for (cp = buffer; *cp; ++cp) {
7707 x = charmapencode_output(*cp, mapping, res, respos);
7708 if (x==enc_EXCEPTION)
7709 return -1;
7710 else if (x==enc_FAILED) {
7711 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7712 return -1;
7713 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007714 }
7715 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007716 *inpos = collendpos;
7717 break;
7718 default:
7719 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00007720 encoding, reason, p, size, exceptionObject,
7721 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007722 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007723 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00007724 if (PyBytes_Check(repunicode)) {
7725 /* Directly copy bytes result to output. */
7726 Py_ssize_t outsize = PyBytes_Size(*res);
7727 Py_ssize_t requiredsize;
7728 repsize = PyBytes_Size(repunicode);
7729 requiredsize = *respos + repsize;
7730 if (requiredsize > outsize)
7731 /* Make room for all additional bytes. */
7732 if (charmapencode_resize(res, respos, requiredsize)) {
7733 Py_DECREF(repunicode);
7734 return -1;
7735 }
7736 memcpy(PyBytes_AsString(*res) + *respos,
7737 PyBytes_AsString(repunicode), repsize);
7738 *respos += repsize;
7739 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007740 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00007741 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007742 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007743 /* generate replacement */
7744 repsize = PyUnicode_GET_SIZE(repunicode);
7745 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007746 x = charmapencode_output(*uni2, mapping, res, respos);
7747 if (x==enc_EXCEPTION) {
7748 return -1;
7749 }
7750 else if (x==enc_FAILED) {
7751 Py_DECREF(repunicode);
7752 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7753 return -1;
7754 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007755 }
7756 *inpos = newpos;
7757 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007758 }
7759 return 0;
7760}
7761
Alexander Belopolsky40018472011-02-26 01:02:56 +00007762PyObject *
7763PyUnicode_EncodeCharmap(const Py_UNICODE *p,
7764 Py_ssize_t size,
7765 PyObject *mapping,
7766 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007767{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007768 /* output object */
7769 PyObject *res = NULL;
7770 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007771 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007772 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007773 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007774 PyObject *errorHandler = NULL;
7775 PyObject *exc = NULL;
7776 /* the following variable is used for caching string comparisons
7777 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
7778 * 3=ignore, 4=xmlcharrefreplace */
7779 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007780
7781 /* Default to Latin-1 */
7782 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007783 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007784
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007785 /* allocate enough for a simple encoding without
7786 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00007787 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007788 if (res == NULL)
7789 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00007790 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007791 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007792
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007793 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007794 /* try to encode it */
7795 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
7796 if (x==enc_EXCEPTION) /* error */
7797 goto onError;
7798 if (x==enc_FAILED) { /* unencodable character */
7799 if (charmap_encoding_error(p, size, &inpos, mapping,
7800 &exc,
7801 &known_errorHandler, &errorHandler, errors,
7802 &res, &respos)) {
7803 goto onError;
7804 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007805 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007806 else
7807 /* done with this character => adjust input position */
7808 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007809 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007810
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007811 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00007812 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00007813 if (_PyBytes_Resize(&res, respos) < 0)
7814 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00007815
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007816 Py_XDECREF(exc);
7817 Py_XDECREF(errorHandler);
7818 return res;
7819
Benjamin Peterson29060642009-01-31 22:14:21 +00007820 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007821 Py_XDECREF(res);
7822 Py_XDECREF(exc);
7823 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007824 return NULL;
7825}
7826
Alexander Belopolsky40018472011-02-26 01:02:56 +00007827PyObject *
7828PyUnicode_AsCharmapString(PyObject *unicode,
7829 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007830{
7831 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007832 PyErr_BadArgument();
7833 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007834 }
7835 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00007836 PyUnicode_GET_SIZE(unicode),
7837 mapping,
7838 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007839}
7840
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007841/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007842static void
7843make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007844 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007845 Py_ssize_t startpos, Py_ssize_t endpos,
7846 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007847{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007848 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007849 *exceptionObject = _PyUnicodeTranslateError_Create(
7850 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007851 }
7852 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007853 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
7854 goto onError;
7855 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
7856 goto onError;
7857 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
7858 goto onError;
7859 return;
7860 onError:
7861 Py_DECREF(*exceptionObject);
7862 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007863 }
7864}
7865
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007866/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007867static void
7868raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007869 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007870 Py_ssize_t startpos, Py_ssize_t endpos,
7871 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007872{
7873 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007874 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007875 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007876 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007877}
7878
7879/* error handling callback helper:
7880 build arguments, call the callback and check the arguments,
7881 put the result into newpos and return the replacement string, which
7882 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007883static PyObject *
7884unicode_translate_call_errorhandler(const char *errors,
7885 PyObject **errorHandler,
7886 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007887 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007888 Py_ssize_t startpos, Py_ssize_t endpos,
7889 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007890{
Benjamin Peterson142957c2008-07-04 19:55:29 +00007891 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007892
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007893 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007894 PyObject *restuple;
7895 PyObject *resunicode;
7896
7897 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007898 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007899 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007900 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007901 }
7902
7903 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007904 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007905 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007906 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007907
7908 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00007909 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007910 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007911 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007912 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00007913 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00007914 Py_DECREF(restuple);
7915 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007916 }
7917 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00007918 &resunicode, &i_newpos)) {
7919 Py_DECREF(restuple);
7920 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007921 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00007922 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007923 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007924 else
7925 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007926 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007927 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
7928 Py_DECREF(restuple);
7929 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00007930 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007931 Py_INCREF(resunicode);
7932 Py_DECREF(restuple);
7933 return resunicode;
7934}
7935
7936/* Lookup the character ch in the mapping and put the result in result,
7937 which must be decrefed by the caller.
7938 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007939static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007940charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007941{
Christian Heimes217cfd12007-12-02 14:31:20 +00007942 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007943 PyObject *x;
7944
7945 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007946 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007947 x = PyObject_GetItem(mapping, w);
7948 Py_DECREF(w);
7949 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007950 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7951 /* No mapping found means: use 1:1 mapping. */
7952 PyErr_Clear();
7953 *result = NULL;
7954 return 0;
7955 } else
7956 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007957 }
7958 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007959 *result = x;
7960 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007961 }
Christian Heimes217cfd12007-12-02 14:31:20 +00007962 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007963 long value = PyLong_AS_LONG(x);
7964 long max = PyUnicode_GetMax();
7965 if (value < 0 || value > max) {
7966 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00007967 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00007968 Py_DECREF(x);
7969 return -1;
7970 }
7971 *result = x;
7972 return 0;
7973 }
7974 else if (PyUnicode_Check(x)) {
7975 *result = x;
7976 return 0;
7977 }
7978 else {
7979 /* wrong return value */
7980 PyErr_SetString(PyExc_TypeError,
7981 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007982 Py_DECREF(x);
7983 return -1;
7984 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007985}
7986/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00007987 if not reallocate and adjust various state variables.
7988 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007989static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007990charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00007991 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007992{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007993 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00007994 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007995 /* exponentially overallocate to minimize reallocations */
7996 if (requiredsize < 2 * oldsize)
7997 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007998 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
7999 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008000 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008001 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008002 }
8003 return 0;
8004}
8005/* lookup the character, put the result in the output string and adjust
8006 various state variables. Return a new reference to the object that
8007 was put in the output buffer in *result, or Py_None, if the mapping was
8008 undefined (in which case no character was written).
8009 The called must decref result.
8010 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008011static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008012charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8013 PyObject *mapping, Py_UCS4 **output,
8014 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008015 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008016{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008017 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8018 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008019 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008020 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008021 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008022 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008023 }
8024 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008025 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008026 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008027 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008028 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008029 }
8030 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008031 Py_ssize_t repsize;
8032 if (PyUnicode_READY(*res) == -1)
8033 return -1;
8034 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008035 if (repsize==1) {
8036 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008037 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008038 }
8039 else if (repsize!=0) {
8040 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008041 Py_ssize_t requiredsize = *opos +
8042 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008043 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008044 Py_ssize_t i;
8045 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008046 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008047 for(i = 0; i < repsize; i++)
8048 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008049 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008050 }
8051 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008052 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008053 return 0;
8054}
8055
Alexander Belopolsky40018472011-02-26 01:02:56 +00008056PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008057_PyUnicode_TranslateCharmap(PyObject *input,
8058 PyObject *mapping,
8059 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008060{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008061 /* input object */
8062 char *idata;
8063 Py_ssize_t size, i;
8064 int kind;
8065 /* output buffer */
8066 Py_UCS4 *output = NULL;
8067 Py_ssize_t osize;
8068 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008069 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008070 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008071 char *reason = "character maps to <undefined>";
8072 PyObject *errorHandler = NULL;
8073 PyObject *exc = NULL;
8074 /* the following variable is used for caching string comparisons
8075 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8076 * 3=ignore, 4=xmlcharrefreplace */
8077 int known_errorHandler = -1;
8078
Guido van Rossumd57fd912000-03-10 22:53:23 +00008079 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008080 PyErr_BadArgument();
8081 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008082 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008083
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008084 if (PyUnicode_READY(input) == -1)
8085 return NULL;
8086 idata = (char*)PyUnicode_DATA(input);
8087 kind = PyUnicode_KIND(input);
8088 size = PyUnicode_GET_LENGTH(input);
8089 i = 0;
8090
8091 if (size == 0) {
8092 Py_INCREF(input);
8093 return input;
8094 }
8095
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008096 /* allocate enough for a simple 1:1 translation without
8097 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008098 osize = size;
8099 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8100 opos = 0;
8101 if (output == NULL) {
8102 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008103 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008104 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008105
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008106 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008107 /* try to encode it */
8108 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008109 if (charmaptranslate_output(input, i, mapping,
8110 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008111 Py_XDECREF(x);
8112 goto onError;
8113 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008114 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008115 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008116 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008117 else { /* untranslatable character */
8118 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8119 Py_ssize_t repsize;
8120 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008121 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008122 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008123 Py_ssize_t collstart = i;
8124 Py_ssize_t collend = i+1;
8125 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008126
Benjamin Peterson29060642009-01-31 22:14:21 +00008127 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008128 while (collend < size) {
8129 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008130 goto onError;
8131 Py_XDECREF(x);
8132 if (x!=Py_None)
8133 break;
8134 ++collend;
8135 }
8136 /* cache callback name lookup
8137 * (if not done yet, i.e. it's the first error) */
8138 if (known_errorHandler==-1) {
8139 if ((errors==NULL) || (!strcmp(errors, "strict")))
8140 known_errorHandler = 1;
8141 else if (!strcmp(errors, "replace"))
8142 known_errorHandler = 2;
8143 else if (!strcmp(errors, "ignore"))
8144 known_errorHandler = 3;
8145 else if (!strcmp(errors, "xmlcharrefreplace"))
8146 known_errorHandler = 4;
8147 else
8148 known_errorHandler = 0;
8149 }
8150 switch (known_errorHandler) {
8151 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008152 raise_translate_exception(&exc, input, collstart,
8153 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008154 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008155 case 2: /* replace */
8156 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008157 for (coll = collstart; coll<collend; coll++)
8158 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008159 /* fall through */
8160 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008161 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008162 break;
8163 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008164 /* generate replacement (temporarily (mis)uses i) */
8165 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008166 char buffer[2+29+1+1];
8167 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008168 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8169 if (charmaptranslate_makespace(&output, &osize,
8170 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008171 goto onError;
8172 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008173 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008174 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008175 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008176 break;
8177 default:
8178 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008179 reason, input, &exc,
8180 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008181 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008182 goto onError;
8183 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008184 repsize = PyUnicode_GET_LENGTH(repunicode);
8185 if (charmaptranslate_makespace(&output, &osize,
8186 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008187 Py_DECREF(repunicode);
8188 goto onError;
8189 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008190 for (uni2 = 0; repsize-->0; ++uni2)
8191 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8192 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008193 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008194 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008195 }
8196 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008197 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8198 if (!res)
8199 goto onError;
8200 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008201 Py_XDECREF(exc);
8202 Py_XDECREF(errorHandler);
8203 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008204
Benjamin Peterson29060642009-01-31 22:14:21 +00008205 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008206 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008207 Py_XDECREF(exc);
8208 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008209 return NULL;
8210}
8211
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008212/* Deprecated. Use PyUnicode_Translate instead. */
8213PyObject *
8214PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8215 Py_ssize_t size,
8216 PyObject *mapping,
8217 const char *errors)
8218{
8219 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8220 if (!unicode)
8221 return NULL;
8222 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8223}
8224
Alexander Belopolsky40018472011-02-26 01:02:56 +00008225PyObject *
8226PyUnicode_Translate(PyObject *str,
8227 PyObject *mapping,
8228 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008229{
8230 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008231
Guido van Rossumd57fd912000-03-10 22:53:23 +00008232 str = PyUnicode_FromObject(str);
8233 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008234 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008235 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008236 Py_DECREF(str);
8237 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008238
Benjamin Peterson29060642009-01-31 22:14:21 +00008239 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008240 Py_XDECREF(str);
8241 return NULL;
8242}
Tim Petersced69f82003-09-16 20:30:58 +00008243
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008244static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008245fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008246{
8247 /* No need to call PyUnicode_READY(self) because this function is only
8248 called as a callback from fixup() which does it already. */
8249 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8250 const int kind = PyUnicode_KIND(self);
8251 void *data = PyUnicode_DATA(self);
8252 Py_UCS4 maxchar = 0, ch, fixed;
8253 Py_ssize_t i;
8254
8255 for (i = 0; i < len; ++i) {
8256 ch = PyUnicode_READ(kind, data, i);
8257 fixed = 0;
8258 if (ch > 127) {
8259 if (Py_UNICODE_ISSPACE(ch))
8260 fixed = ' ';
8261 else {
8262 const int decimal = Py_UNICODE_TODECIMAL(ch);
8263 if (decimal >= 0)
8264 fixed = '0' + decimal;
8265 }
8266 if (fixed != 0) {
8267 if (fixed > maxchar)
8268 maxchar = fixed;
8269 PyUnicode_WRITE(kind, data, i, fixed);
8270 }
8271 else if (ch > maxchar)
8272 maxchar = ch;
8273 }
8274 else if (ch > maxchar)
8275 maxchar = ch;
8276 }
8277
8278 return maxchar;
8279}
8280
8281PyObject *
8282_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8283{
8284 if (!PyUnicode_Check(unicode)) {
8285 PyErr_BadInternalCall();
8286 return NULL;
8287 }
8288 if (PyUnicode_READY(unicode) == -1)
8289 return NULL;
8290 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8291 /* If the string is already ASCII, just return the same string */
8292 Py_INCREF(unicode);
8293 return unicode;
8294 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008295 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008296}
8297
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008298PyObject *
8299PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8300 Py_ssize_t length)
8301{
8302 PyObject *result;
8303 Py_UNICODE *p; /* write pointer into result */
8304 Py_ssize_t i;
8305 /* Copy to a new string */
8306 result = (PyObject *)_PyUnicode_New(length);
8307 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8308 if (result == NULL)
8309 return result;
8310 p = PyUnicode_AS_UNICODE(result);
8311 /* Iterate over code points */
8312 for (i = 0; i < length; i++) {
8313 Py_UNICODE ch =s[i];
8314 if (ch > 127) {
8315 int decimal = Py_UNICODE_TODECIMAL(ch);
8316 if (decimal >= 0)
8317 p[i] = '0' + decimal;
8318 }
8319 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008320#ifndef DONT_MAKE_RESULT_READY
8321 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008322 Py_DECREF(result);
8323 return NULL;
8324 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008325#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008326 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008327 return result;
8328}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008329/* --- Decimal Encoder ---------------------------------------------------- */
8330
Alexander Belopolsky40018472011-02-26 01:02:56 +00008331int
8332PyUnicode_EncodeDecimal(Py_UNICODE *s,
8333 Py_ssize_t length,
8334 char *output,
8335 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008336{
8337 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008338 PyObject *errorHandler = NULL;
8339 PyObject *exc = NULL;
8340 const char *encoding = "decimal";
8341 const char *reason = "invalid decimal Unicode string";
8342 /* the following variable is used for caching string comparisons
8343 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8344 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008345
8346 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008347 PyErr_BadArgument();
8348 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008349 }
8350
8351 p = s;
8352 end = s + length;
8353 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008354 register Py_UNICODE ch = *p;
8355 int decimal;
8356 PyObject *repunicode;
8357 Py_ssize_t repsize;
8358 Py_ssize_t newpos;
8359 Py_UNICODE *uni2;
8360 Py_UNICODE *collstart;
8361 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008362
Benjamin Peterson29060642009-01-31 22:14:21 +00008363 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008364 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008365 ++p;
8366 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008367 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008368 decimal = Py_UNICODE_TODECIMAL(ch);
8369 if (decimal >= 0) {
8370 *output++ = '0' + decimal;
8371 ++p;
8372 continue;
8373 }
8374 if (0 < ch && ch < 256) {
8375 *output++ = (char)ch;
8376 ++p;
8377 continue;
8378 }
8379 /* All other characters are considered unencodable */
8380 collstart = p;
8381 collend = p+1;
8382 while (collend < end) {
8383 if ((0 < *collend && *collend < 256) ||
8384 !Py_UNICODE_ISSPACE(*collend) ||
8385 Py_UNICODE_TODECIMAL(*collend))
8386 break;
8387 }
8388 /* cache callback name lookup
8389 * (if not done yet, i.e. it's the first error) */
8390 if (known_errorHandler==-1) {
8391 if ((errors==NULL) || (!strcmp(errors, "strict")))
8392 known_errorHandler = 1;
8393 else if (!strcmp(errors, "replace"))
8394 known_errorHandler = 2;
8395 else if (!strcmp(errors, "ignore"))
8396 known_errorHandler = 3;
8397 else if (!strcmp(errors, "xmlcharrefreplace"))
8398 known_errorHandler = 4;
8399 else
8400 known_errorHandler = 0;
8401 }
8402 switch (known_errorHandler) {
8403 case 1: /* strict */
8404 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
8405 goto onError;
8406 case 2: /* replace */
8407 for (p = collstart; p < collend; ++p)
8408 *output++ = '?';
8409 /* fall through */
8410 case 3: /* ignore */
8411 p = collend;
8412 break;
8413 case 4: /* xmlcharrefreplace */
8414 /* generate replacement (temporarily (mis)uses p) */
8415 for (p = collstart; p < collend; ++p)
8416 output += sprintf(output, "&#%d;", (int)*p);
8417 p = collend;
8418 break;
8419 default:
8420 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
8421 encoding, reason, s, length, &exc,
8422 collstart-s, collend-s, &newpos);
8423 if (repunicode == NULL)
8424 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008425 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008426 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008427 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8428 Py_DECREF(repunicode);
8429 goto onError;
8430 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008431 /* generate replacement */
8432 repsize = PyUnicode_GET_SIZE(repunicode);
8433 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
8434 Py_UNICODE ch = *uni2;
8435 if (Py_UNICODE_ISSPACE(ch))
8436 *output++ = ' ';
8437 else {
8438 decimal = Py_UNICODE_TODECIMAL(ch);
8439 if (decimal >= 0)
8440 *output++ = '0' + decimal;
8441 else if (0 < ch && ch < 256)
8442 *output++ = (char)ch;
8443 else {
8444 Py_DECREF(repunicode);
8445 raise_encode_exception(&exc, encoding,
8446 s, length, collstart-s, collend-s, reason);
8447 goto onError;
8448 }
8449 }
8450 }
8451 p = s + newpos;
8452 Py_DECREF(repunicode);
8453 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008454 }
8455 /* 0-terminate the output string */
8456 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008457 Py_XDECREF(exc);
8458 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008459 return 0;
8460
Benjamin Peterson29060642009-01-31 22:14:21 +00008461 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008462 Py_XDECREF(exc);
8463 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008464 return -1;
8465}
8466
Guido van Rossumd57fd912000-03-10 22:53:23 +00008467/* --- Helpers ------------------------------------------------------------ */
8468
Victor Stinnerc3cec782011-10-05 21:24:08 +02008469#include "stringlib/asciilib.h"
8470#include "stringlib/fastsearch.h"
8471#include "stringlib/partition.h"
8472#include "stringlib/split.h"
8473#include "stringlib/count.h"
8474#include "stringlib/find.h"
8475#include "stringlib/localeutil.h"
8476#include "stringlib/undef.h"
8477
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008478#include "stringlib/ucs1lib.h"
8479#include "stringlib/fastsearch.h"
8480#include "stringlib/partition.h"
8481#include "stringlib/split.h"
8482#include "stringlib/count.h"
8483#include "stringlib/find.h"
8484#include "stringlib/localeutil.h"
8485#include "stringlib/undef.h"
8486
8487#include "stringlib/ucs2lib.h"
8488#include "stringlib/fastsearch.h"
8489#include "stringlib/partition.h"
8490#include "stringlib/split.h"
8491#include "stringlib/count.h"
8492#include "stringlib/find.h"
8493#include "stringlib/localeutil.h"
8494#include "stringlib/undef.h"
8495
8496#include "stringlib/ucs4lib.h"
8497#include "stringlib/fastsearch.h"
8498#include "stringlib/partition.h"
8499#include "stringlib/split.h"
8500#include "stringlib/count.h"
8501#include "stringlib/find.h"
8502#include "stringlib/localeutil.h"
8503#include "stringlib/undef.h"
8504
8505static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02008506any_find_slice(Py_ssize_t Py_LOCAL_CALLBACK(ascii)(const Py_UCS1*, Py_ssize_t,
8507 const Py_UCS1*, Py_ssize_t,
8508 Py_ssize_t, Py_ssize_t),
8509 Py_ssize_t Py_LOCAL_CALLBACK(ucs1)(const Py_UCS1*, Py_ssize_t,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008510 const Py_UCS1*, Py_ssize_t,
8511 Py_ssize_t, Py_ssize_t),
8512 Py_ssize_t Py_LOCAL_CALLBACK(ucs2)(const Py_UCS2*, Py_ssize_t,
8513 const Py_UCS2*, Py_ssize_t,
8514 Py_ssize_t, Py_ssize_t),
8515 Py_ssize_t Py_LOCAL_CALLBACK(ucs4)(const Py_UCS4*, Py_ssize_t,
8516 const Py_UCS4*, Py_ssize_t,
8517 Py_ssize_t, Py_ssize_t),
8518 PyObject* s1, PyObject* s2,
8519 Py_ssize_t start,
8520 Py_ssize_t end)
8521{
8522 int kind1, kind2, kind;
8523 void *buf1, *buf2;
8524 Py_ssize_t len1, len2, result;
8525
8526 kind1 = PyUnicode_KIND(s1);
8527 kind2 = PyUnicode_KIND(s2);
8528 kind = kind1 > kind2 ? kind1 : kind2;
8529 buf1 = PyUnicode_DATA(s1);
8530 buf2 = PyUnicode_DATA(s2);
8531 if (kind1 != kind)
8532 buf1 = _PyUnicode_AsKind(s1, kind);
8533 if (!buf1)
8534 return -2;
8535 if (kind2 != kind)
8536 buf2 = _PyUnicode_AsKind(s2, kind);
8537 if (!buf2) {
8538 if (kind1 != kind) PyMem_Free(buf1);
8539 return -2;
8540 }
8541 len1 = PyUnicode_GET_LENGTH(s1);
8542 len2 = PyUnicode_GET_LENGTH(s2);
8543
8544 switch(kind) {
8545 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008546 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8547 result = ascii(buf1, len1, buf2, len2, start, end);
8548 else
8549 result = ucs1(buf1, len1, buf2, len2, start, end);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008550 break;
8551 case PyUnicode_2BYTE_KIND:
8552 result = ucs2(buf1, len1, buf2, len2, start, end);
8553 break;
8554 case PyUnicode_4BYTE_KIND:
8555 result = ucs4(buf1, len1, buf2, len2, start, end);
8556 break;
8557 default:
8558 assert(0); result = -2;
8559 }
8560
8561 if (kind1 != kind)
8562 PyMem_Free(buf1);
8563 if (kind2 != kind)
8564 PyMem_Free(buf2);
8565
8566 return result;
8567}
8568
8569Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02008570_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008571 Py_ssize_t n_buffer,
8572 void *digits, Py_ssize_t n_digits,
8573 Py_ssize_t min_width,
8574 const char *grouping,
8575 const char *thousands_sep)
8576{
8577 switch(kind) {
8578 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008579 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
8580 return _PyUnicode_ascii_InsertThousandsGrouping(
8581 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
8582 min_width, grouping, thousands_sep);
8583 else
8584 return _PyUnicode_ucs1_InsertThousandsGrouping(
8585 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
8586 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008587 case PyUnicode_2BYTE_KIND:
8588 return _PyUnicode_ucs2_InsertThousandsGrouping(
8589 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
8590 min_width, grouping, thousands_sep);
8591 case PyUnicode_4BYTE_KIND:
8592 return _PyUnicode_ucs4_InsertThousandsGrouping(
8593 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
8594 min_width, grouping, thousands_sep);
8595 }
8596 assert(0);
8597 return -1;
8598}
8599
8600
Eric Smith8c663262007-08-25 02:26:07 +00008601#include "stringlib/unicodedefs.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00008602#include "stringlib/fastsearch.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008603
Thomas Wouters477c8d52006-05-27 19:21:47 +00008604#include "stringlib/count.h"
8605#include "stringlib/find.h"
Eric Smith5807c412008-05-11 21:00:57 +00008606
Thomas Wouters477c8d52006-05-27 19:21:47 +00008607/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008608#define ADJUST_INDICES(start, end, len) \
8609 if (end > len) \
8610 end = len; \
8611 else if (end < 0) { \
8612 end += len; \
8613 if (end < 0) \
8614 end = 0; \
8615 } \
8616 if (start < 0) { \
8617 start += len; \
8618 if (start < 0) \
8619 start = 0; \
8620 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008621
Alexander Belopolsky40018472011-02-26 01:02:56 +00008622Py_ssize_t
8623PyUnicode_Count(PyObject *str,
8624 PyObject *substr,
8625 Py_ssize_t start,
8626 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008627{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008628 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008629 PyUnicodeObject* str_obj;
8630 PyUnicodeObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008631 int kind1, kind2, kind;
8632 void *buf1 = NULL, *buf2 = NULL;
8633 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008634
Thomas Wouters477c8d52006-05-27 19:21:47 +00008635 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008636 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008637 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008638 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02008639 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008640 Py_DECREF(str_obj);
8641 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008642 }
Tim Petersced69f82003-09-16 20:30:58 +00008643
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008644 kind1 = PyUnicode_KIND(str_obj);
8645 kind2 = PyUnicode_KIND(sub_obj);
8646 kind = kind1 > kind2 ? kind1 : kind2;
8647 buf1 = PyUnicode_DATA(str_obj);
8648 if (kind1 != kind)
8649 buf1 = _PyUnicode_AsKind((PyObject*)str_obj, kind);
8650 if (!buf1)
8651 goto onError;
8652 buf2 = PyUnicode_DATA(sub_obj);
8653 if (kind2 != kind)
8654 buf2 = _PyUnicode_AsKind((PyObject*)sub_obj, kind);
8655 if (!buf2)
8656 goto onError;
8657 len1 = PyUnicode_GET_LENGTH(str_obj);
8658 len2 = PyUnicode_GET_LENGTH(sub_obj);
8659
8660 ADJUST_INDICES(start, end, len1);
8661 switch(kind) {
8662 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008663 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
8664 result = asciilib_count(
8665 ((Py_UCS1*)buf1) + start, end - start,
8666 buf2, len2, PY_SSIZE_T_MAX
8667 );
8668 else
8669 result = ucs1lib_count(
8670 ((Py_UCS1*)buf1) + start, end - start,
8671 buf2, len2, PY_SSIZE_T_MAX
8672 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008673 break;
8674 case PyUnicode_2BYTE_KIND:
8675 result = ucs2lib_count(
8676 ((Py_UCS2*)buf1) + start, end - start,
8677 buf2, len2, PY_SSIZE_T_MAX
8678 );
8679 break;
8680 case PyUnicode_4BYTE_KIND:
8681 result = ucs4lib_count(
8682 ((Py_UCS4*)buf1) + start, end - start,
8683 buf2, len2, PY_SSIZE_T_MAX
8684 );
8685 break;
8686 default:
8687 assert(0); result = 0;
8688 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008689
8690 Py_DECREF(sub_obj);
8691 Py_DECREF(str_obj);
8692
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008693 if (kind1 != kind)
8694 PyMem_Free(buf1);
8695 if (kind2 != kind)
8696 PyMem_Free(buf2);
8697
Guido van Rossumd57fd912000-03-10 22:53:23 +00008698 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008699 onError:
8700 Py_DECREF(sub_obj);
8701 Py_DECREF(str_obj);
8702 if (kind1 != kind && buf1)
8703 PyMem_Free(buf1);
8704 if (kind2 != kind && buf2)
8705 PyMem_Free(buf2);
8706 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008707}
8708
Alexander Belopolsky40018472011-02-26 01:02:56 +00008709Py_ssize_t
8710PyUnicode_Find(PyObject *str,
8711 PyObject *sub,
8712 Py_ssize_t start,
8713 Py_ssize_t end,
8714 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008715{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008716 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008717
Guido van Rossumd57fd912000-03-10 22:53:23 +00008718 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008719 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008720 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008721 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008722 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008723 Py_DECREF(str);
8724 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008725 }
Tim Petersced69f82003-09-16 20:30:58 +00008726
Thomas Wouters477c8d52006-05-27 19:21:47 +00008727 if (direction > 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008728 result = any_find_slice(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008729 asciilib_find_slice, ucs1lib_find_slice,
8730 ucs2lib_find_slice, ucs4lib_find_slice,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008731 str, sub, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +00008732 );
8733 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008734 result = any_find_slice(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008735 asciilib_find_slice, ucs1lib_rfind_slice,
8736 ucs2lib_rfind_slice, ucs4lib_rfind_slice,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008737 str, sub, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +00008738 );
8739
Guido van Rossumd57fd912000-03-10 22:53:23 +00008740 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008741 Py_DECREF(sub);
8742
Guido van Rossumd57fd912000-03-10 22:53:23 +00008743 return result;
8744}
8745
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008746Py_ssize_t
8747PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
8748 Py_ssize_t start, Py_ssize_t end,
8749 int direction)
8750{
8751 char *result;
8752 int kind;
8753 if (PyUnicode_READY(str) == -1)
8754 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02008755 if (start < 0 || end < 0) {
8756 PyErr_SetString(PyExc_IndexError, "string index out of range");
8757 return -2;
8758 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008759 if (end > PyUnicode_GET_LENGTH(str))
8760 end = PyUnicode_GET_LENGTH(str);
8761 kind = PyUnicode_KIND(str);
8762 result = findchar(PyUnicode_1BYTE_DATA(str)
8763 + PyUnicode_KIND_SIZE(kind, start),
8764 kind,
8765 end-start, ch, direction);
8766 if (!result)
8767 return -1;
8768 return (result-(char*)PyUnicode_DATA(str)) >> (kind-1);
8769}
8770
Alexander Belopolsky40018472011-02-26 01:02:56 +00008771static int
8772tailmatch(PyUnicodeObject *self,
8773 PyUnicodeObject *substring,
8774 Py_ssize_t start,
8775 Py_ssize_t end,
8776 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008777{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008778 int kind_self;
8779 int kind_sub;
8780 void *data_self;
8781 void *data_sub;
8782 Py_ssize_t offset;
8783 Py_ssize_t i;
8784 Py_ssize_t end_sub;
8785
8786 if (PyUnicode_READY(self) == -1 ||
8787 PyUnicode_READY(substring) == -1)
8788 return 0;
8789
8790 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008791 return 1;
8792
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008793 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
8794 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008795 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00008796 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008797
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008798 kind_self = PyUnicode_KIND(self);
8799 data_self = PyUnicode_DATA(self);
8800 kind_sub = PyUnicode_KIND(substring);
8801 data_sub = PyUnicode_DATA(substring);
8802 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
8803
8804 if (direction > 0)
8805 offset = end;
8806 else
8807 offset = start;
8808
8809 if (PyUnicode_READ(kind_self, data_self, offset) ==
8810 PyUnicode_READ(kind_sub, data_sub, 0) &&
8811 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
8812 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
8813 /* If both are of the same kind, memcmp is sufficient */
8814 if (kind_self == kind_sub) {
8815 return ! memcmp((char *)data_self +
8816 (offset * PyUnicode_CHARACTER_SIZE(substring)),
8817 data_sub,
8818 PyUnicode_GET_LENGTH(substring) *
8819 PyUnicode_CHARACTER_SIZE(substring));
8820 }
8821 /* otherwise we have to compare each character by first accesing it */
8822 else {
8823 /* We do not need to compare 0 and len(substring)-1 because
8824 the if statement above ensured already that they are equal
8825 when we end up here. */
8826 // TODO: honor direction and do a forward or backwards search
8827 for (i = 1; i < end_sub; ++i) {
8828 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
8829 PyUnicode_READ(kind_sub, data_sub, i))
8830 return 0;
8831 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008832 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008833 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008834 }
8835
8836 return 0;
8837}
8838
Alexander Belopolsky40018472011-02-26 01:02:56 +00008839Py_ssize_t
8840PyUnicode_Tailmatch(PyObject *str,
8841 PyObject *substr,
8842 Py_ssize_t start,
8843 Py_ssize_t end,
8844 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008845{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008846 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008847
Guido van Rossumd57fd912000-03-10 22:53:23 +00008848 str = PyUnicode_FromObject(str);
8849 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008850 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008851 substr = PyUnicode_FromObject(substr);
8852 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008853 Py_DECREF(str);
8854 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008855 }
Tim Petersced69f82003-09-16 20:30:58 +00008856
Guido van Rossumd57fd912000-03-10 22:53:23 +00008857 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00008858 (PyUnicodeObject *)substr,
8859 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008860 Py_DECREF(str);
8861 Py_DECREF(substr);
8862 return result;
8863}
8864
Guido van Rossumd57fd912000-03-10 22:53:23 +00008865/* Apply fixfct filter to the Unicode object self and return a
8866 reference to the modified object */
8867
Alexander Belopolsky40018472011-02-26 01:02:56 +00008868static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02008869fixup(PyObject *self,
8870 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008871{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008872 PyObject *u;
8873 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008874
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008875 if (PyUnicode_READY(self) == -1)
8876 return NULL;
8877 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
8878 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
8879 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008880 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008881 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00008882
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008883 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
8884 PyUnicode_GET_LENGTH(u) * PyUnicode_CHARACTER_SIZE(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00008885
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008886 /* fix functions return the new maximum character in a string,
8887 if the kind of the resulting unicode object does not change,
8888 everything is fine. Otherwise we need to change the string kind
8889 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02008890 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008891 if (maxchar_new == 0)
8892 /* do nothing, keep maxchar_new at 0 which means no changes. */;
8893 else if (maxchar_new <= 127)
8894 maxchar_new = 127;
8895 else if (maxchar_new <= 255)
8896 maxchar_new = 255;
8897 else if (maxchar_new <= 65535)
8898 maxchar_new = 65535;
8899 else
8900 maxchar_new = 1114111; /* 0x10ffff */
8901
8902 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008903 /* fixfct should return TRUE if it modified the buffer. If
8904 FALSE, return a reference to the original buffer instead
8905 (to save space, not time) */
8906 Py_INCREF(self);
8907 Py_DECREF(u);
8908 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008909 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008910 else if (maxchar_new == maxchar_old) {
8911 return u;
8912 }
8913 else {
8914 /* In case the maximum character changed, we need to
8915 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008916 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008917 if (v == NULL) {
8918 Py_DECREF(u);
8919 return NULL;
8920 }
8921 if (maxchar_new > maxchar_old) {
8922 /* If the maxchar increased so that the kind changed, not all
8923 characters are representable anymore and we need to fix the
8924 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02008925 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02008926 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008927 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
8928 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008929 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02008930 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008931 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008932
8933 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008934 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008935 return v;
8936 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008937}
8938
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008939static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008940fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008941{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008942 /* No need to call PyUnicode_READY(self) because this function is only
8943 called as a callback from fixup() which does it already. */
8944 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8945 const int kind = PyUnicode_KIND(self);
8946 void *data = PyUnicode_DATA(self);
8947 int touched = 0;
8948 Py_UCS4 maxchar = 0;
8949 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008950
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008951 for (i = 0; i < len; ++i) {
8952 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8953 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
8954 if (up != ch) {
8955 if (up > maxchar)
8956 maxchar = up;
8957 PyUnicode_WRITE(kind, data, i, up);
8958 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008959 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008960 else if (ch > maxchar)
8961 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008962 }
8963
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008964 if (touched)
8965 return maxchar;
8966 else
8967 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008968}
8969
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008970static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008971fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008972{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008973 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8974 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8975 const int kind = PyUnicode_KIND(self);
8976 void *data = PyUnicode_DATA(self);
8977 int touched = 0;
8978 Py_UCS4 maxchar = 0;
8979 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008980
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008981 for(i = 0; i < len; ++i) {
8982 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8983 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
8984 if (lo != ch) {
8985 if (lo > maxchar)
8986 maxchar = lo;
8987 PyUnicode_WRITE(kind, data, i, lo);
8988 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008989 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008990 else if (ch > maxchar)
8991 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008992 }
8993
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008994 if (touched)
8995 return maxchar;
8996 else
8997 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008998}
8999
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009000static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009001fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009002{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009003 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9004 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9005 const int kind = PyUnicode_KIND(self);
9006 void *data = PyUnicode_DATA(self);
9007 int touched = 0;
9008 Py_UCS4 maxchar = 0;
9009 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009010
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009011 for(i = 0; i < len; ++i) {
9012 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9013 Py_UCS4 nu = 0;
9014
9015 if (Py_UNICODE_ISUPPER(ch))
9016 nu = Py_UNICODE_TOLOWER(ch);
9017 else if (Py_UNICODE_ISLOWER(ch))
9018 nu = Py_UNICODE_TOUPPER(ch);
9019
9020 if (nu != 0) {
9021 if (nu > maxchar)
9022 maxchar = nu;
9023 PyUnicode_WRITE(kind, data, i, nu);
9024 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009025 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009026 else if (ch > maxchar)
9027 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009028 }
9029
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009030 if (touched)
9031 return maxchar;
9032 else
9033 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009034}
9035
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009036static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009037fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009038{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009039 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9040 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9041 const int kind = PyUnicode_KIND(self);
9042 void *data = PyUnicode_DATA(self);
9043 int touched = 0;
9044 Py_UCS4 maxchar = 0;
9045 Py_ssize_t i = 0;
9046 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009047
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009048 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009049 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009050
9051 ch = PyUnicode_READ(kind, data, i);
9052 if (!Py_UNICODE_ISUPPER(ch)) {
9053 maxchar = Py_UNICODE_TOUPPER(ch);
9054 PyUnicode_WRITE(kind, data, i, maxchar);
9055 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009056 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009057 ++i;
9058 for(; i < len; ++i) {
9059 ch = PyUnicode_READ(kind, data, i);
9060 if (!Py_UNICODE_ISLOWER(ch)) {
9061 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9062 if (lo > maxchar)
9063 maxchar = lo;
9064 PyUnicode_WRITE(kind, data, i, lo);
9065 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009066 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009067 else if (ch > maxchar)
9068 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009069 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009070
9071 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 +02009078fixtitle(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 Py_UCS4 maxchar = 0;
9085 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009086 int previous_is_cased;
9087
9088 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009089 if (len == 1) {
9090 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9091 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9092 if (ti != ch) {
9093 PyUnicode_WRITE(kind, data, i, ti);
9094 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009095 }
9096 else
9097 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009098 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009099 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009100 for(; i < len; ++i) {
9101 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9102 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009103
Benjamin Peterson29060642009-01-31 22:14:21 +00009104 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009105 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009106 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009107 nu = Py_UNICODE_TOTITLE(ch);
9108
9109 if (nu > maxchar)
9110 maxchar = nu;
9111 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009112
Benjamin Peterson29060642009-01-31 22:14:21 +00009113 if (Py_UNICODE_ISLOWER(ch) ||
9114 Py_UNICODE_ISUPPER(ch) ||
9115 Py_UNICODE_ISTITLE(ch))
9116 previous_is_cased = 1;
9117 else
9118 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009119 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009120 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009121}
9122
Tim Peters8ce9f162004-08-27 01:49:32 +00009123PyObject *
9124PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009125{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009126 PyObject *sep = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009127 Py_ssize_t seplen = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009128 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009129 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009130 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9131 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009132 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009133 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009134 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009135 Py_UCS4 item_maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009136
Tim Peters05eba1f2004-08-27 21:32:02 +00009137 fseq = PySequence_Fast(seq, "");
9138 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009139 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009140 }
9141
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009142 /* NOTE: the following code can't call back into Python code,
9143 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009144 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009145
Tim Peters05eba1f2004-08-27 21:32:02 +00009146 seqlen = PySequence_Fast_GET_SIZE(fseq);
9147 /* If empty sequence, return u"". */
9148 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009149 Py_DECREF(fseq);
9150 Py_INCREF(unicode_empty);
9151 res = unicode_empty;
9152 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009153 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009154
Tim Peters05eba1f2004-08-27 21:32:02 +00009155 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009156 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009157 if (seqlen == 1) {
9158 if (PyUnicode_CheckExact(items[0])) {
9159 res = items[0];
9160 Py_INCREF(res);
9161 Py_DECREF(fseq);
9162 return res;
9163 }
9164 sep = NULL;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009165 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009166 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009167 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009168 /* Set up sep and seplen */
9169 if (separator == NULL) {
9170 /* fall back to a blank space separator */
9171 sep = PyUnicode_FromOrdinal(' ');
9172 if (!sep)
9173 goto onError;
9174 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009175 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009176 else {
9177 if (!PyUnicode_Check(separator)) {
9178 PyErr_Format(PyExc_TypeError,
9179 "separator: expected str instance,"
9180 " %.80s found",
9181 Py_TYPE(separator)->tp_name);
9182 goto onError;
9183 }
9184 if (PyUnicode_READY(separator))
9185 goto onError;
9186 sep = separator;
9187 seplen = PyUnicode_GET_LENGTH(separator);
9188 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9189 /* inc refcount to keep this code path symmetric with the
9190 above case of a blank separator */
9191 Py_INCREF(sep);
9192 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009193 }
9194
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009195 /* There are at least two things to join, or else we have a subclass
9196 * of str in the sequence.
9197 * Do a pre-pass to figure out the total amount of space we'll
9198 * need (sz), and see whether all argument are strings.
9199 */
9200 sz = 0;
9201 for (i = 0; i < seqlen; i++) {
9202 const Py_ssize_t old_sz = sz;
9203 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009204 if (!PyUnicode_Check(item)) {
9205 PyErr_Format(PyExc_TypeError,
9206 "sequence item %zd: expected str instance,"
9207 " %.80s found",
9208 i, Py_TYPE(item)->tp_name);
9209 goto onError;
9210 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009211 if (PyUnicode_READY(item) == -1)
9212 goto onError;
9213 sz += PyUnicode_GET_LENGTH(item);
9214 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009215 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009216 if (i != 0)
9217 sz += seplen;
9218 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9219 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009220 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009221 goto onError;
9222 }
9223 }
Tim Petersced69f82003-09-16 20:30:58 +00009224
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009225 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009226 if (res == NULL)
9227 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009228
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009229 /* Catenate everything. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009230 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009231 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009232 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009233 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009234 if (i && seplen != 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009235 copy_characters(res, res_offset, sep, 0, seplen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009236 res_offset += seplen;
Benjamin Peterson29060642009-01-31 22:14:21 +00009237 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009238 itemlen = PyUnicode_GET_LENGTH(item);
9239 if (itemlen != 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009240 copy_characters(res, res_offset, item, 0, itemlen);
Victor Stinner9ce5a832011-10-03 23:36:02 +02009241 res_offset += itemlen;
Victor Stinner9ce5a832011-10-03 23:36:02 +02009242 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009243 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009244 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009245
Tim Peters05eba1f2004-08-27 21:32:02 +00009246 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009247 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009248 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009249 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009250
Benjamin Peterson29060642009-01-31 22:14:21 +00009251 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009252 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009253 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009254 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009255 return NULL;
9256}
9257
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009258#define FILL(kind, data, value, start, length) \
9259 do { \
9260 Py_ssize_t i_ = 0; \
9261 assert(kind != PyUnicode_WCHAR_KIND); \
9262 switch ((kind)) { \
9263 case PyUnicode_1BYTE_KIND: { \
9264 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9265 memset(to_, (unsigned char)value, length); \
9266 break; \
9267 } \
9268 case PyUnicode_2BYTE_KIND: { \
9269 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9270 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9271 break; \
9272 } \
9273 default: { \
9274 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9275 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9276 break; \
9277 } \
9278 } \
9279 } while (0)
9280
Victor Stinner9310abb2011-10-05 00:59:23 +02009281static PyObject *
9282pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009283 Py_ssize_t left,
9284 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009285 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009286{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009287 PyObject *u;
9288 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009289 int kind;
9290 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009291
9292 if (left < 0)
9293 left = 0;
9294 if (right < 0)
9295 right = 0;
9296
Tim Peters7a29bd52001-09-12 03:03:31 +00009297 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009298 Py_INCREF(self);
9299 return self;
9300 }
9301
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009302 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9303 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009304 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9305 return NULL;
9306 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009307 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9308 if (fill > maxchar)
9309 maxchar = fill;
9310 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009311 if (!u)
9312 return NULL;
9313
9314 kind = PyUnicode_KIND(u);
9315 data = PyUnicode_DATA(u);
9316 if (left)
9317 FILL(kind, data, fill, 0, left);
9318 if (right)
9319 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009320 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009321 assert(_PyUnicode_CheckConsistency(u, 1));
9322 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009323}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009324#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009325
Alexander Belopolsky40018472011-02-26 01:02:56 +00009326PyObject *
9327PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009328{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009329 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009330
9331 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009332 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009333 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009334
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009335 switch(PyUnicode_KIND(string)) {
9336 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009337 if (PyUnicode_IS_ASCII(string))
9338 list = asciilib_splitlines(
9339 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9340 PyUnicode_GET_LENGTH(string), keepends);
9341 else
9342 list = ucs1lib_splitlines(
9343 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9344 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009345 break;
9346 case PyUnicode_2BYTE_KIND:
9347 list = ucs2lib_splitlines(
9348 (PyObject*) string, PyUnicode_2BYTE_DATA(string),
9349 PyUnicode_GET_LENGTH(string), keepends);
9350 break;
9351 case PyUnicode_4BYTE_KIND:
9352 list = ucs4lib_splitlines(
9353 (PyObject*) string, PyUnicode_4BYTE_DATA(string),
9354 PyUnicode_GET_LENGTH(string), keepends);
9355 break;
9356 default:
9357 assert(0);
9358 list = 0;
9359 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009360 Py_DECREF(string);
9361 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009362}
9363
Alexander Belopolsky40018472011-02-26 01:02:56 +00009364static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009365split(PyObject *self,
9366 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009367 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009368{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009369 int kind1, kind2, kind;
9370 void *buf1, *buf2;
9371 Py_ssize_t len1, len2;
9372 PyObject* out;
9373
Guido van Rossumd57fd912000-03-10 22:53:23 +00009374 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009375 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009376
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009377 if (PyUnicode_READY(self) == -1)
9378 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009379
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009380 if (substring == NULL)
9381 switch(PyUnicode_KIND(self)) {
9382 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009383 if (PyUnicode_IS_ASCII(self))
9384 return asciilib_split_whitespace(
9385 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9386 PyUnicode_GET_LENGTH(self), maxcount
9387 );
9388 else
9389 return ucs1lib_split_whitespace(
9390 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9391 PyUnicode_GET_LENGTH(self), maxcount
9392 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009393 case PyUnicode_2BYTE_KIND:
9394 return ucs2lib_split_whitespace(
9395 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9396 PyUnicode_GET_LENGTH(self), maxcount
9397 );
9398 case PyUnicode_4BYTE_KIND:
9399 return ucs4lib_split_whitespace(
9400 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
9401 PyUnicode_GET_LENGTH(self), maxcount
9402 );
9403 default:
9404 assert(0);
9405 return NULL;
9406 }
9407
9408 if (PyUnicode_READY(substring) == -1)
9409 return NULL;
9410
9411 kind1 = PyUnicode_KIND(self);
9412 kind2 = PyUnicode_KIND(substring);
9413 kind = kind1 > kind2 ? kind1 : kind2;
9414 buf1 = PyUnicode_DATA(self);
9415 buf2 = PyUnicode_DATA(substring);
9416 if (kind1 != kind)
9417 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9418 if (!buf1)
9419 return NULL;
9420 if (kind2 != kind)
9421 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9422 if (!buf2) {
9423 if (kind1 != kind) PyMem_Free(buf1);
9424 return NULL;
9425 }
9426 len1 = PyUnicode_GET_LENGTH(self);
9427 len2 = PyUnicode_GET_LENGTH(substring);
9428
9429 switch(kind) {
9430 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009431 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9432 out = asciilib_split(
9433 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9434 else
9435 out = ucs1lib_split(
9436 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009437 break;
9438 case PyUnicode_2BYTE_KIND:
9439 out = ucs2lib_split(
9440 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9441 break;
9442 case PyUnicode_4BYTE_KIND:
9443 out = ucs4lib_split(
9444 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9445 break;
9446 default:
9447 out = NULL;
9448 }
9449 if (kind1 != kind)
9450 PyMem_Free(buf1);
9451 if (kind2 != kind)
9452 PyMem_Free(buf2);
9453 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009454}
9455
Alexander Belopolsky40018472011-02-26 01:02:56 +00009456static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009457rsplit(PyObject *self,
9458 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009459 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009460{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009461 int kind1, kind2, kind;
9462 void *buf1, *buf2;
9463 Py_ssize_t len1, len2;
9464 PyObject* out;
9465
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009466 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009467 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009468
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009469 if (PyUnicode_READY(self) == -1)
9470 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009471
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009472 if (substring == NULL)
9473 switch(PyUnicode_KIND(self)) {
9474 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009475 if (PyUnicode_IS_ASCII(self))
9476 return asciilib_rsplit_whitespace(
9477 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9478 PyUnicode_GET_LENGTH(self), maxcount
9479 );
9480 else
9481 return ucs1lib_rsplit_whitespace(
9482 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9483 PyUnicode_GET_LENGTH(self), maxcount
9484 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009485 case PyUnicode_2BYTE_KIND:
9486 return ucs2lib_rsplit_whitespace(
9487 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9488 PyUnicode_GET_LENGTH(self), maxcount
9489 );
9490 case PyUnicode_4BYTE_KIND:
9491 return ucs4lib_rsplit_whitespace(
9492 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
9493 PyUnicode_GET_LENGTH(self), maxcount
9494 );
9495 default:
9496 assert(0);
9497 return NULL;
9498 }
9499
9500 if (PyUnicode_READY(substring) == -1)
9501 return NULL;
9502
9503 kind1 = PyUnicode_KIND(self);
9504 kind2 = PyUnicode_KIND(substring);
9505 kind = kind1 > kind2 ? kind1 : kind2;
9506 buf1 = PyUnicode_DATA(self);
9507 buf2 = PyUnicode_DATA(substring);
9508 if (kind1 != kind)
9509 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9510 if (!buf1)
9511 return NULL;
9512 if (kind2 != kind)
9513 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9514 if (!buf2) {
9515 if (kind1 != kind) PyMem_Free(buf1);
9516 return NULL;
9517 }
9518 len1 = PyUnicode_GET_LENGTH(self);
9519 len2 = PyUnicode_GET_LENGTH(substring);
9520
9521 switch(kind) {
9522 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009523 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9524 out = asciilib_rsplit(
9525 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9526 else
9527 out = ucs1lib_rsplit(
9528 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009529 break;
9530 case PyUnicode_2BYTE_KIND:
9531 out = ucs2lib_rsplit(
9532 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9533 break;
9534 case PyUnicode_4BYTE_KIND:
9535 out = ucs4lib_rsplit(
9536 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9537 break;
9538 default:
9539 out = NULL;
9540 }
9541 if (kind1 != kind)
9542 PyMem_Free(buf1);
9543 if (kind2 != kind)
9544 PyMem_Free(buf2);
9545 return out;
9546}
9547
9548static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009549anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9550 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009551{
9552 switch(kind) {
9553 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009554 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
9555 return asciilib_find(buf1, len1, buf2, len2, offset);
9556 else
9557 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009558 case PyUnicode_2BYTE_KIND:
9559 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9560 case PyUnicode_4BYTE_KIND:
9561 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9562 }
9563 assert(0);
9564 return -1;
9565}
9566
9567static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009568anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
9569 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009570{
9571 switch(kind) {
9572 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009573 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
9574 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
9575 else
9576 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009577 case PyUnicode_2BYTE_KIND:
9578 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
9579 case PyUnicode_4BYTE_KIND:
9580 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
9581 }
9582 assert(0);
9583 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009584}
9585
Alexander Belopolsky40018472011-02-26 01:02:56 +00009586static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009587replace(PyObject *self, PyObject *str1,
9588 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009589{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009590 PyObject *u;
9591 char *sbuf = PyUnicode_DATA(self);
9592 char *buf1 = PyUnicode_DATA(str1);
9593 char *buf2 = PyUnicode_DATA(str2);
9594 int srelease = 0, release1 = 0, release2 = 0;
9595 int skind = PyUnicode_KIND(self);
9596 int kind1 = PyUnicode_KIND(str1);
9597 int kind2 = PyUnicode_KIND(str2);
9598 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
9599 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
9600 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009601
9602 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009603 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009604 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009605 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009606
Victor Stinner59de0ee2011-10-07 10:01:28 +02009607 if (str1 == str2)
9608 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009609 if (skind < kind1)
9610 /* substring too wide to be present */
9611 goto nothing;
9612
9613 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +00009614 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009615 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009616 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009617 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009618 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009619 /* replace characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009620 Py_UCS4 u1, u2, maxchar;
9621 int mayshrink, rkind;
9622 u1 = PyUnicode_READ_CHAR(str1, 0);
9623 if (!findchar(sbuf, PyUnicode_KIND(self),
9624 slen, u1, 1))
Thomas Wouters477c8d52006-05-27 19:21:47 +00009625 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009626 u2 = PyUnicode_READ_CHAR(str2, 0);
9627 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9628 /* Replacing u1 with u2 may cause a maxchar reduction in the
9629 result string. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009630 if (u2 > maxchar) {
9631 maxchar = u2;
9632 mayshrink = 0;
9633 }
Victor Stinnerb9275c12011-10-05 14:01:42 +02009634 else
9635 mayshrink = maxchar > 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009636 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009637 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009638 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009639 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009640 rkind = PyUnicode_KIND(u);
9641 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
9642 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009643 if (--maxcount < 0)
9644 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009645 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009646 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009647 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +02009648 unicode_adjust_maxchar(&u);
9649 if (u == NULL)
9650 goto error;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009651 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009652 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009653 int rkind = skind;
9654 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +02009655 PyObject *rstr;
9656 Py_UCS4 maxchar;
9657
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009658 if (kind1 < rkind) {
9659 /* widen substring */
9660 buf1 = _PyUnicode_AsKind(str1, rkind);
9661 if (!buf1) goto error;
9662 release1 = 1;
9663 }
Victor Stinnerc3cec782011-10-05 21:24:08 +02009664 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009665 if (i < 0)
9666 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009667 if (rkind > kind2) {
9668 /* widen replacement */
9669 buf2 = _PyUnicode_AsKind(str2, rkind);
9670 if (!buf2) goto error;
9671 release2 = 1;
9672 }
9673 else if (rkind < kind2) {
9674 /* widen self and buf1 */
9675 rkind = kind2;
9676 if (release1) PyMem_Free(buf1);
9677 sbuf = _PyUnicode_AsKind(self, rkind);
9678 if (!sbuf) goto error;
9679 srelease = 1;
9680 buf1 = _PyUnicode_AsKind(str1, rkind);
9681 if (!buf1) goto error;
9682 release1 = 1;
9683 }
Victor Stinner25a4b292011-10-06 12:31:55 +02009684 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9685 maxchar = Py_MAX(maxchar, PyUnicode_MAX_CHAR_VALUE(str2));
9686 rstr = PyUnicode_New(slen, maxchar);
9687 if (!rstr)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009688 goto error;
Victor Stinner25a4b292011-10-06 12:31:55 +02009689 res = PyUnicode_DATA(rstr);
9690
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009691 memcpy(res, sbuf, PyUnicode_KIND_SIZE(rkind, slen));
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009692 /* change everything in-place, starting with this one */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009693 memcpy(res + PyUnicode_KIND_SIZE(rkind, i),
9694 buf2,
9695 PyUnicode_KIND_SIZE(rkind, len2));
9696 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009697
9698 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +02009699 i = anylib_find(rkind, self,
9700 sbuf+PyUnicode_KIND_SIZE(rkind, i), slen-i,
9701 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009702 if (i == -1)
9703 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009704 memcpy(res + PyUnicode_KIND_SIZE(rkind, i),
9705 buf2,
9706 PyUnicode_KIND_SIZE(rkind, len2));
9707 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009708 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009709
Victor Stinner25a4b292011-10-06 12:31:55 +02009710 u = rstr;
9711 unicode_adjust_maxchar(&u);
9712 if (!u)
9713 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009714 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009715 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009716
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009717 Py_ssize_t n, i, j, ires;
9718 Py_ssize_t product, new_size;
9719 int rkind = skind;
Victor Stinner25a4b292011-10-06 12:31:55 +02009720 PyObject *rstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009721 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +02009722 Py_UCS4 maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009723
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009724 if (kind1 < rkind) {
9725 buf1 = _PyUnicode_AsKind(str1, rkind);
9726 if (!buf1) goto error;
9727 release1 = 1;
9728 }
Victor Stinnerc3cec782011-10-05 21:24:08 +02009729 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009730 if (n == 0)
9731 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009732 if (kind2 < rkind) {
9733 buf2 = _PyUnicode_AsKind(str2, rkind);
9734 if (!buf2) goto error;
9735 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009736 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009737 else if (kind2 > rkind) {
9738 rkind = kind2;
9739 sbuf = _PyUnicode_AsKind(self, rkind);
9740 if (!sbuf) goto error;
9741 srelease = 1;
9742 if (release1) PyMem_Free(buf1);
9743 buf1 = _PyUnicode_AsKind(str1, rkind);
9744 if (!buf1) goto error;
9745 release1 = 1;
9746 }
9747 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
9748 PyUnicode_GET_LENGTH(str1))); */
9749 product = n * (len2-len1);
9750 if ((product / (len2-len1)) != n) {
9751 PyErr_SetString(PyExc_OverflowError,
9752 "replace string is too long");
9753 goto error;
9754 }
9755 new_size = slen + product;
9756 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
9757 PyErr_SetString(PyExc_OverflowError,
9758 "replace string is too long");
9759 goto error;
9760 }
Victor Stinner25a4b292011-10-06 12:31:55 +02009761 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9762 maxchar = Py_MAX(maxchar, PyUnicode_MAX_CHAR_VALUE(str2));
9763 rstr = PyUnicode_New(new_size, maxchar);
9764 if (!rstr)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009765 goto error;
Victor Stinner25a4b292011-10-06 12:31:55 +02009766 res = PyUnicode_DATA(rstr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009767 ires = i = 0;
9768 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009769 while (n-- > 0) {
9770 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +02009771 j = anylib_find(rkind, self,
9772 sbuf + PyUnicode_KIND_SIZE(rkind, i), slen-i,
9773 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009774 if (j == -1)
9775 break;
9776 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009777 /* copy unchanged part [i:j] */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009778 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9779 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9780 PyUnicode_KIND_SIZE(rkind, j-i));
9781 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009782 }
9783 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009784 if (len2 > 0) {
9785 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9786 buf2,
9787 PyUnicode_KIND_SIZE(rkind, len2));
9788 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009789 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009790 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009791 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009792 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +00009793 /* copy tail [i:] */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009794 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9795 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9796 PyUnicode_KIND_SIZE(rkind, slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00009797 } else {
9798 /* interleave */
9799 while (n > 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009800 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9801 buf2,
9802 PyUnicode_KIND_SIZE(rkind, len2));
9803 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009804 if (--n <= 0)
9805 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009806 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9807 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9808 PyUnicode_KIND_SIZE(rkind, 1));
9809 ires++;
9810 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009811 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009812 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9813 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9814 PyUnicode_KIND_SIZE(rkind, slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00009815 }
Victor Stinner25a4b292011-10-06 12:31:55 +02009816 u = rstr;
9817 unicode_adjust_maxchar(&u);
9818 if (u == NULL)
9819 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009820 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009821 if (srelease)
9822 PyMem_FREE(sbuf);
9823 if (release1)
9824 PyMem_FREE(buf1);
9825 if (release2)
9826 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009827 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009828 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009829
Benjamin Peterson29060642009-01-31 22:14:21 +00009830 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00009831 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009832 if (srelease)
9833 PyMem_FREE(sbuf);
9834 if (release1)
9835 PyMem_FREE(buf1);
9836 if (release2)
9837 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009838 if (PyUnicode_CheckExact(self)) {
9839 Py_INCREF(self);
9840 return (PyObject *) self;
9841 }
Victor Stinner034f6cf2011-09-30 02:26:44 +02009842 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009843 error:
9844 if (srelease && sbuf)
9845 PyMem_FREE(sbuf);
9846 if (release1 && buf1)
9847 PyMem_FREE(buf1);
9848 if (release2 && buf2)
9849 PyMem_FREE(buf2);
9850 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009851}
9852
9853/* --- Unicode Object Methods --------------------------------------------- */
9854
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009855PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009856 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009857\n\
9858Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009859characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009860
9861static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +02009862unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009863{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009864 return fixup(self, fixtitle);
9865}
9866
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009867PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009868 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009869\n\
9870Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +00009871have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009872
9873static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +02009874unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009875{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009876 return fixup(self, fixcapitalize);
9877}
9878
9879#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009880PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009881 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009882\n\
9883Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009884normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009885
9886static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009887unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009888{
9889 PyObject *list;
9890 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009891 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009892
Guido van Rossumd57fd912000-03-10 22:53:23 +00009893 /* Split into words */
9894 list = split(self, NULL, -1);
9895 if (!list)
9896 return NULL;
9897
9898 /* Capitalize each word */
9899 for (i = 0; i < PyList_GET_SIZE(list); i++) {
9900 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00009901 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009902 if (item == NULL)
9903 goto onError;
9904 Py_DECREF(PyList_GET_ITEM(list, i));
9905 PyList_SET_ITEM(list, i, item);
9906 }
9907
9908 /* Join the words to form a new string */
9909 item = PyUnicode_Join(NULL, list);
9910
Benjamin Peterson29060642009-01-31 22:14:21 +00009911 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009912 Py_DECREF(list);
9913 return (PyObject *)item;
9914}
9915#endif
9916
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009917/* Argument converter. Coerces to a single unicode character */
9918
9919static int
9920convert_uc(PyObject *obj, void *addr)
9921{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009922 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009923 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009924
Benjamin Peterson14339b62009-01-31 16:36:08 +00009925 uniobj = PyUnicode_FromObject(obj);
9926 if (uniobj == NULL) {
9927 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009928 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009929 return 0;
9930 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009931 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009932 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009933 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009934 Py_DECREF(uniobj);
9935 return 0;
9936 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009937 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009938 Py_DECREF(uniobj);
9939 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009940}
9941
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009942PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009943 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009944\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00009945Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009946done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009947
9948static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009949unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009950{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009951 Py_ssize_t marg, left;
9952 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009953 Py_UCS4 fillchar = ' ';
9954
Victor Stinnere9a29352011-10-01 02:14:59 +02009955 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009956 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009957
Victor Stinnere9a29352011-10-01 02:14:59 +02009958 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009959 return NULL;
9960
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009961 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009962 Py_INCREF(self);
9963 return (PyObject*) self;
9964 }
9965
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009966 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009967 left = marg / 2 + (marg & width & 1);
9968
Victor Stinner9310abb2011-10-05 00:59:23 +02009969 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009970}
9971
Marc-André Lemburge5034372000-08-08 08:04:29 +00009972#if 0
9973
9974/* This code should go into some future Unicode collation support
9975 module. The basic comparison should compare ordinals on a naive
Georg Brandlc6c31782009-06-08 13:41:29 +00009976 basis (this is what Java does and thus Jython too). */
Marc-André Lemburge5034372000-08-08 08:04:29 +00009977
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009978/* speedy UTF-16 code point order comparison */
9979/* gleaned from: */
9980/* http://www-4.ibm.com/software/developer/library/utf16.html?dwzone=unicode */
9981
Marc-André Lemburge12896e2000-07-07 17:51:08 +00009982static short utf16Fixup[32] =
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009983{
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009984 0, 0, 0, 0, 0, 0, 0, 0,
Tim Petersced69f82003-09-16 20:30:58 +00009985 0, 0, 0, 0, 0, 0, 0, 0,
9986 0, 0, 0, 0, 0, 0, 0, 0,
Marc-André Lemburge12896e2000-07-07 17:51:08 +00009987 0, 0, 0, 0x2000, -0x800, -0x800, -0x800, -0x800
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009988};
9989
Guido van Rossumd57fd912000-03-10 22:53:23 +00009990static int
9991unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
9992{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009993 Py_ssize_t len1, len2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009994
Guido van Rossumd57fd912000-03-10 22:53:23 +00009995 Py_UNICODE *s1 = str1->str;
9996 Py_UNICODE *s2 = str2->str;
9997
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009998 len1 = str1->_base._base.length;
9999 len2 = str2->_base._base.length;
Tim Petersced69f82003-09-16 20:30:58 +000010000
Guido van Rossumd57fd912000-03-10 22:53:23 +000010001 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +000010002 Py_UNICODE c1, c2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010003
10004 c1 = *s1++;
10005 c2 = *s2++;
Fredrik Lundh45714e92001-06-26 16:39:36 +000010006
Benjamin Peterson29060642009-01-31 22:14:21 +000010007 if (c1 > (1<<11) * 26)
10008 c1 += utf16Fixup[c1>>11];
10009 if (c2 > (1<<11) * 26)
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010010 c2 += utf16Fixup[c2>>11];
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010011 /* now c1 and c2 are in UTF-32-compatible order */
Fredrik Lundh45714e92001-06-26 16:39:36 +000010012
10013 if (c1 != c2)
10014 return (c1 < c2) ? -1 : 1;
Tim Petersced69f82003-09-16 20:30:58 +000010015
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010016 len1--; len2--;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010017 }
10018
10019 return (len1 < len2) ? -1 : (len1 != len2);
10020}
10021
Marc-André Lemburge5034372000-08-08 08:04:29 +000010022#else
10023
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010024/* This function assumes that str1 and str2 are readied by the caller. */
10025
Marc-André Lemburge5034372000-08-08 08:04:29 +000010026static int
10027unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
10028{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010029 int kind1, kind2;
10030 void *data1, *data2;
10031 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010032
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010033 kind1 = PyUnicode_KIND(str1);
10034 kind2 = PyUnicode_KIND(str2);
10035 data1 = PyUnicode_DATA(str1);
10036 data2 = PyUnicode_DATA(str2);
10037 len1 = PyUnicode_GET_LENGTH(str1);
10038 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010039
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010040 for (i = 0; i < len1 && i < len2; ++i) {
10041 Py_UCS4 c1, c2;
10042 c1 = PyUnicode_READ(kind1, data1, i);
10043 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010044
10045 if (c1 != c2)
10046 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010047 }
10048
10049 return (len1 < len2) ? -1 : (len1 != len2);
10050}
10051
10052#endif
10053
Alexander Belopolsky40018472011-02-26 01:02:56 +000010054int
10055PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010056{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010057 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10058 if (PyUnicode_READY(left) == -1 ||
10059 PyUnicode_READY(right) == -1)
10060 return -1;
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010061 return unicode_compare((PyUnicodeObject *)left,
10062 (PyUnicodeObject *)right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010063 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010064 PyErr_Format(PyExc_TypeError,
10065 "Can't compare %.100s and %.100s",
10066 left->ob_type->tp_name,
10067 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010068 return -1;
10069}
10070
Martin v. Löwis5b222132007-06-10 09:51:05 +000010071int
10072PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10073{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010074 Py_ssize_t i;
10075 int kind;
10076 void *data;
10077 Py_UCS4 chr;
10078
Victor Stinner910337b2011-10-03 03:20:16 +020010079 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010080 if (PyUnicode_READY(uni) == -1)
10081 return -1;
10082 kind = PyUnicode_KIND(uni);
10083 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010084 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010085 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10086 if (chr != str[i])
10087 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010088 /* This check keeps Python strings that end in '\0' from comparing equal
10089 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010090 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010091 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010092 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010093 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010094 return 0;
10095}
10096
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010097
Benjamin Peterson29060642009-01-31 22:14:21 +000010098#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010099 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010100
Alexander Belopolsky40018472011-02-26 01:02:56 +000010101PyObject *
10102PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010103{
10104 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010105
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010106 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10107 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010108 if (PyUnicode_READY(left) == -1 ||
10109 PyUnicode_READY(right) == -1)
10110 return NULL;
10111 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10112 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010113 if (op == Py_EQ) {
10114 Py_INCREF(Py_False);
10115 return Py_False;
10116 }
10117 if (op == Py_NE) {
10118 Py_INCREF(Py_True);
10119 return Py_True;
10120 }
10121 }
10122 if (left == right)
10123 result = 0;
10124 else
10125 result = unicode_compare((PyUnicodeObject *)left,
10126 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010127
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010128 /* Convert the return value to a Boolean */
10129 switch (op) {
10130 case Py_EQ:
10131 v = TEST_COND(result == 0);
10132 break;
10133 case Py_NE:
10134 v = TEST_COND(result != 0);
10135 break;
10136 case Py_LE:
10137 v = TEST_COND(result <= 0);
10138 break;
10139 case Py_GE:
10140 v = TEST_COND(result >= 0);
10141 break;
10142 case Py_LT:
10143 v = TEST_COND(result == -1);
10144 break;
10145 case Py_GT:
10146 v = TEST_COND(result == 1);
10147 break;
10148 default:
10149 PyErr_BadArgument();
10150 return NULL;
10151 }
10152 Py_INCREF(v);
10153 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010154 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010155
Brian Curtindfc80e32011-08-10 20:28:54 -050010156 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010157}
10158
Alexander Belopolsky40018472011-02-26 01:02:56 +000010159int
10160PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010161{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010162 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163 int kind1, kind2, kind;
10164 void *buf1, *buf2;
10165 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010166 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010167
10168 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010169 sub = PyUnicode_FromObject(element);
10170 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010171 PyErr_Format(PyExc_TypeError,
10172 "'in <string>' requires string as left operand, not %s",
10173 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010174 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010175 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010176 if (PyUnicode_READY(sub) == -1)
10177 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010178
Thomas Wouters477c8d52006-05-27 19:21:47 +000010179 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010180 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010181 Py_DECREF(sub);
10182 return -1;
10183 }
10184
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010185 kind1 = PyUnicode_KIND(str);
10186 kind2 = PyUnicode_KIND(sub);
10187 kind = kind1 > kind2 ? kind1 : kind2;
10188 buf1 = PyUnicode_DATA(str);
10189 buf2 = PyUnicode_DATA(sub);
10190 if (kind1 != kind)
10191 buf1 = _PyUnicode_AsKind((PyObject*)str, kind);
10192 if (!buf1) {
10193 Py_DECREF(sub);
10194 return -1;
10195 }
10196 if (kind2 != kind)
10197 buf2 = _PyUnicode_AsKind((PyObject*)sub, kind);
10198 if (!buf2) {
10199 Py_DECREF(sub);
10200 if (kind1 != kind) PyMem_Free(buf1);
10201 return -1;
10202 }
10203 len1 = PyUnicode_GET_LENGTH(str);
10204 len2 = PyUnicode_GET_LENGTH(sub);
10205
10206 switch(kind) {
10207 case PyUnicode_1BYTE_KIND:
10208 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10209 break;
10210 case PyUnicode_2BYTE_KIND:
10211 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10212 break;
10213 case PyUnicode_4BYTE_KIND:
10214 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10215 break;
10216 default:
10217 result = -1;
10218 assert(0);
10219 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010220
10221 Py_DECREF(str);
10222 Py_DECREF(sub);
10223
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010224 if (kind1 != kind)
10225 PyMem_Free(buf1);
10226 if (kind2 != kind)
10227 PyMem_Free(buf2);
10228
Guido van Rossum403d68b2000-03-13 15:55:09 +000010229 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010230}
10231
Guido van Rossumd57fd912000-03-10 22:53:23 +000010232/* Concat to string or Unicode object giving a new Unicode object. */
10233
Alexander Belopolsky40018472011-02-26 01:02:56 +000010234PyObject *
10235PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010236{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010237 PyObject *u = NULL, *v = NULL, *w;
10238 Py_UCS4 maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010239
10240 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010241 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010242 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010243 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010244 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010245 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010246 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010247
10248 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010249 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010250 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010251 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010252 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010253 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010254 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010255 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010256 }
10257
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010258 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinnerff9e50f2011-09-28 22:17:19 +020010259 maxchar = Py_MAX(maxchar, PyUnicode_MAX_CHAR_VALUE(v));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010260
Guido van Rossumd57fd912000-03-10 22:53:23 +000010261 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010262 w = PyUnicode_New(
10263 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10264 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010265 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010266 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010267 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10268 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010269 Py_DECREF(u);
10270 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010271 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010272 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010273
Benjamin Peterson29060642009-01-31 22:14:21 +000010274 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010275 Py_XDECREF(u);
10276 Py_XDECREF(v);
10277 return NULL;
10278}
10279
Victor Stinnerb0923652011-10-04 01:17:31 +020010280static void
10281unicode_append_inplace(PyObject **p_left, PyObject *right)
10282{
10283 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010284
10285 assert(PyUnicode_IS_READY(*p_left));
10286 assert(PyUnicode_IS_READY(right));
10287
10288 left_len = PyUnicode_GET_LENGTH(*p_left);
10289 right_len = PyUnicode_GET_LENGTH(right);
10290 if (left_len > PY_SSIZE_T_MAX - right_len) {
10291 PyErr_SetString(PyExc_OverflowError,
10292 "strings are too large to concat");
10293 goto error;
10294 }
10295 new_len = left_len + right_len;
10296
10297 /* Now we own the last reference to 'left', so we can resize it
10298 * in-place.
10299 */
10300 if (unicode_resize(p_left, new_len) != 0) {
10301 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10302 * deallocated so it cannot be put back into
10303 * 'variable'. The MemoryError is raised when there
10304 * is no value in 'variable', which might (very
10305 * remotely) be a cause of incompatibilities.
10306 */
10307 goto error;
10308 }
10309 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010310 copy_characters(*p_left, left_len, right, 0, right_len);
10311 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010312 return;
10313
10314error:
10315 Py_DECREF(*p_left);
10316 *p_left = NULL;
10317}
10318
Walter Dörwald1ab83302007-05-18 17:15:44 +000010319void
Victor Stinner23e56682011-10-03 03:54:37 +020010320PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010321{
Victor Stinner23e56682011-10-03 03:54:37 +020010322 PyObject *left, *res;
10323
10324 if (p_left == NULL) {
10325 if (!PyErr_Occurred())
10326 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010327 return;
10328 }
Victor Stinner23e56682011-10-03 03:54:37 +020010329 left = *p_left;
10330 if (right == NULL || !PyUnicode_Check(left)) {
10331 if (!PyErr_Occurred())
10332 PyErr_BadInternalCall();
10333 goto error;
10334 }
10335
Victor Stinnere1335c72011-10-04 20:53:03 +020010336 if (PyUnicode_READY(left))
10337 goto error;
10338 if (PyUnicode_READY(right))
10339 goto error;
10340
Victor Stinner23e56682011-10-03 03:54:37 +020010341 if (PyUnicode_CheckExact(left) && left != unicode_empty
10342 && PyUnicode_CheckExact(right) && right != unicode_empty
10343 && unicode_resizable(left)
10344 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10345 || _PyUnicode_WSTR(left) != NULL))
10346 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010347 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10348 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010349 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010350 not so different than duplicating the string. */
10351 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010352 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010353 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010354 if (p_left != NULL)
10355 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010356 return;
10357 }
10358 }
10359
10360 res = PyUnicode_Concat(left, right);
10361 if (res == NULL)
10362 goto error;
10363 Py_DECREF(left);
10364 *p_left = res;
10365 return;
10366
10367error:
10368 Py_DECREF(*p_left);
10369 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010370}
10371
10372void
10373PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10374{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010375 PyUnicode_Append(pleft, right);
10376 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010377}
10378
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010379PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010380 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010381\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010382Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010383string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010384interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010385
10386static PyObject *
10387unicode_count(PyUnicodeObject *self, PyObject *args)
10388{
10389 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010390 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010391 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010392 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010393 int kind1, kind2, kind;
10394 void *buf1, *buf2;
10395 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010396
Jesus Ceaac451502011-04-20 17:09:23 +020010397 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10398 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010399 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010400
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010401 kind1 = PyUnicode_KIND(self);
10402 kind2 = PyUnicode_KIND(substring);
10403 kind = kind1 > kind2 ? kind1 : kind2;
10404 buf1 = PyUnicode_DATA(self);
10405 buf2 = PyUnicode_DATA(substring);
10406 if (kind1 != kind)
10407 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10408 if (!buf1) {
10409 Py_DECREF(substring);
10410 return NULL;
10411 }
10412 if (kind2 != kind)
10413 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10414 if (!buf2) {
10415 Py_DECREF(substring);
10416 if (kind1 != kind) PyMem_Free(buf1);
10417 return NULL;
10418 }
10419 len1 = PyUnicode_GET_LENGTH(self);
10420 len2 = PyUnicode_GET_LENGTH(substring);
10421
10422 ADJUST_INDICES(start, end, len1);
10423 switch(kind) {
10424 case PyUnicode_1BYTE_KIND:
10425 iresult = ucs1lib_count(
10426 ((Py_UCS1*)buf1) + start, end - start,
10427 buf2, len2, PY_SSIZE_T_MAX
10428 );
10429 break;
10430 case PyUnicode_2BYTE_KIND:
10431 iresult = ucs2lib_count(
10432 ((Py_UCS2*)buf1) + start, end - start,
10433 buf2, len2, PY_SSIZE_T_MAX
10434 );
10435 break;
10436 case PyUnicode_4BYTE_KIND:
10437 iresult = ucs4lib_count(
10438 ((Py_UCS4*)buf1) + start, end - start,
10439 buf2, len2, PY_SSIZE_T_MAX
10440 );
10441 break;
10442 default:
10443 assert(0); iresult = 0;
10444 }
10445
10446 result = PyLong_FromSsize_t(iresult);
10447
10448 if (kind1 != kind)
10449 PyMem_Free(buf1);
10450 if (kind2 != kind)
10451 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010452
10453 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010454
Guido van Rossumd57fd912000-03-10 22:53:23 +000010455 return result;
10456}
10457
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010458PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010459 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010460\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010461Encode S using the codec registered for encoding. Default encoding\n\
10462is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010463handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010464a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10465'xmlcharrefreplace' as well as any other name registered with\n\
10466codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010467
10468static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +000010469unicode_encode(PyUnicodeObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010470{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010471 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010472 char *encoding = NULL;
10473 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010474
Benjamin Peterson308d6372009-09-18 21:42:35 +000010475 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10476 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010477 return NULL;
Georg Brandl3b9406b2010-12-03 07:54:09 +000010478 return PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010479}
10480
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010481PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010482 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010483\n\
10484Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010485If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010486
10487static PyObject*
10488unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
10489{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010490 Py_ssize_t i, j, line_pos, src_len, incr;
10491 Py_UCS4 ch;
10492 PyObject *u;
10493 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010494 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010495 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010496 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010497
10498 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010499 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010500
Antoine Pitrou22425222011-10-04 19:10:51 +020010501 if (PyUnicode_READY(self) == -1)
10502 return NULL;
10503
Thomas Wouters7e474022000-07-16 12:04:32 +000010504 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010505 src_len = PyUnicode_GET_LENGTH(self);
10506 i = j = line_pos = 0;
10507 kind = PyUnicode_KIND(self);
10508 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010509 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010510 for (; i < src_len; i++) {
10511 ch = PyUnicode_READ(kind, src_data, i);
10512 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010513 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010514 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010515 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010516 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010517 goto overflow;
10518 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010519 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010520 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010521 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010522 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010523 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010524 goto overflow;
10525 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010526 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010527 if (ch == '\n' || ch == '\r')
10528 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010529 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010530 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020010531 if (!found && PyUnicode_CheckExact(self)) {
10532 Py_INCREF((PyObject *) self);
10533 return (PyObject *) self;
10534 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010535
Guido van Rossumd57fd912000-03-10 22:53:23 +000010536 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010537 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010538 if (!u)
10539 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010540 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010541
Antoine Pitroue71d5742011-10-04 15:55:09 +020010542 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010543
Antoine Pitroue71d5742011-10-04 15:55:09 +020010544 for (; i < src_len; i++) {
10545 ch = PyUnicode_READ(kind, src_data, i);
10546 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010547 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010548 incr = tabsize - (line_pos % tabsize);
10549 line_pos += incr;
10550 while (incr--) {
10551 PyUnicode_WRITE(kind, dest_data, j, ' ');
10552 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010553 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010554 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010555 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010556 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010557 line_pos++;
10558 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010559 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010560 if (ch == '\n' || ch == '\r')
10561 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010562 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010563 }
10564 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020010565#ifndef DONT_MAKE_RESULT_READY
10566 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010567 Py_DECREF(u);
10568 return NULL;
10569 }
Victor Stinner17efeed2011-10-04 20:05:46 +020010570#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010571 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010572 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010573
Antoine Pitroue71d5742011-10-04 15:55:09 +020010574 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010575 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10576 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010577}
10578
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010579PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010580 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010581\n\
10582Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010583such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010584arguments start and end are interpreted as in slice notation.\n\
10585\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010586Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010587
10588static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010589unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010590{
Jesus Ceaac451502011-04-20 17:09:23 +020010591 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010592 Py_ssize_t start;
10593 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010594 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010595
Jesus Ceaac451502011-04-20 17:09:23 +020010596 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10597 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010598 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010599
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010600 if (PyUnicode_READY(self) == -1)
10601 return NULL;
10602 if (PyUnicode_READY(substring) == -1)
10603 return NULL;
10604
10605 result = any_find_slice(
Victor Stinnerc3cec782011-10-05 21:24:08 +020010606 asciilib_find_slice, ucs1lib_find_slice,
10607 ucs2lib_find_slice, ucs4lib_find_slice,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010608 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010609 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010610
10611 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010612
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010613 if (result == -2)
10614 return NULL;
10615
Christian Heimes217cfd12007-12-02 14:31:20 +000010616 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010617}
10618
10619static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010620unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010621{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010622 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
10623 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010624 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010625 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010626}
10627
Guido van Rossumc2504932007-09-18 19:42:40 +000010628/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010010629 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000010630static Py_hash_t
Neil Schemenauerf8c37d12007-09-07 20:49:04 +000010631unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010632{
Guido van Rossumc2504932007-09-18 19:42:40 +000010633 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010010634 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010635
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010636 if (_PyUnicode_HASH(self) != -1)
10637 return _PyUnicode_HASH(self);
10638 if (PyUnicode_READY(self) == -1)
10639 return -1;
10640 len = PyUnicode_GET_LENGTH(self);
10641
10642 /* The hash function as a macro, gets expanded three times below. */
10643#define HASH(P) \
10644 x = (Py_uhash_t)*P << 7; \
10645 while (--len >= 0) \
10646 x = (1000003*x) ^ (Py_uhash_t)*P++;
10647
10648 switch (PyUnicode_KIND(self)) {
10649 case PyUnicode_1BYTE_KIND: {
10650 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
10651 HASH(c);
10652 break;
10653 }
10654 case PyUnicode_2BYTE_KIND: {
10655 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
10656 HASH(s);
10657 break;
10658 }
10659 default: {
10660 Py_UCS4 *l;
10661 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
10662 "Impossible switch case in unicode_hash");
10663 l = PyUnicode_4BYTE_DATA(self);
10664 HASH(l);
10665 break;
10666 }
10667 }
10668 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
10669
Guido van Rossumc2504932007-09-18 19:42:40 +000010670 if (x == -1)
10671 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010672 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010673 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010674}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010675#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000010676
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010677PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010678 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010679\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010680Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010681
10682static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010683unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010684{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010685 Py_ssize_t result;
Jesus Ceaac451502011-04-20 17:09:23 +020010686 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010687 Py_ssize_t start;
10688 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010689
Jesus Ceaac451502011-04-20 17:09:23 +020010690 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
10691 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010692 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010693
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010694 if (PyUnicode_READY(self) == -1)
10695 return NULL;
10696 if (PyUnicode_READY(substring) == -1)
10697 return NULL;
10698
10699 result = any_find_slice(
Victor Stinnerc3cec782011-10-05 21:24:08 +020010700 asciilib_find_slice, ucs1lib_find_slice,
10701 ucs2lib_find_slice, ucs4lib_find_slice,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010702 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010703 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010704
10705 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010706
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010707 if (result == -2)
10708 return NULL;
10709
Guido van Rossumd57fd912000-03-10 22:53:23 +000010710 if (result < 0) {
10711 PyErr_SetString(PyExc_ValueError, "substring not found");
10712 return NULL;
10713 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010714
Christian Heimes217cfd12007-12-02 14:31:20 +000010715 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010716}
10717
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010718PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010719 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010720\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010721Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010722at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010723
10724static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010725unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010726{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010727 Py_ssize_t i, length;
10728 int kind;
10729 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010730 int cased;
10731
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010732 if (PyUnicode_READY(self) == -1)
10733 return NULL;
10734 length = PyUnicode_GET_LENGTH(self);
10735 kind = PyUnicode_KIND(self);
10736 data = PyUnicode_DATA(self);
10737
Guido van Rossumd57fd912000-03-10 22:53:23 +000010738 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010739 if (length == 1)
10740 return PyBool_FromLong(
10741 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010742
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010743 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010744 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010745 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010746
Guido van Rossumd57fd912000-03-10 22:53:23 +000010747 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010748 for (i = 0; i < length; i++) {
10749 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010750
Benjamin Peterson29060642009-01-31 22:14:21 +000010751 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
10752 return PyBool_FromLong(0);
10753 else if (!cased && Py_UNICODE_ISLOWER(ch))
10754 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010755 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010756 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010757}
10758
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010759PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010760 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010761\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010762Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010763at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010764
10765static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010766unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010767{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010768 Py_ssize_t i, length;
10769 int kind;
10770 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010771 int cased;
10772
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010773 if (PyUnicode_READY(self) == -1)
10774 return NULL;
10775 length = PyUnicode_GET_LENGTH(self);
10776 kind = PyUnicode_KIND(self);
10777 data = PyUnicode_DATA(self);
10778
Guido van Rossumd57fd912000-03-10 22:53:23 +000010779 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010780 if (length == 1)
10781 return PyBool_FromLong(
10782 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010783
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010784 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010785 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010786 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010787
Guido van Rossumd57fd912000-03-10 22:53:23 +000010788 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010789 for (i = 0; i < length; i++) {
10790 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010791
Benjamin Peterson29060642009-01-31 22:14:21 +000010792 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
10793 return PyBool_FromLong(0);
10794 else if (!cased && Py_UNICODE_ISUPPER(ch))
10795 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010796 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010797 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010798}
10799
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010800PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010801 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010802\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010803Return True if S is a titlecased string and there is at least one\n\
10804character in S, i.e. upper- and titlecase characters may only\n\
10805follow uncased characters and lowercase characters only cased ones.\n\
10806Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010807
10808static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010809unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010810{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010811 Py_ssize_t i, length;
10812 int kind;
10813 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010814 int cased, previous_is_cased;
10815
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010816 if (PyUnicode_READY(self) == -1)
10817 return NULL;
10818 length = PyUnicode_GET_LENGTH(self);
10819 kind = PyUnicode_KIND(self);
10820 data = PyUnicode_DATA(self);
10821
Guido van Rossumd57fd912000-03-10 22:53:23 +000010822 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010823 if (length == 1) {
10824 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10825 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
10826 (Py_UNICODE_ISUPPER(ch) != 0));
10827 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010828
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010829 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010830 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010831 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010832
Guido van Rossumd57fd912000-03-10 22:53:23 +000010833 cased = 0;
10834 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010835 for (i = 0; i < length; i++) {
10836 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010837
Benjamin Peterson29060642009-01-31 22:14:21 +000010838 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
10839 if (previous_is_cased)
10840 return PyBool_FromLong(0);
10841 previous_is_cased = 1;
10842 cased = 1;
10843 }
10844 else if (Py_UNICODE_ISLOWER(ch)) {
10845 if (!previous_is_cased)
10846 return PyBool_FromLong(0);
10847 previous_is_cased = 1;
10848 cased = 1;
10849 }
10850 else
10851 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010852 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010853 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010854}
10855
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010856PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010857 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010858\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010859Return True if all characters in S are whitespace\n\
10860and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010861
10862static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010863unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010864{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010865 Py_ssize_t i, length;
10866 int kind;
10867 void *data;
10868
10869 if (PyUnicode_READY(self) == -1)
10870 return NULL;
10871 length = PyUnicode_GET_LENGTH(self);
10872 kind = PyUnicode_KIND(self);
10873 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010874
Guido van Rossumd57fd912000-03-10 22:53:23 +000010875 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010876 if (length == 1)
10877 return PyBool_FromLong(
10878 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010879
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010880 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010881 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010882 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010883
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010884 for (i = 0; i < length; i++) {
10885 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010886 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000010887 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010888 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010889 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010890}
10891
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010892PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010893 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010894\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010895Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010896and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010897
10898static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010899unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010900{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010901 Py_ssize_t i, length;
10902 int kind;
10903 void *data;
10904
10905 if (PyUnicode_READY(self) == -1)
10906 return NULL;
10907 length = PyUnicode_GET_LENGTH(self);
10908 kind = PyUnicode_KIND(self);
10909 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010910
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010911 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010912 if (length == 1)
10913 return PyBool_FromLong(
10914 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010915
10916 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010917 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010918 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010919
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010920 for (i = 0; i < length; i++) {
10921 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010922 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010923 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010924 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010925}
10926
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010927PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010928 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010929\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010930Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010931and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010932
10933static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010934unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010935{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010936 int kind;
10937 void *data;
10938 Py_ssize_t len, i;
10939
10940 if (PyUnicode_READY(self) == -1)
10941 return NULL;
10942
10943 kind = PyUnicode_KIND(self);
10944 data = PyUnicode_DATA(self);
10945 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010946
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010947 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010948 if (len == 1) {
10949 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10950 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
10951 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010952
10953 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010954 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010955 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010956
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010957 for (i = 0; i < len; i++) {
10958 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010959 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000010960 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010961 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010962 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010963}
10964
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010965PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010966 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010967\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010968Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010969False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010970
10971static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010972unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010973{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010974 Py_ssize_t i, length;
10975 int kind;
10976 void *data;
10977
10978 if (PyUnicode_READY(self) == -1)
10979 return NULL;
10980 length = PyUnicode_GET_LENGTH(self);
10981 kind = PyUnicode_KIND(self);
10982 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010983
Guido van Rossumd57fd912000-03-10 22:53:23 +000010984 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010985 if (length == 1)
10986 return PyBool_FromLong(
10987 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010988
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010989 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010990 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010991 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010992
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010993 for (i = 0; i < length; i++) {
10994 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010995 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010996 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010997 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010998}
10999
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011000PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011001 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011002\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011003Return True if all characters in S are digits\n\
11004and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011005
11006static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011007unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011008{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011009 Py_ssize_t i, length;
11010 int kind;
11011 void *data;
11012
11013 if (PyUnicode_READY(self) == -1)
11014 return NULL;
11015 length = PyUnicode_GET_LENGTH(self);
11016 kind = PyUnicode_KIND(self);
11017 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011018
Guido van Rossumd57fd912000-03-10 22:53:23 +000011019 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011020 if (length == 1) {
11021 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11022 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11023 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011024
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011025 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011026 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011027 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011028
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011029 for (i = 0; i < length; i++) {
11030 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011031 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011032 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011033 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011034}
11035
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011036PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011037 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011038\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011039Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011040False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011041
11042static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011043unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011044{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011045 Py_ssize_t i, length;
11046 int kind;
11047 void *data;
11048
11049 if (PyUnicode_READY(self) == -1)
11050 return NULL;
11051 length = PyUnicode_GET_LENGTH(self);
11052 kind = PyUnicode_KIND(self);
11053 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011054
Guido van Rossumd57fd912000-03-10 22:53:23 +000011055 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011056 if (length == 1)
11057 return PyBool_FromLong(
11058 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011059
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011060 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011061 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011062 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011063
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011064 for (i = 0; i < length; i++) {
11065 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011066 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011067 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011068 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011069}
11070
Martin v. Löwis47383402007-08-15 07:32:56 +000011071int
11072PyUnicode_IsIdentifier(PyObject *self)
11073{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011074 int kind;
11075 void *data;
11076 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011077 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011078
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011079 if (PyUnicode_READY(self) == -1) {
11080 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011081 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011082 }
11083
11084 /* Special case for empty strings */
11085 if (PyUnicode_GET_LENGTH(self) == 0)
11086 return 0;
11087 kind = PyUnicode_KIND(self);
11088 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011089
11090 /* PEP 3131 says that the first character must be in
11091 XID_Start and subsequent characters in XID_Continue,
11092 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011093 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011094 letters, digits, underscore). However, given the current
11095 definition of XID_Start and XID_Continue, it is sufficient
11096 to check just for these, except that _ must be allowed
11097 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011098 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011099 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011100 return 0;
11101
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011102 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011103 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011104 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011105 return 1;
11106}
11107
11108PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011109 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011110\n\
11111Return True if S is a valid identifier according\n\
11112to the language definition.");
11113
11114static PyObject*
11115unicode_isidentifier(PyObject *self)
11116{
11117 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11118}
11119
Georg Brandl559e5d72008-06-11 18:37:52 +000011120PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011121 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011122\n\
11123Return True if all characters in S are considered\n\
11124printable in repr() or S is empty, False otherwise.");
11125
11126static PyObject*
11127unicode_isprintable(PyObject *self)
11128{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011129 Py_ssize_t i, length;
11130 int kind;
11131 void *data;
11132
11133 if (PyUnicode_READY(self) == -1)
11134 return NULL;
11135 length = PyUnicode_GET_LENGTH(self);
11136 kind = PyUnicode_KIND(self);
11137 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011138
11139 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011140 if (length == 1)
11141 return PyBool_FromLong(
11142 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011143
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011144 for (i = 0; i < length; i++) {
11145 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011146 Py_RETURN_FALSE;
11147 }
11148 }
11149 Py_RETURN_TRUE;
11150}
11151
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011152PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011153 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011154\n\
11155Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011156iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011157
11158static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011159unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011160{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011161 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011162}
11163
Martin v. Löwis18e16552006-02-15 17:27:45 +000011164static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +000011165unicode_length(PyUnicodeObject *self)
11166{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011167 if (PyUnicode_READY(self) == -1)
11168 return -1;
11169 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011170}
11171
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011172PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011173 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011174\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011175Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011176done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011177
11178static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011179unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011180{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011181 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011182 Py_UCS4 fillchar = ' ';
11183
11184 if (PyUnicode_READY(self) == -1)
11185 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011186
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011187 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011188 return NULL;
11189
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011190 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011191 Py_INCREF(self);
11192 return (PyObject*) self;
11193 }
11194
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011195 return (PyObject*) pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011196}
11197
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011198PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011199 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011200\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011201Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011202
11203static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011204unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011205{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011206 return fixup(self, fixlower);
11207}
11208
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011209#define LEFTSTRIP 0
11210#define RIGHTSTRIP 1
11211#define BOTHSTRIP 2
11212
11213/* Arrays indexed by above */
11214static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11215
11216#define STRIPNAME(i) (stripformat[i]+3)
11217
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011218/* externally visible for str.strip(unicode) */
11219PyObject *
11220_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
11221{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011222 void *data;
11223 int kind;
11224 Py_ssize_t i, j, len;
11225 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011226
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011227 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11228 return NULL;
11229
11230 kind = PyUnicode_KIND(self);
11231 data = PyUnicode_DATA(self);
11232 len = PyUnicode_GET_LENGTH(self);
11233 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11234 PyUnicode_DATA(sepobj),
11235 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011236
Benjamin Peterson14339b62009-01-31 16:36:08 +000011237 i = 0;
11238 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011239 while (i < len &&
11240 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011241 i++;
11242 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011243 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011244
Benjamin Peterson14339b62009-01-31 16:36:08 +000011245 j = len;
11246 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011247 do {
11248 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011249 } while (j >= i &&
11250 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011251 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011252 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011253
Victor Stinner12bab6d2011-10-01 01:53:49 +020011254 return PyUnicode_Substring((PyObject*)self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011255}
11256
11257PyObject*
11258PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11259{
11260 unsigned char *data;
11261 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011262 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011263
Victor Stinnerde636f32011-10-01 03:55:54 +020011264 if (PyUnicode_READY(self) == -1)
11265 return NULL;
11266
11267 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11268
Victor Stinner12bab6d2011-10-01 01:53:49 +020011269 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011270 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011271 if (PyUnicode_CheckExact(self)) {
11272 Py_INCREF(self);
11273 return self;
11274 }
11275 else
11276 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011277 }
11278
Victor Stinner12bab6d2011-10-01 01:53:49 +020011279 length = end - start;
11280 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011281 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011282
Victor Stinnerde636f32011-10-01 03:55:54 +020011283 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011284 PyErr_SetString(PyExc_IndexError, "string index out of range");
11285 return NULL;
11286 }
11287
Victor Stinnerb9275c12011-10-05 14:01:42 +020011288 if (PyUnicode_IS_ASCII(self)) {
11289 kind = PyUnicode_KIND(self);
11290 data = PyUnicode_1BYTE_DATA(self);
11291 return unicode_fromascii(data + start, length);
11292 }
11293 else {
11294 kind = PyUnicode_KIND(self);
11295 data = PyUnicode_1BYTE_DATA(self);
11296 return PyUnicode_FromKindAndData(kind,
11297 data + PyUnicode_KIND_SIZE(kind, start),
11298 length);
11299 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011300}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011301
11302static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011303do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011304{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011305 int kind;
11306 void *data;
11307 Py_ssize_t len, i, j;
11308
11309 if (PyUnicode_READY(self) == -1)
11310 return NULL;
11311
11312 kind = PyUnicode_KIND(self);
11313 data = PyUnicode_DATA(self);
11314 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011315
Benjamin Peterson14339b62009-01-31 16:36:08 +000011316 i = 0;
11317 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011318 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011319 i++;
11320 }
11321 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011322
Benjamin Peterson14339b62009-01-31 16:36:08 +000011323 j = len;
11324 if (striptype != LEFTSTRIP) {
11325 do {
11326 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011327 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011328 j++;
11329 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011330
Victor Stinner12bab6d2011-10-01 01:53:49 +020011331 return PyUnicode_Substring((PyObject*)self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011332}
11333
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011334
11335static PyObject *
11336do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
11337{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011338 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011339
Benjamin Peterson14339b62009-01-31 16:36:08 +000011340 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11341 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011342
Benjamin Peterson14339b62009-01-31 16:36:08 +000011343 if (sep != NULL && sep != Py_None) {
11344 if (PyUnicode_Check(sep))
11345 return _PyUnicode_XStrip(self, striptype, sep);
11346 else {
11347 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011348 "%s arg must be None or str",
11349 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011350 return NULL;
11351 }
11352 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011353
Benjamin Peterson14339b62009-01-31 16:36:08 +000011354 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011355}
11356
11357
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011358PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011359 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011360\n\
11361Return a copy of the string S with leading and trailing\n\
11362whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011363If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011364
11365static PyObject *
11366unicode_strip(PyUnicodeObject *self, PyObject *args)
11367{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011368 if (PyTuple_GET_SIZE(args) == 0)
11369 return do_strip(self, BOTHSTRIP); /* Common case */
11370 else
11371 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011372}
11373
11374
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011375PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011376 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011377\n\
11378Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011379If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011380
11381static PyObject *
11382unicode_lstrip(PyUnicodeObject *self, PyObject *args)
11383{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011384 if (PyTuple_GET_SIZE(args) == 0)
11385 return do_strip(self, LEFTSTRIP); /* Common case */
11386 else
11387 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011388}
11389
11390
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011391PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011392 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011393\n\
11394Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011395If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011396
11397static PyObject *
11398unicode_rstrip(PyUnicodeObject *self, PyObject *args)
11399{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011400 if (PyTuple_GET_SIZE(args) == 0)
11401 return do_strip(self, RIGHTSTRIP); /* Common case */
11402 else
11403 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011404}
11405
11406
Guido van Rossumd57fd912000-03-10 22:53:23 +000011407static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +000011408unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011409{
11410 PyUnicodeObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011411 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011412
Georg Brandl222de0f2009-04-12 12:01:50 +000011413 if (len < 1) {
11414 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011415 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011416 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011417
Tim Peters7a29bd52001-09-12 03:03:31 +000011418 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011419 /* no repeat, return original string */
11420 Py_INCREF(str);
11421 return (PyObject*) str;
11422 }
Tim Peters8f422462000-09-09 06:13:41 +000011423
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011424 if (PyUnicode_READY(str) == -1)
11425 return NULL;
11426
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011427 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011428 PyErr_SetString(PyExc_OverflowError,
11429 "repeated string is too long");
11430 return NULL;
11431 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011432 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011433
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011434 u = (PyUnicodeObject *)PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435 if (!u)
11436 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011437 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011438
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011439 if (PyUnicode_GET_LENGTH(str) == 1) {
11440 const int kind = PyUnicode_KIND(str);
11441 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11442 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011443 if (kind == PyUnicode_1BYTE_KIND)
11444 memset(to, (unsigned char)fill_char, len);
11445 else {
11446 for (n = 0; n < len; ++n)
11447 PyUnicode_WRITE(kind, to, n, fill_char);
11448 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011449 }
11450 else {
11451 /* number of characters copied this far */
11452 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
11453 const Py_ssize_t char_size = PyUnicode_CHARACTER_SIZE(str);
11454 char *to = (char *) PyUnicode_DATA(u);
11455 Py_MEMCPY(to, PyUnicode_DATA(str),
11456 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011457 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011458 n = (done <= nchars-done) ? done : nchars-done;
11459 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011460 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011461 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462 }
11463
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011464 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011465 return (PyObject*) u;
11466}
11467
Alexander Belopolsky40018472011-02-26 01:02:56 +000011468PyObject *
11469PyUnicode_Replace(PyObject *obj,
11470 PyObject *subobj,
11471 PyObject *replobj,
11472 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011473{
11474 PyObject *self;
11475 PyObject *str1;
11476 PyObject *str2;
11477 PyObject *result;
11478
11479 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011480 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011481 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011482 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011483 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011484 Py_DECREF(self);
11485 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011486 }
11487 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011488 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011489 Py_DECREF(self);
11490 Py_DECREF(str1);
11491 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011492 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011493 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011494 Py_DECREF(self);
11495 Py_DECREF(str1);
11496 Py_DECREF(str2);
11497 return result;
11498}
11499
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011500PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011501 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011502\n\
11503Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011504old replaced by new. If the optional argument count is\n\
11505given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011506
11507static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011508unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011509{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011510 PyObject *str1;
11511 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011512 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011513 PyObject *result;
11514
Martin v. Löwis18e16552006-02-15 17:27:45 +000011515 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011516 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011517 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011518 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011519 str1 = PyUnicode_FromObject(str1);
11520 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11521 return NULL;
11522 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011523 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011524 Py_DECREF(str1);
11525 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011526 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011527
11528 result = replace(self, str1, str2, maxcount);
11529
11530 Py_DECREF(str1);
11531 Py_DECREF(str2);
11532 return result;
11533}
11534
Alexander Belopolsky40018472011-02-26 01:02:56 +000011535static PyObject *
11536unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011537{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011538 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011539 Py_ssize_t isize;
11540 Py_ssize_t osize, squote, dquote, i, o;
11541 Py_UCS4 max, quote;
11542 int ikind, okind;
11543 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011544
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011545 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011546 return NULL;
11547
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011548 isize = PyUnicode_GET_LENGTH(unicode);
11549 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011550
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011551 /* Compute length of output, quote characters, and
11552 maximum character */
11553 osize = 2; /* quotes */
11554 max = 127;
11555 squote = dquote = 0;
11556 ikind = PyUnicode_KIND(unicode);
11557 for (i = 0; i < isize; i++) {
11558 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11559 switch (ch) {
11560 case '\'': squote++; osize++; break;
11561 case '"': dquote++; osize++; break;
11562 case '\\': case '\t': case '\r': case '\n':
11563 osize += 2; break;
11564 default:
11565 /* Fast-path ASCII */
11566 if (ch < ' ' || ch == 0x7f)
11567 osize += 4; /* \xHH */
11568 else if (ch < 0x7f)
11569 osize++;
11570 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11571 osize++;
11572 max = ch > max ? ch : max;
11573 }
11574 else if (ch < 0x100)
11575 osize += 4; /* \xHH */
11576 else if (ch < 0x10000)
11577 osize += 6; /* \uHHHH */
11578 else
11579 osize += 10; /* \uHHHHHHHH */
11580 }
11581 }
11582
11583 quote = '\'';
11584 if (squote) {
11585 if (dquote)
11586 /* Both squote and dquote present. Use squote,
11587 and escape them */
11588 osize += squote;
11589 else
11590 quote = '"';
11591 }
11592
11593 repr = PyUnicode_New(osize, max);
11594 if (repr == NULL)
11595 return NULL;
11596 okind = PyUnicode_KIND(repr);
11597 odata = PyUnicode_DATA(repr);
11598
11599 PyUnicode_WRITE(okind, odata, 0, quote);
11600 PyUnicode_WRITE(okind, odata, osize-1, quote);
11601
11602 for (i = 0, o = 1; i < isize; i++) {
11603 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011604
11605 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011606 if ((ch == quote) || (ch == '\\')) {
11607 PyUnicode_WRITE(okind, odata, o++, '\\');
11608 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011609 continue;
11610 }
11611
Benjamin Peterson29060642009-01-31 22:14:21 +000011612 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011613 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011614 PyUnicode_WRITE(okind, odata, o++, '\\');
11615 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011616 }
11617 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011618 PyUnicode_WRITE(okind, odata, o++, '\\');
11619 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011620 }
11621 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011622 PyUnicode_WRITE(okind, odata, o++, '\\');
11623 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011624 }
11625
11626 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011627 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011628 PyUnicode_WRITE(okind, odata, o++, '\\');
11629 PyUnicode_WRITE(okind, odata, o++, 'x');
11630 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
11631 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011632 }
11633
Georg Brandl559e5d72008-06-11 18:37:52 +000011634 /* Copy ASCII characters as-is */
11635 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011636 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011637 }
11638
Benjamin Peterson29060642009-01-31 22:14:21 +000011639 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000011640 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011641 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000011642 (categories Z* and C* except ASCII space)
11643 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011644 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011645 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011646 if (ch <= 0xff) {
11647 PyUnicode_WRITE(okind, odata, o++, '\\');
11648 PyUnicode_WRITE(okind, odata, o++, 'x');
11649 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
11650 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011651 }
11652 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011653 else if (ch >= 0x10000) {
11654 PyUnicode_WRITE(okind, odata, o++, '\\');
11655 PyUnicode_WRITE(okind, odata, o++, 'U');
11656 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 28) & 0xF]);
11657 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 24) & 0xF]);
11658 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 20) & 0xF]);
11659 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 16) & 0xF]);
11660 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
11661 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
11662 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
11663 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011664 }
11665 /* Map 16-bit characters to '\uxxxx' */
11666 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011667 PyUnicode_WRITE(okind, odata, o++, '\\');
11668 PyUnicode_WRITE(okind, odata, o++, 'u');
11669 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
11670 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
11671 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
11672 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011673 }
11674 }
11675 /* Copy characters as-is */
11676 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011677 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011678 }
11679 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000011680 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011681 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020011682 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000011683 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011684}
11685
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011686PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011687 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011688\n\
11689Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011690such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011691arguments start and end are interpreted as in slice notation.\n\
11692\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011693Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011694
11695static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011696unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011697{
Jesus Ceaac451502011-04-20 17:09:23 +020011698 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011699 Py_ssize_t start;
11700 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011701 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011702
Jesus Ceaac451502011-04-20 17:09:23 +020011703 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
11704 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000011705 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011706
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011707 if (PyUnicode_READY(self) == -1)
11708 return NULL;
11709 if (PyUnicode_READY(substring) == -1)
11710 return NULL;
11711
11712 result = any_find_slice(
Victor Stinnerc3cec782011-10-05 21:24:08 +020011713 asciilib_rfind_slice, ucs1lib_rfind_slice,
11714 ucs2lib_rfind_slice, ucs4lib_rfind_slice,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011715 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011716 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011717
11718 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011719
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011720 if (result == -2)
11721 return NULL;
11722
Christian Heimes217cfd12007-12-02 14:31:20 +000011723 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011724}
11725
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011726PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011727 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011728\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011729Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011730
11731static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011732unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011733{
Jesus Ceaac451502011-04-20 17:09:23 +020011734 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011735 Py_ssize_t start;
11736 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011737 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011738
Jesus Ceaac451502011-04-20 17:09:23 +020011739 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
11740 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000011741 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011742
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011743 if (PyUnicode_READY(self) == -1)
11744 return NULL;
11745 if (PyUnicode_READY(substring) == -1)
11746 return NULL;
11747
11748 result = any_find_slice(
Victor Stinnerc3cec782011-10-05 21:24:08 +020011749 asciilib_rfind_slice, ucs1lib_rfind_slice,
11750 ucs2lib_rfind_slice, ucs4lib_rfind_slice,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011751 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011752 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011753
11754 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011755
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011756 if (result == -2)
11757 return NULL;
11758
Guido van Rossumd57fd912000-03-10 22:53:23 +000011759 if (result < 0) {
11760 PyErr_SetString(PyExc_ValueError, "substring not found");
11761 return NULL;
11762 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011763
Christian Heimes217cfd12007-12-02 14:31:20 +000011764 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011765}
11766
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011767PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011768 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011769\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011770Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011771done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011772
11773static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011774unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011775{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011776 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011777 Py_UCS4 fillchar = ' ';
11778
Victor Stinnere9a29352011-10-01 02:14:59 +020011779 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011780 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011781
Victor Stinnere9a29352011-10-01 02:14:59 +020011782 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011783 return NULL;
11784
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011785 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011786 Py_INCREF(self);
11787 return (PyObject*) self;
11788 }
11789
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011790 return (PyObject*) pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011791}
11792
Alexander Belopolsky40018472011-02-26 01:02:56 +000011793PyObject *
11794PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011795{
11796 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000011797
Guido van Rossumd57fd912000-03-10 22:53:23 +000011798 s = PyUnicode_FromObject(s);
11799 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000011800 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000011801 if (sep != NULL) {
11802 sep = PyUnicode_FromObject(sep);
11803 if (sep == NULL) {
11804 Py_DECREF(s);
11805 return NULL;
11806 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011807 }
11808
Victor Stinner9310abb2011-10-05 00:59:23 +020011809 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011810
11811 Py_DECREF(s);
11812 Py_XDECREF(sep);
11813 return result;
11814}
11815
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011816PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011817 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011818\n\
11819Return a list of the words in S, using sep as the\n\
11820delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000011821splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000011822whitespace string is a separator and empty strings are\n\
11823removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011824
11825static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011826unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011827{
11828 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011829 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011830
Martin v. Löwis18e16552006-02-15 17:27:45 +000011831 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011832 return NULL;
11833
11834 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000011835 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011836 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020011837 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011838 else
Benjamin Peterson29060642009-01-31 22:14:21 +000011839 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011840}
11841
Thomas Wouters477c8d52006-05-27 19:21:47 +000011842PyObject *
11843PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
11844{
11845 PyObject* str_obj;
11846 PyObject* sep_obj;
11847 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011848 int kind1, kind2, kind;
11849 void *buf1 = NULL, *buf2 = NULL;
11850 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011851
11852 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020011853 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011854 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011855 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011856 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000011857 Py_DECREF(str_obj);
11858 return NULL;
11859 }
11860
Victor Stinner14f8f022011-10-05 20:58:25 +020011861 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011862 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020011863 kind = Py_MAX(kind1, kind2);
11864 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011865 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020011866 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011867 if (!buf1)
11868 goto onError;
11869 buf2 = PyUnicode_DATA(sep_obj);
11870 if (kind2 != kind)
11871 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11872 if (!buf2)
11873 goto onError;
11874 len1 = PyUnicode_GET_LENGTH(str_obj);
11875 len2 = PyUnicode_GET_LENGTH(sep_obj);
11876
Victor Stinner14f8f022011-10-05 20:58:25 +020011877 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011878 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020011879 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
11880 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11881 else
11882 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011883 break;
11884 case PyUnicode_2BYTE_KIND:
11885 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11886 break;
11887 case PyUnicode_4BYTE_KIND:
11888 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11889 break;
11890 default:
11891 assert(0);
11892 out = 0;
11893 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011894
11895 Py_DECREF(sep_obj);
11896 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011897 if (kind1 != kind)
11898 PyMem_Free(buf1);
11899 if (kind2 != kind)
11900 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011901
11902 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011903 onError:
11904 Py_DECREF(sep_obj);
11905 Py_DECREF(str_obj);
11906 if (kind1 != kind && buf1)
11907 PyMem_Free(buf1);
11908 if (kind2 != kind && buf2)
11909 PyMem_Free(buf2);
11910 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011911}
11912
11913
11914PyObject *
11915PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
11916{
11917 PyObject* str_obj;
11918 PyObject* sep_obj;
11919 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011920 int kind1, kind2, kind;
11921 void *buf1 = NULL, *buf2 = NULL;
11922 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011923
11924 str_obj = PyUnicode_FromObject(str_in);
11925 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000011926 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011927 sep_obj = PyUnicode_FromObject(sep_in);
11928 if (!sep_obj) {
11929 Py_DECREF(str_obj);
11930 return NULL;
11931 }
11932
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011933 kind1 = PyUnicode_KIND(str_in);
11934 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020011935 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011936 buf1 = PyUnicode_DATA(str_in);
11937 if (kind1 != kind)
11938 buf1 = _PyUnicode_AsKind(str_in, kind);
11939 if (!buf1)
11940 goto onError;
11941 buf2 = PyUnicode_DATA(sep_obj);
11942 if (kind2 != kind)
11943 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11944 if (!buf2)
11945 goto onError;
11946 len1 = PyUnicode_GET_LENGTH(str_obj);
11947 len2 = PyUnicode_GET_LENGTH(sep_obj);
11948
11949 switch(PyUnicode_KIND(str_in)) {
11950 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020011951 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
11952 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11953 else
11954 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011955 break;
11956 case PyUnicode_2BYTE_KIND:
11957 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11958 break;
11959 case PyUnicode_4BYTE_KIND:
11960 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11961 break;
11962 default:
11963 assert(0);
11964 out = 0;
11965 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011966
11967 Py_DECREF(sep_obj);
11968 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011969 if (kind1 != kind)
11970 PyMem_Free(buf1);
11971 if (kind2 != kind)
11972 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011973
11974 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011975 onError:
11976 Py_DECREF(sep_obj);
11977 Py_DECREF(str_obj);
11978 if (kind1 != kind && buf1)
11979 PyMem_Free(buf1);
11980 if (kind2 != kind && buf2)
11981 PyMem_Free(buf2);
11982 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011983}
11984
11985PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011986 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011987\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000011988Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011989the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011990found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000011991
11992static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011993unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011994{
Victor Stinner9310abb2011-10-05 00:59:23 +020011995 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011996}
11997
11998PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000011999 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012000\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012001Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012002the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012003separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012004
12005static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012006unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012007{
Victor Stinner9310abb2011-10-05 00:59:23 +020012008 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012009}
12010
Alexander Belopolsky40018472011-02-26 01:02:56 +000012011PyObject *
12012PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012013{
12014 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012015
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012016 s = PyUnicode_FromObject(s);
12017 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012018 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012019 if (sep != NULL) {
12020 sep = PyUnicode_FromObject(sep);
12021 if (sep == NULL) {
12022 Py_DECREF(s);
12023 return NULL;
12024 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012025 }
12026
Victor Stinner9310abb2011-10-05 00:59:23 +020012027 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012028
12029 Py_DECREF(s);
12030 Py_XDECREF(sep);
12031 return result;
12032}
12033
12034PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012035 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012036\n\
12037Return a list of the words in S, using sep as the\n\
12038delimiter string, starting at the end of the string and\n\
12039working to the front. If maxsplit is given, at most maxsplit\n\
12040splits are done. If sep is not specified, any whitespace string\n\
12041is a separator.");
12042
12043static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012044unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012045{
12046 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012047 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012048
Martin v. Löwis18e16552006-02-15 17:27:45 +000012049 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012050 return NULL;
12051
12052 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012053 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012054 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012055 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012056 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012057 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012058}
12059
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012060PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012061 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012062\n\
12063Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012064Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012065is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012066
12067static PyObject*
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012068unicode_splitlines(PyUnicodeObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012069{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012070 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012071 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012072
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012073 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12074 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012075 return NULL;
12076
Guido van Rossum86662912000-04-11 15:38:46 +000012077 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012078}
12079
12080static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012081PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012082{
Walter Dörwald346737f2007-05-31 10:44:43 +000012083 if (PyUnicode_CheckExact(self)) {
12084 Py_INCREF(self);
12085 return self;
12086 } else
12087 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012088 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012089}
12090
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012091PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012092 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012093\n\
12094Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012095and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012096
12097static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012098unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012099{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012100 return fixup(self, fixswapcase);
12101}
12102
Georg Brandlceee0772007-11-27 23:48:05 +000012103PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012104 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012105\n\
12106Return a translation table usable for str.translate().\n\
12107If there is only one argument, it must be a dictionary mapping Unicode\n\
12108ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012109Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012110If there are two arguments, they must be strings of equal length, and\n\
12111in the resulting dictionary, each character in x will be mapped to the\n\
12112character at the same position in y. If there is a third argument, it\n\
12113must be a string, whose characters will be mapped to None in the result.");
12114
12115static PyObject*
12116unicode_maketrans(PyUnicodeObject *null, PyObject *args)
12117{
12118 PyObject *x, *y = NULL, *z = NULL;
12119 PyObject *new = NULL, *key, *value;
12120 Py_ssize_t i = 0;
12121 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012122
Georg Brandlceee0772007-11-27 23:48:05 +000012123 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12124 return NULL;
12125 new = PyDict_New();
12126 if (!new)
12127 return NULL;
12128 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012129 int x_kind, y_kind, z_kind;
12130 void *x_data, *y_data, *z_data;
12131
Georg Brandlceee0772007-11-27 23:48:05 +000012132 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012133 if (!PyUnicode_Check(x)) {
12134 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12135 "be a string if there is a second argument");
12136 goto err;
12137 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012138 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012139 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12140 "arguments must have equal length");
12141 goto err;
12142 }
12143 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012144 x_kind = PyUnicode_KIND(x);
12145 y_kind = PyUnicode_KIND(y);
12146 x_data = PyUnicode_DATA(x);
12147 y_data = PyUnicode_DATA(y);
12148 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12149 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12150 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012151 if (!key || !value)
12152 goto err;
12153 res = PyDict_SetItem(new, key, value);
12154 Py_DECREF(key);
12155 Py_DECREF(value);
12156 if (res < 0)
12157 goto err;
12158 }
12159 /* create entries for deleting chars in z */
12160 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012161 z_kind = PyUnicode_KIND(z);
12162 z_data = PyUnicode_DATA(z);
Georg Brandlceee0772007-11-27 23:48:05 +000012163 for (i = 0; i < PyUnicode_GET_SIZE(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012164 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012165 if (!key)
12166 goto err;
12167 res = PyDict_SetItem(new, key, Py_None);
12168 Py_DECREF(key);
12169 if (res < 0)
12170 goto err;
12171 }
12172 }
12173 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012174 int kind;
12175 void *data;
12176
Georg Brandlceee0772007-11-27 23:48:05 +000012177 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012178 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012179 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12180 "to maketrans it must be a dict");
12181 goto err;
12182 }
12183 /* copy entries into the new dict, converting string keys to int keys */
12184 while (PyDict_Next(x, &i, &key, &value)) {
12185 if (PyUnicode_Check(key)) {
12186 /* convert string keys to integer keys */
12187 PyObject *newkey;
12188 if (PyUnicode_GET_SIZE(key) != 1) {
12189 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12190 "table must be of length 1");
12191 goto err;
12192 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012193 kind = PyUnicode_KIND(key);
12194 data = PyUnicode_DATA(key);
12195 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012196 if (!newkey)
12197 goto err;
12198 res = PyDict_SetItem(new, newkey, value);
12199 Py_DECREF(newkey);
12200 if (res < 0)
12201 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012202 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012203 /* just keep integer keys */
12204 if (PyDict_SetItem(new, key, value) < 0)
12205 goto err;
12206 } else {
12207 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12208 "be strings or integers");
12209 goto err;
12210 }
12211 }
12212 }
12213 return new;
12214 err:
12215 Py_DECREF(new);
12216 return NULL;
12217}
12218
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012219PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012220 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012221\n\
12222Return a copy of the string S, where all characters have been mapped\n\
12223through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012224Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012225Unmapped characters are left untouched. Characters mapped to None\n\
12226are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012227
12228static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012229unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012230{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012231 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012232}
12233
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012234PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012235 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012236\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012237Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012238
12239static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012240unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012241{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012242 return fixup(self, fixupper);
12243}
12244
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012245PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012246 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012247\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012248Pad a numeric string S with zeros on the left, to fill a field\n\
12249of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012250
12251static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012252unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012253{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012254 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012255 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012256 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012257 int kind;
12258 void *data;
12259 Py_UCS4 chr;
12260
12261 if (PyUnicode_READY(self) == -1)
12262 return NULL;
12263
Martin v. Löwis18e16552006-02-15 17:27:45 +000012264 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012265 return NULL;
12266
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012267 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012268 if (PyUnicode_CheckExact(self)) {
12269 Py_INCREF(self);
12270 return (PyObject*) self;
12271 }
12272 else
Victor Stinner2219e0a2011-10-01 01:16:59 +020012273 return PyUnicode_Copy((PyObject*)self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012274 }
12275
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012276 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012277
12278 u = pad(self, fill, 0, '0');
12279
Walter Dörwald068325e2002-04-15 13:36:47 +000012280 if (u == NULL)
12281 return NULL;
12282
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012283 kind = PyUnicode_KIND(u);
12284 data = PyUnicode_DATA(u);
12285 chr = PyUnicode_READ(kind, data, fill);
12286
12287 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012288 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012289 PyUnicode_WRITE(kind, data, 0, chr);
12290 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012291 }
12292
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012293 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012294 return (PyObject*) u;
12295}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012296
12297#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012298static PyObject *
12299unicode__decimal2ascii(PyObject *self)
12300{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012301 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012302}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012303#endif
12304
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012305PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012306 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012307\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012308Return True if S starts with the specified prefix, False otherwise.\n\
12309With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012310With optional end, stop comparing S at that position.\n\
12311prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012312
12313static PyObject *
12314unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012315 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012316{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012317 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012318 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012319 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012320 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012321 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012322
Jesus Ceaac451502011-04-20 17:09:23 +020012323 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012324 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012325 if (PyTuple_Check(subobj)) {
12326 Py_ssize_t i;
12327 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
12328 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012329 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012330 if (substring == NULL)
12331 return NULL;
12332 result = tailmatch(self, substring, start, end, -1);
12333 Py_DECREF(substring);
12334 if (result) {
12335 Py_RETURN_TRUE;
12336 }
12337 }
12338 /* nothing matched */
12339 Py_RETURN_FALSE;
12340 }
12341 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012342 if (substring == NULL) {
12343 if (PyErr_ExceptionMatches(PyExc_TypeError))
12344 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12345 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012346 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012347 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012348 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012349 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012350 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012351}
12352
12353
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012354PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012355 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012356\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012357Return True if S ends with the specified suffix, False otherwise.\n\
12358With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012359With optional end, stop comparing S at that position.\n\
12360suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012361
12362static PyObject *
12363unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012364 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012365{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012366 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012367 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012368 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012369 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012370 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012371
Jesus Ceaac451502011-04-20 17:09:23 +020012372 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012373 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012374 if (PyTuple_Check(subobj)) {
12375 Py_ssize_t i;
12376 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
12377 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012378 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012379 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012380 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012381 result = tailmatch(self, substring, start, end, +1);
12382 Py_DECREF(substring);
12383 if (result) {
12384 Py_RETURN_TRUE;
12385 }
12386 }
12387 Py_RETURN_FALSE;
12388 }
12389 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012390 if (substring == NULL) {
12391 if (PyErr_ExceptionMatches(PyExc_TypeError))
12392 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12393 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012394 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012395 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012396 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012397 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012398 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012399}
12400
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012401#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012402
12403PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012404 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012405\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012406Return a formatted version of S, using substitutions from args and kwargs.\n\
12407The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012408
Eric Smith27bbca62010-11-04 17:06:58 +000012409PyDoc_STRVAR(format_map__doc__,
12410 "S.format_map(mapping) -> str\n\
12411\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012412Return a formatted version of S, using substitutions from mapping.\n\
12413The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012414
Eric Smith4a7d76d2008-05-30 18:10:19 +000012415static PyObject *
12416unicode__format__(PyObject* self, PyObject* args)
12417{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012418 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012419
12420 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12421 return NULL;
12422
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012423 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012424 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012425 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012426}
12427
Eric Smith8c663262007-08-25 02:26:07 +000012428PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012429 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012430\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012431Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012432
12433static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012434unicode__sizeof__(PyUnicodeObject *v)
12435{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012436 Py_ssize_t size;
12437
12438 /* If it's a compact object, account for base structure +
12439 character data. */
12440 if (PyUnicode_IS_COMPACT_ASCII(v))
12441 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12442 else if (PyUnicode_IS_COMPACT(v))
12443 size = sizeof(PyCompactUnicodeObject) +
12444 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_CHARACTER_SIZE(v);
12445 else {
12446 /* If it is a two-block object, account for base object, and
12447 for character block if present. */
12448 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012449 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012450 size += (PyUnicode_GET_LENGTH(v) + 1) *
12451 PyUnicode_CHARACTER_SIZE(v);
12452 }
12453 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012454 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012455 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012456 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012457 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012458 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012459
12460 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012461}
12462
12463PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012464 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012465
12466static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012467unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012468{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012469 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012470 if (!copy)
12471 return NULL;
12472 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012473}
12474
Guido van Rossumd57fd912000-03-10 22:53:23 +000012475static PyMethodDef unicode_methods[] = {
12476
12477 /* Order is according to common usage: often used methods should
12478 appear first, since lookup is done sequentially. */
12479
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012480 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012481 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12482 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012483 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012484 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12485 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12486 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12487 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12488 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12489 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12490 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012491 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012492 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12493 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12494 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012495 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012496 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12497 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12498 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012499 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012500 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012501 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012502 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012503 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12504 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12505 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12506 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12507 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12508 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12509 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12510 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12511 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12512 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12513 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12514 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12515 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12516 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012517 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012518 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012519 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012520 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012521 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012522 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012523 {"maketrans", (PyCFunction) unicode_maketrans,
12524 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012525 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012526#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012527 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012528#endif
12529
12530#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012531 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012532 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012533#endif
12534
Benjamin Peterson14339b62009-01-31 16:36:08 +000012535 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012536 {NULL, NULL}
12537};
12538
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012539static PyObject *
12540unicode_mod(PyObject *v, PyObject *w)
12541{
Brian Curtindfc80e32011-08-10 20:28:54 -050012542 if (!PyUnicode_Check(v))
12543 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012544 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012545}
12546
12547static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012548 0, /*nb_add*/
12549 0, /*nb_subtract*/
12550 0, /*nb_multiply*/
12551 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012552};
12553
Guido van Rossumd57fd912000-03-10 22:53:23 +000012554static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012555 (lenfunc) unicode_length, /* sq_length */
12556 PyUnicode_Concat, /* sq_concat */
12557 (ssizeargfunc) unicode_repeat, /* sq_repeat */
12558 (ssizeargfunc) unicode_getitem, /* sq_item */
12559 0, /* sq_slice */
12560 0, /* sq_ass_item */
12561 0, /* sq_ass_slice */
12562 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012563};
12564
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012565static PyObject*
12566unicode_subscript(PyUnicodeObject* self, PyObject* item)
12567{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012568 if (PyUnicode_READY(self) == -1)
12569 return NULL;
12570
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000012571 if (PyIndex_Check(item)) {
12572 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012573 if (i == -1 && PyErr_Occurred())
12574 return NULL;
12575 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012576 i += PyUnicode_GET_LENGTH(self);
Victor Stinner2fe5ced2011-10-02 00:25:40 +020012577 return unicode_getitem((PyObject*)self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012578 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000012579 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012580 PyObject *result;
12581 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012582 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012583 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012584
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012585 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000012586 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012587 return NULL;
12588 }
12589
12590 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012591 return PyUnicode_New(0, 0);
12592 } else if (start == 0 && step == 1 &&
12593 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000012594 PyUnicode_CheckExact(self)) {
12595 Py_INCREF(self);
12596 return (PyObject *)self;
12597 } else if (step == 1) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012598 return PyUnicode_Substring((PyObject*)self,
12599 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012600 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012601 /* General case */
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012602 max_char = 0;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012603 src_kind = PyUnicode_KIND(self);
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012604 kind_limit = kind_maxchar_limit(src_kind);
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012605 src_data = PyUnicode_DATA(self);
12606 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
12607 ch = PyUnicode_READ(src_kind, src_data, cur);
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012608 if (ch > max_char) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012609 max_char = ch;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012610 if (max_char >= kind_limit)
12611 break;
12612 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012613 }
12614 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012615 if (result == NULL)
12616 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012617 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012618 dest_data = PyUnicode_DATA(result);
12619
12620 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012621 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
12622 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012623 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012624 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012625 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012626 } else {
12627 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
12628 return NULL;
12629 }
12630}
12631
12632static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012633 (lenfunc)unicode_length, /* mp_length */
12634 (binaryfunc)unicode_subscript, /* mp_subscript */
12635 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012636};
12637
Guido van Rossumd57fd912000-03-10 22:53:23 +000012638
Guido van Rossumd57fd912000-03-10 22:53:23 +000012639/* Helpers for PyUnicode_Format() */
12640
12641static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000012642getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012643{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012644 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012645 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012646 (*p_argidx)++;
12647 if (arglen < 0)
12648 return args;
12649 else
12650 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012651 }
12652 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012653 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012654 return NULL;
12655}
12656
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012657/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012658
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012659static PyObject *
12660formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012661{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012662 char *p;
12663 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012664 double x;
Tim Petersced69f82003-09-16 20:30:58 +000012665
Guido van Rossumd57fd912000-03-10 22:53:23 +000012666 x = PyFloat_AsDouble(v);
12667 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012668 return NULL;
12669
Guido van Rossumd57fd912000-03-10 22:53:23 +000012670 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012671 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000012672
Eric Smith0923d1d2009-04-16 20:16:10 +000012673 p = PyOS_double_to_string(x, type, prec,
12674 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012675 if (p == NULL)
12676 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012677 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000012678 PyMem_Free(p);
12679 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012680}
12681
Tim Peters38fd5b62000-09-21 05:43:11 +000012682static PyObject*
12683formatlong(PyObject *val, int flags, int prec, int type)
12684{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012685 char *buf;
12686 int len;
12687 PyObject *str; /* temporary string object. */
12688 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000012689
Benjamin Peterson14339b62009-01-31 16:36:08 +000012690 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
12691 if (!str)
12692 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012693 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012694 Py_DECREF(str);
12695 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000012696}
12697
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012698static Py_UCS4
12699formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012700{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000012701 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012702 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012703 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012704 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000012705 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012706 goto onError;
12707 }
12708 else {
12709 /* Integer input truncated to a character */
12710 long x;
12711 x = PyLong_AsLong(v);
12712 if (x == -1 && PyErr_Occurred())
12713 goto onError;
12714
12715 if (x < 0 || x > 0x10ffff) {
12716 PyErr_SetString(PyExc_OverflowError,
12717 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012718 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000012719 }
12720
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012721 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012722 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000012723
Benjamin Peterson29060642009-01-31 22:14:21 +000012724 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012725 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012726 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012727 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012728}
12729
Alexander Belopolsky40018472011-02-26 01:02:56 +000012730PyObject *
12731PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012732{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012733 void *fmt;
12734 int fmtkind;
12735 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012736 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012737 int r;
12738 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012739 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012740 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012741 PyObject *temp = NULL;
12742 PyObject *second = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012743 PyUnicodeObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012744 _PyAccu acc;
12745 static PyObject *plus, *minus, *blank, *zero, *percent;
12746
12747 if (!plus && !(plus = get_latin1_char('+')))
12748 return NULL;
12749 if (!minus && !(minus = get_latin1_char('-')))
12750 return NULL;
12751 if (!blank && !(blank = get_latin1_char(' ')))
12752 return NULL;
12753 if (!zero && !(zero = get_latin1_char('0')))
12754 return NULL;
12755 if (!percent && !(percent = get_latin1_char('%')))
12756 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000012757
Guido van Rossumd57fd912000-03-10 22:53:23 +000012758 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012759 PyErr_BadInternalCall();
12760 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012761 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012762 uformat = (PyUnicodeObject*)PyUnicode_FromObject(format);
12763 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012764 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012765 if (_PyAccu_Init(&acc))
12766 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012767 fmt = PyUnicode_DATA(uformat);
12768 fmtkind = PyUnicode_KIND(uformat);
12769 fmtcnt = PyUnicode_GET_LENGTH(uformat);
12770 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012771
Guido van Rossumd57fd912000-03-10 22:53:23 +000012772 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012773 arglen = PyTuple_Size(args);
12774 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012775 }
12776 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012777 arglen = -1;
12778 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012779 }
Christian Heimes90aa7642007-12-19 02:45:37 +000012780 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000012781 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000012782 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012783
12784 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012785 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012786 PyObject *nonfmt;
12787 Py_ssize_t nonfmtpos;
12788 nonfmtpos = fmtpos++;
12789 while (fmtcnt >= 0 &&
12790 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
12791 fmtpos++;
12792 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012793 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012794 nonfmt = PyUnicode_Substring((PyObject *) uformat, nonfmtpos, fmtpos);
12795 if (nonfmt == NULL)
12796 goto onError;
12797 r = _PyAccu_Accumulate(&acc, nonfmt);
12798 Py_DECREF(nonfmt);
12799 if (r)
12800 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012801 }
12802 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012803 /* Got a format specifier */
12804 int flags = 0;
12805 Py_ssize_t width = -1;
12806 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012807 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012808 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000012809 int isnumok;
12810 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012811 void *pbuf = NULL;
12812 Py_ssize_t pindex, len;
12813 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012815 fmtpos++;
12816 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
12817 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000012818 Py_ssize_t keylen;
12819 PyObject *key;
12820 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000012821
Benjamin Peterson29060642009-01-31 22:14:21 +000012822 if (dict == NULL) {
12823 PyErr_SetString(PyExc_TypeError,
12824 "format requires a mapping");
12825 goto onError;
12826 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012827 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000012828 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012829 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000012830 /* Skip over balanced parentheses */
12831 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012832 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000012833 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012834 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000012835 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012836 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000012837 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012838 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000012839 if (fmtcnt < 0 || pcount > 0) {
12840 PyErr_SetString(PyExc_ValueError,
12841 "incomplete format key");
12842 goto onError;
12843 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020012844 key = PyUnicode_Substring((PyObject*)uformat,
12845 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000012846 if (key == NULL)
12847 goto onError;
12848 if (args_owned) {
12849 Py_DECREF(args);
12850 args_owned = 0;
12851 }
12852 args = PyObject_GetItem(dict, key);
12853 Py_DECREF(key);
12854 if (args == NULL) {
12855 goto onError;
12856 }
12857 args_owned = 1;
12858 arglen = -1;
12859 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012860 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012861 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012862 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012863 case '-': flags |= F_LJUST; continue;
12864 case '+': flags |= F_SIGN; continue;
12865 case ' ': flags |= F_BLANK; continue;
12866 case '#': flags |= F_ALT; continue;
12867 case '0': flags |= F_ZERO; continue;
12868 }
12869 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012870 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012871 if (c == '*') {
12872 v = getnextarg(args, arglen, &argidx);
12873 if (v == NULL)
12874 goto onError;
12875 if (!PyLong_Check(v)) {
12876 PyErr_SetString(PyExc_TypeError,
12877 "* wants int");
12878 goto onError;
12879 }
12880 width = PyLong_AsLong(v);
12881 if (width == -1 && PyErr_Occurred())
12882 goto onError;
12883 if (width < 0) {
12884 flags |= F_LJUST;
12885 width = -width;
12886 }
12887 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012888 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012889 }
12890 else if (c >= '0' && c <= '9') {
12891 width = c - '0';
12892 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012893 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012894 if (c < '0' || c > '9')
12895 break;
12896 if ((width*10) / 10 != width) {
12897 PyErr_SetString(PyExc_ValueError,
12898 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000012899 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000012900 }
12901 width = width*10 + (c - '0');
12902 }
12903 }
12904 if (c == '.') {
12905 prec = 0;
12906 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012907 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012908 if (c == '*') {
12909 v = getnextarg(args, arglen, &argidx);
12910 if (v == NULL)
12911 goto onError;
12912 if (!PyLong_Check(v)) {
12913 PyErr_SetString(PyExc_TypeError,
12914 "* wants int");
12915 goto onError;
12916 }
12917 prec = PyLong_AsLong(v);
12918 if (prec == -1 && PyErr_Occurred())
12919 goto onError;
12920 if (prec < 0)
12921 prec = 0;
12922 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012923 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012924 }
12925 else if (c >= '0' && c <= '9') {
12926 prec = c - '0';
12927 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012928 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012929 if (c < '0' || c > '9')
12930 break;
12931 if ((prec*10) / 10 != prec) {
12932 PyErr_SetString(PyExc_ValueError,
12933 "prec too big");
12934 goto onError;
12935 }
12936 prec = prec*10 + (c - '0');
12937 }
12938 }
12939 } /* prec */
12940 if (fmtcnt >= 0) {
12941 if (c == 'h' || c == 'l' || c == 'L') {
12942 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012943 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012944 }
12945 }
12946 if (fmtcnt < 0) {
12947 PyErr_SetString(PyExc_ValueError,
12948 "incomplete format");
12949 goto onError;
12950 }
12951 if (c != '%') {
12952 v = getnextarg(args, arglen, &argidx);
12953 if (v == NULL)
12954 goto onError;
12955 }
12956 sign = 0;
12957 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012958 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000012959 switch (c) {
12960
12961 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012962 _PyAccu_Accumulate(&acc, percent);
12963 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000012964
12965 case 's':
12966 case 'r':
12967 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000012968 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000012969 temp = v;
12970 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012971 }
12972 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012973 if (c == 's')
12974 temp = PyObject_Str(v);
12975 else if (c == 'r')
12976 temp = PyObject_Repr(v);
12977 else
12978 temp = PyObject_ASCII(v);
12979 if (temp == NULL)
12980 goto onError;
12981 if (PyUnicode_Check(temp))
12982 /* nothing to do */;
12983 else {
12984 Py_DECREF(temp);
12985 PyErr_SetString(PyExc_TypeError,
12986 "%s argument has non-string str()");
12987 goto onError;
12988 }
12989 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012990 if (PyUnicode_READY(temp) == -1) {
12991 Py_CLEAR(temp);
12992 goto onError;
12993 }
12994 pbuf = PyUnicode_DATA(temp);
12995 kind = PyUnicode_KIND(temp);
12996 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012997 if (prec >= 0 && len > prec)
12998 len = prec;
12999 break;
13000
13001 case 'i':
13002 case 'd':
13003 case 'u':
13004 case 'o':
13005 case 'x':
13006 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013007 isnumok = 0;
13008 if (PyNumber_Check(v)) {
13009 PyObject *iobj=NULL;
13010
13011 if (PyLong_Check(v)) {
13012 iobj = v;
13013 Py_INCREF(iobj);
13014 }
13015 else {
13016 iobj = PyNumber_Long(v);
13017 }
13018 if (iobj!=NULL) {
13019 if (PyLong_Check(iobj)) {
13020 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013021 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013022 Py_DECREF(iobj);
13023 if (!temp)
13024 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013025 if (PyUnicode_READY(temp) == -1) {
13026 Py_CLEAR(temp);
13027 goto onError;
13028 }
13029 pbuf = PyUnicode_DATA(temp);
13030 kind = PyUnicode_KIND(temp);
13031 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013032 sign = 1;
13033 }
13034 else {
13035 Py_DECREF(iobj);
13036 }
13037 }
13038 }
13039 if (!isnumok) {
13040 PyErr_Format(PyExc_TypeError,
13041 "%%%c format: a number is required, "
13042 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13043 goto onError;
13044 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013045 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013046 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013047 fillobj = zero;
13048 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013049 break;
13050
13051 case 'e':
13052 case 'E':
13053 case 'f':
13054 case 'F':
13055 case 'g':
13056 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013057 temp = formatfloat(v, flags, prec, c);
13058 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013059 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013060 if (PyUnicode_READY(temp) == -1) {
13061 Py_CLEAR(temp);
13062 goto onError;
13063 }
13064 pbuf = PyUnicode_DATA(temp);
13065 kind = PyUnicode_KIND(temp);
13066 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013067 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013068 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013069 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013070 fillobj = zero;
13071 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013072 break;
13073
13074 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013075 {
13076 Py_UCS4 ch = formatchar(v);
13077 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013078 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013079 temp = _PyUnicode_FromUCS4(&ch, 1);
13080 if (temp == NULL)
13081 goto onError;
13082 pbuf = PyUnicode_DATA(temp);
13083 kind = PyUnicode_KIND(temp);
13084 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013085 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013086 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013087
13088 default:
13089 PyErr_Format(PyExc_ValueError,
13090 "unsupported format character '%c' (0x%x) "
13091 "at index %zd",
13092 (31<=c && c<=126) ? (char)c : '?',
13093 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013094 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013095 goto onError;
13096 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013097 /* pbuf is initialized here. */
13098 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013099 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013100 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13101 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013102 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013103 pindex++;
13104 }
13105 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13106 signobj = plus;
13107 len--;
13108 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013109 }
13110 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013111 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013112 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013113 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013114 else
13115 sign = 0;
13116 }
13117 if (width < len)
13118 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013119 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013120 if (fill != ' ') {
13121 assert(signobj != NULL);
13122 if (_PyAccu_Accumulate(&acc, signobj))
13123 goto onError;
13124 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013125 if (width > len)
13126 width--;
13127 }
13128 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013129 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013130 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013131 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013132 second = get_latin1_char(
13133 PyUnicode_READ(kind, pbuf, pindex + 1));
13134 pindex += 2;
13135 if (second == NULL ||
13136 _PyAccu_Accumulate(&acc, zero) ||
13137 _PyAccu_Accumulate(&acc, second))
13138 goto onError;
13139 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013140 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013141 width -= 2;
13142 if (width < 0)
13143 width = 0;
13144 len -= 2;
13145 }
13146 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013147 assert(fillobj != NULL);
Benjamin Peterson29060642009-01-31 22:14:21 +000013148 do {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013149 if (_PyAccu_Accumulate(&acc, fillobj))
13150 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013151 } while (--width > len);
13152 }
13153 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013154 if (sign) {
13155 assert(signobj != NULL);
13156 if (_PyAccu_Accumulate(&acc, signobj))
13157 goto onError;
13158 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013159 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013160 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13161 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013162 second = get_latin1_char(
13163 PyUnicode_READ(kind, pbuf, pindex + 1));
13164 pindex += 2;
13165 if (second == NULL ||
13166 _PyAccu_Accumulate(&acc, zero) ||
13167 _PyAccu_Accumulate(&acc, second))
13168 goto onError;
13169 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013170 }
13171 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013172 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013173 if (temp != NULL) {
13174 assert(pbuf == PyUnicode_DATA(temp));
13175 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013176 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013177 else {
13178 const char *p = (const char *) pbuf;
13179 assert(pbuf != NULL);
13180 p = p + PyUnicode_KIND_SIZE(kind, pindex);
13181 v = PyUnicode_FromKindAndData(kind, p, len);
13182 }
13183 if (v == NULL)
13184 goto onError;
13185 r = _PyAccu_Accumulate(&acc, v);
13186 Py_DECREF(v);
13187 if (r)
13188 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013189 while (--width >= len) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013190 if (_PyAccu_Accumulate(&acc, blank))
13191 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013192 }
13193 if (dict && (argidx < arglen) && c != '%') {
13194 PyErr_SetString(PyExc_TypeError,
13195 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013196 goto onError;
13197 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013198 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013199 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013200 } /* until end */
13201 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013202 PyErr_SetString(PyExc_TypeError,
13203 "not all arguments converted during string formatting");
13204 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013205 }
13206
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013207 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013208 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013209 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013210 }
13211 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013212 Py_XDECREF(temp);
13213 Py_XDECREF(second);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013214 return (PyObject *)result;
13215
Benjamin Peterson29060642009-01-31 22:14:21 +000013216 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013217 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013218 Py_XDECREF(temp);
13219 Py_XDECREF(second);
13220 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013221 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013222 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013223 }
13224 return NULL;
13225}
13226
Jeremy Hylton938ace62002-07-17 16:30:39 +000013227static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013228unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13229
Tim Peters6d6c1a32001-08-02 04:15:00 +000013230static PyObject *
13231unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13232{
Benjamin Peterson29060642009-01-31 22:14:21 +000013233 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013234 static char *kwlist[] = {"object", "encoding", "errors", 0};
13235 char *encoding = NULL;
13236 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013237
Benjamin Peterson14339b62009-01-31 16:36:08 +000013238 if (type != &PyUnicode_Type)
13239 return unicode_subtype_new(type, args, kwds);
13240 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013241 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013242 return NULL;
13243 if (x == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013244 return (PyObject *)PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013245 if (encoding == NULL && errors == NULL)
13246 return PyObject_Str(x);
13247 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013248 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013249}
13250
Guido van Rossume023fe02001-08-30 03:12:59 +000013251static PyObject *
13252unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13253{
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013254 PyUnicodeObject *unicode, *self;
13255 Py_ssize_t length, char_size;
13256 int share_wstr, share_utf8;
13257 unsigned int kind;
13258 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013259
Benjamin Peterson14339b62009-01-31 16:36:08 +000013260 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013261
13262 unicode = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
13263 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013264 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013265 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013266 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013267 return NULL;
13268
13269 self = (PyUnicodeObject *) type->tp_alloc(type, 0);
13270 if (self == NULL) {
13271 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013272 return NULL;
13273 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013274 kind = PyUnicode_KIND(unicode);
13275 length = PyUnicode_GET_LENGTH(unicode);
13276
13277 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013278#ifdef Py_DEBUG
13279 _PyUnicode_HASH(self) = -1;
13280#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013281 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013282#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013283 _PyUnicode_STATE(self).interned = 0;
13284 _PyUnicode_STATE(self).kind = kind;
13285 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013286 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013287 _PyUnicode_STATE(self).ready = 1;
13288 _PyUnicode_WSTR(self) = NULL;
13289 _PyUnicode_UTF8_LENGTH(self) = 0;
13290 _PyUnicode_UTF8(self) = NULL;
13291 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013292 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013293
13294 share_utf8 = 0;
13295 share_wstr = 0;
13296 if (kind == PyUnicode_1BYTE_KIND) {
13297 char_size = 1;
13298 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13299 share_utf8 = 1;
13300 }
13301 else if (kind == PyUnicode_2BYTE_KIND) {
13302 char_size = 2;
13303 if (sizeof(wchar_t) == 2)
13304 share_wstr = 1;
13305 }
13306 else {
13307 assert(kind == PyUnicode_4BYTE_KIND);
13308 char_size = 4;
13309 if (sizeof(wchar_t) == 4)
13310 share_wstr = 1;
13311 }
13312
13313 /* Ensure we won't overflow the length. */
13314 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13315 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013316 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013317 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013318 data = PyObject_MALLOC((length + 1) * char_size);
13319 if (data == NULL) {
13320 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013321 goto onError;
13322 }
13323
Victor Stinnerc3c74152011-10-02 20:39:55 +020013324 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013325 if (share_utf8) {
13326 _PyUnicode_UTF8_LENGTH(self) = length;
13327 _PyUnicode_UTF8(self) = data;
13328 }
13329 if (share_wstr) {
13330 _PyUnicode_WSTR_LENGTH(self) = length;
13331 _PyUnicode_WSTR(self) = (wchar_t *)data;
13332 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013333
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013334 Py_MEMCPY(data, PyUnicode_DATA(unicode),
13335 PyUnicode_KIND_SIZE(kind, length + 1));
13336 Py_DECREF(unicode);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013337 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013338#ifdef Py_DEBUG
13339 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13340#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013341 return (PyObject *)self;
13342
13343onError:
13344 Py_DECREF(unicode);
13345 Py_DECREF(self);
13346 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013347}
13348
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013349PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013350 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013351\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013352Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013353encoding defaults to the current default string encoding.\n\
13354errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013355
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013356static PyObject *unicode_iter(PyObject *seq);
13357
Guido van Rossumd57fd912000-03-10 22:53:23 +000013358PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013359 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013360 "str", /* tp_name */
13361 sizeof(PyUnicodeObject), /* tp_size */
13362 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013363 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013364 (destructor)unicode_dealloc, /* tp_dealloc */
13365 0, /* tp_print */
13366 0, /* tp_getattr */
13367 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013368 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013369 unicode_repr, /* tp_repr */
13370 &unicode_as_number, /* tp_as_number */
13371 &unicode_as_sequence, /* tp_as_sequence */
13372 &unicode_as_mapping, /* tp_as_mapping */
13373 (hashfunc) unicode_hash, /* tp_hash*/
13374 0, /* tp_call*/
13375 (reprfunc) unicode_str, /* tp_str */
13376 PyObject_GenericGetAttr, /* tp_getattro */
13377 0, /* tp_setattro */
13378 0, /* tp_as_buffer */
13379 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013380 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013381 unicode_doc, /* tp_doc */
13382 0, /* tp_traverse */
13383 0, /* tp_clear */
13384 PyUnicode_RichCompare, /* tp_richcompare */
13385 0, /* tp_weaklistoffset */
13386 unicode_iter, /* tp_iter */
13387 0, /* tp_iternext */
13388 unicode_methods, /* tp_methods */
13389 0, /* tp_members */
13390 0, /* tp_getset */
13391 &PyBaseObject_Type, /* tp_base */
13392 0, /* tp_dict */
13393 0, /* tp_descr_get */
13394 0, /* tp_descr_set */
13395 0, /* tp_dictoffset */
13396 0, /* tp_init */
13397 0, /* tp_alloc */
13398 unicode_new, /* tp_new */
13399 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013400};
13401
13402/* Initialize the Unicode implementation */
13403
Thomas Wouters78890102000-07-22 19:25:51 +000013404void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013405{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013406 int i;
13407
Thomas Wouters477c8d52006-05-27 19:21:47 +000013408 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013409 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013410 0x000A, /* LINE FEED */
13411 0x000D, /* CARRIAGE RETURN */
13412 0x001C, /* FILE SEPARATOR */
13413 0x001D, /* GROUP SEPARATOR */
13414 0x001E, /* RECORD SEPARATOR */
13415 0x0085, /* NEXT LINE */
13416 0x2028, /* LINE SEPARATOR */
13417 0x2029, /* PARAGRAPH SEPARATOR */
13418 };
13419
Fred Drakee4315f52000-05-09 19:53:39 +000013420 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013421 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013422 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013423 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013424 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013425
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013426 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013427 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013428 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013429 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013430
13431 /* initialize the linebreak bloom filter */
13432 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013433 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013434 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013435
13436 PyType_Ready(&EncodingMapType);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013437}
13438
13439/* Finalize the Unicode implementation */
13440
Christian Heimesa156e092008-02-16 07:38:31 +000013441int
13442PyUnicode_ClearFreeList(void)
13443{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013444 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013445}
13446
Guido van Rossumd57fd912000-03-10 22:53:23 +000013447void
Thomas Wouters78890102000-07-22 19:25:51 +000013448_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013449{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013450 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013451
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013452 Py_XDECREF(unicode_empty);
13453 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013454
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013455 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013456 if (unicode_latin1[i]) {
13457 Py_DECREF(unicode_latin1[i]);
13458 unicode_latin1[i] = NULL;
13459 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013460 }
Christian Heimesa156e092008-02-16 07:38:31 +000013461 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013462}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013463
Walter Dörwald16807132007-05-25 13:52:07 +000013464void
13465PyUnicode_InternInPlace(PyObject **p)
13466{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013467 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
13468 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013469#ifdef Py_DEBUG
13470 assert(s != NULL);
13471 assert(_PyUnicode_CHECK(s));
13472#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013473 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013474 return;
13475#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013476 /* If it's a subclass, we don't really know what putting
13477 it in the interned dict might do. */
13478 if (!PyUnicode_CheckExact(s))
13479 return;
13480 if (PyUnicode_CHECK_INTERNED(s))
13481 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013482 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013483 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013484 return;
13485 }
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013486 s = (PyUnicodeObject *)(*p);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013487 if (interned == NULL) {
13488 interned = PyDict_New();
13489 if (interned == NULL) {
13490 PyErr_Clear(); /* Don't leave an exception */
13491 return;
13492 }
13493 }
13494 /* It might be that the GetItem call fails even
13495 though the key is present in the dictionary,
13496 namely when this happens during a stack overflow. */
13497 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000013498 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013499 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013500
Benjamin Peterson29060642009-01-31 22:14:21 +000013501 if (t) {
13502 Py_INCREF(t);
13503 Py_DECREF(*p);
13504 *p = t;
13505 return;
13506 }
Walter Dörwald16807132007-05-25 13:52:07 +000013507
Benjamin Peterson14339b62009-01-31 16:36:08 +000013508 PyThreadState_GET()->recursion_critical = 1;
13509 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
13510 PyErr_Clear();
13511 PyThreadState_GET()->recursion_critical = 0;
13512 return;
13513 }
13514 PyThreadState_GET()->recursion_critical = 0;
13515 /* The two references in interned are not counted by refcnt.
13516 The deallocator will take care of this */
13517 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013518 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013519}
13520
13521void
13522PyUnicode_InternImmortal(PyObject **p)
13523{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013524 PyUnicodeObject *u = (PyUnicodeObject *)*p;
13525
Benjamin Peterson14339b62009-01-31 16:36:08 +000013526 PyUnicode_InternInPlace(p);
13527 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013528 _PyUnicode_STATE(u).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013529 Py_INCREF(*p);
13530 }
Walter Dörwald16807132007-05-25 13:52:07 +000013531}
13532
13533PyObject *
13534PyUnicode_InternFromString(const char *cp)
13535{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013536 PyObject *s = PyUnicode_FromString(cp);
13537 if (s == NULL)
13538 return NULL;
13539 PyUnicode_InternInPlace(&s);
13540 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000013541}
13542
Alexander Belopolsky40018472011-02-26 01:02:56 +000013543void
13544_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000013545{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013546 PyObject *keys;
13547 PyUnicodeObject *s;
13548 Py_ssize_t i, n;
13549 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000013550
Benjamin Peterson14339b62009-01-31 16:36:08 +000013551 if (interned == NULL || !PyDict_Check(interned))
13552 return;
13553 keys = PyDict_Keys(interned);
13554 if (keys == NULL || !PyList_Check(keys)) {
13555 PyErr_Clear();
13556 return;
13557 }
Walter Dörwald16807132007-05-25 13:52:07 +000013558
Benjamin Peterson14339b62009-01-31 16:36:08 +000013559 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
13560 detector, interned unicode strings are not forcibly deallocated;
13561 rather, we give them their stolen references back, and then clear
13562 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000013563
Benjamin Peterson14339b62009-01-31 16:36:08 +000013564 n = PyList_GET_SIZE(keys);
13565 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000013566 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013567 for (i = 0; i < n; i++) {
13568 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013569 if (PyUnicode_READY(s) == -1) {
13570 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013571 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013572 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013573 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013574 case SSTATE_NOT_INTERNED:
13575 /* XXX Shouldn't happen */
13576 break;
13577 case SSTATE_INTERNED_IMMORTAL:
13578 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013579 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013580 break;
13581 case SSTATE_INTERNED_MORTAL:
13582 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013583 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013584 break;
13585 default:
13586 Py_FatalError("Inconsistent interned string state.");
13587 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013588 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013589 }
13590 fprintf(stderr, "total size of all interned strings: "
13591 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
13592 "mortal/immortal\n", mortal_size, immortal_size);
13593 Py_DECREF(keys);
13594 PyDict_Clear(interned);
13595 Py_DECREF(interned);
13596 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000013597}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013598
13599
13600/********************* Unicode Iterator **************************/
13601
13602typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013603 PyObject_HEAD
13604 Py_ssize_t it_index;
13605 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013606} unicodeiterobject;
13607
13608static void
13609unicodeiter_dealloc(unicodeiterobject *it)
13610{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013611 _PyObject_GC_UNTRACK(it);
13612 Py_XDECREF(it->it_seq);
13613 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013614}
13615
13616static int
13617unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
13618{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013619 Py_VISIT(it->it_seq);
13620 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013621}
13622
13623static PyObject *
13624unicodeiter_next(unicodeiterobject *it)
13625{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013626 PyUnicodeObject *seq;
13627 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013628
Benjamin Peterson14339b62009-01-31 16:36:08 +000013629 assert(it != NULL);
13630 seq = it->it_seq;
13631 if (seq == NULL)
13632 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013633 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013634
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013635 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
13636 int kind = PyUnicode_KIND(seq);
13637 void *data = PyUnicode_DATA(seq);
13638 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
13639 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013640 if (item != NULL)
13641 ++it->it_index;
13642 return item;
13643 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013644
Benjamin Peterson14339b62009-01-31 16:36:08 +000013645 Py_DECREF(seq);
13646 it->it_seq = NULL;
13647 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013648}
13649
13650static PyObject *
13651unicodeiter_len(unicodeiterobject *it)
13652{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013653 Py_ssize_t len = 0;
13654 if (it->it_seq)
13655 len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index;
13656 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013657}
13658
13659PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
13660
13661static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013662 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000013663 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000013664 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013665};
13666
13667PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013668 PyVarObject_HEAD_INIT(&PyType_Type, 0)
13669 "str_iterator", /* tp_name */
13670 sizeof(unicodeiterobject), /* tp_basicsize */
13671 0, /* tp_itemsize */
13672 /* methods */
13673 (destructor)unicodeiter_dealloc, /* tp_dealloc */
13674 0, /* tp_print */
13675 0, /* tp_getattr */
13676 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013677 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013678 0, /* tp_repr */
13679 0, /* tp_as_number */
13680 0, /* tp_as_sequence */
13681 0, /* tp_as_mapping */
13682 0, /* tp_hash */
13683 0, /* tp_call */
13684 0, /* tp_str */
13685 PyObject_GenericGetAttr, /* tp_getattro */
13686 0, /* tp_setattro */
13687 0, /* tp_as_buffer */
13688 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
13689 0, /* tp_doc */
13690 (traverseproc)unicodeiter_traverse, /* tp_traverse */
13691 0, /* tp_clear */
13692 0, /* tp_richcompare */
13693 0, /* tp_weaklistoffset */
13694 PyObject_SelfIter, /* tp_iter */
13695 (iternextfunc)unicodeiter_next, /* tp_iternext */
13696 unicodeiter_methods, /* tp_methods */
13697 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013698};
13699
13700static PyObject *
13701unicode_iter(PyObject *seq)
13702{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013703 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013704
Benjamin Peterson14339b62009-01-31 16:36:08 +000013705 if (!PyUnicode_Check(seq)) {
13706 PyErr_BadInternalCall();
13707 return NULL;
13708 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013709 if (PyUnicode_READY(seq) == -1)
13710 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013711 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
13712 if (it == NULL)
13713 return NULL;
13714 it->it_index = 0;
13715 Py_INCREF(seq);
13716 it->it_seq = (PyUnicodeObject *)seq;
13717 _PyObject_GC_TRACK(it);
13718 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013719}
13720
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013721#define UNIOP(x) Py_UNICODE_##x
13722#define UNIOP_t Py_UNICODE
13723#include "uniops.h"
13724#undef UNIOP
13725#undef UNIOP_t
13726#define UNIOP(x) Py_UCS4_##x
13727#define UNIOP_t Py_UCS4
13728#include "uniops.h"
13729#undef UNIOP
13730#undef UNIOP_t
Victor Stinner331ea922010-08-10 16:37:20 +000013731
Victor Stinner71133ff2010-09-01 23:43:53 +000013732Py_UNICODE*
Victor Stinner46408602010-09-03 16:18:00 +000013733PyUnicode_AsUnicodeCopy(PyObject *object)
Victor Stinner71133ff2010-09-01 23:43:53 +000013734{
13735 PyUnicodeObject *unicode = (PyUnicodeObject *)object;
13736 Py_UNICODE *copy;
13737 Py_ssize_t size;
13738
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013739 if (!PyUnicode_Check(unicode)) {
13740 PyErr_BadArgument();
13741 return NULL;
13742 }
Victor Stinner71133ff2010-09-01 23:43:53 +000013743 /* Ensure we won't overflow the size. */
13744 if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
13745 PyErr_NoMemory();
13746 return NULL;
13747 }
13748 size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
13749 size *= sizeof(Py_UNICODE);
13750 copy = PyMem_Malloc(size);
13751 if (copy == NULL) {
13752 PyErr_NoMemory();
13753 return NULL;
13754 }
13755 memcpy(copy, PyUnicode_AS_UNICODE(unicode), size);
13756 return copy;
13757}
Martin v. Löwis5b222132007-06-10 09:51:05 +000013758
Georg Brandl66c221e2010-10-14 07:04:07 +000013759/* A _string module, to export formatter_parser and formatter_field_name_split
13760 to the string.Formatter class implemented in Python. */
13761
13762static PyMethodDef _string_methods[] = {
13763 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
13764 METH_O, PyDoc_STR("split the argument as a field name")},
13765 {"formatter_parser", (PyCFunction) formatter_parser,
13766 METH_O, PyDoc_STR("parse the argument as a format string")},
13767 {NULL, NULL}
13768};
13769
13770static struct PyModuleDef _string_module = {
13771 PyModuleDef_HEAD_INIT,
13772 "_string",
13773 PyDoc_STR("string helper module"),
13774 0,
13775 _string_methods,
13776 NULL,
13777 NULL,
13778 NULL,
13779 NULL
13780};
13781
13782PyMODINIT_FUNC
13783PyInit__string(void)
13784{
13785 return PyModule_Create(&_string_module);
13786}
13787
13788
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013789#ifdef __cplusplus
13790}
13791#endif