blob: 7e29a03c8674857aa785a302ee06747fe7471255 [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;
Victor Stinnerdd077322011-10-07 17:02:31 +02009127 Py_ssize_t seplen;
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;
Victor Stinnerdd077322011-10-07 17:02:31 +02009136 int use_memcpy;
9137 unsigned char *res_data = NULL, *sep_data = NULL;
9138 PyObject *last_obj;
9139 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009140
Tim Peters05eba1f2004-08-27 21:32:02 +00009141 fseq = PySequence_Fast(seq, "");
9142 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009143 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009144 }
9145
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009146 /* NOTE: the following code can't call back into Python code,
9147 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009148 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009149
Tim Peters05eba1f2004-08-27 21:32:02 +00009150 seqlen = PySequence_Fast_GET_SIZE(fseq);
9151 /* If empty sequence, return u"". */
9152 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009153 Py_DECREF(fseq);
9154 Py_INCREF(unicode_empty);
9155 res = unicode_empty;
9156 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009157 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009158
Tim Peters05eba1f2004-08-27 21:32:02 +00009159 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009160 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009161 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009162 if (seqlen == 1) {
9163 if (PyUnicode_CheckExact(items[0])) {
9164 res = items[0];
9165 Py_INCREF(res);
9166 Py_DECREF(fseq);
9167 return res;
9168 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009169 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009170 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009171 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009172 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009173 /* Set up sep and seplen */
9174 if (separator == NULL) {
9175 /* fall back to a blank space separator */
9176 sep = PyUnicode_FromOrdinal(' ');
9177 if (!sep)
9178 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009179 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009180 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009181 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009182 else {
9183 if (!PyUnicode_Check(separator)) {
9184 PyErr_Format(PyExc_TypeError,
9185 "separator: expected str instance,"
9186 " %.80s found",
9187 Py_TYPE(separator)->tp_name);
9188 goto onError;
9189 }
9190 if (PyUnicode_READY(separator))
9191 goto onError;
9192 sep = separator;
9193 seplen = PyUnicode_GET_LENGTH(separator);
9194 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9195 /* inc refcount to keep this code path symmetric with the
9196 above case of a blank separator */
9197 Py_INCREF(sep);
9198 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009199 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009200 }
9201
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009202 /* There are at least two things to join, or else we have a subclass
9203 * of str in the sequence.
9204 * Do a pre-pass to figure out the total amount of space we'll
9205 * need (sz), and see whether all argument are strings.
9206 */
9207 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009208#ifdef Py_DEBUG
9209 use_memcpy = 0;
9210#else
9211 use_memcpy = 1;
9212#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009213 for (i = 0; i < seqlen; i++) {
9214 const Py_ssize_t old_sz = sz;
9215 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009216 if (!PyUnicode_Check(item)) {
9217 PyErr_Format(PyExc_TypeError,
9218 "sequence item %zd: expected str instance,"
9219 " %.80s found",
9220 i, Py_TYPE(item)->tp_name);
9221 goto onError;
9222 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009223 if (PyUnicode_READY(item) == -1)
9224 goto onError;
9225 sz += PyUnicode_GET_LENGTH(item);
9226 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009227 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009228 if (i != 0)
9229 sz += seplen;
9230 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9231 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009232 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009233 goto onError;
9234 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009235 if (use_memcpy && last_obj != NULL) {
9236 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9237 use_memcpy = 0;
9238 }
9239 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009240 }
Tim Petersced69f82003-09-16 20:30:58 +00009241
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009242 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009243 if (res == NULL)
9244 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009245
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009246 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009247#ifdef Py_DEBUG
9248 use_memcpy = 0;
9249#else
9250 if (use_memcpy) {
9251 res_data = PyUnicode_1BYTE_DATA(res);
9252 kind = PyUnicode_KIND(res);
9253 if (seplen != 0)
9254 sep_data = PyUnicode_1BYTE_DATA(sep);
9255 }
9256#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009257 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009258 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009259 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009260 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009261 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009262 if (use_memcpy) {
9263 Py_MEMCPY(res_data,
9264 sep_data,
9265 PyUnicode_KIND_SIZE(kind, seplen));
9266 res_data += PyUnicode_KIND_SIZE(kind, seplen);
9267 }
9268 else {
9269 copy_characters(res, res_offset, sep, 0, seplen);
9270 res_offset += seplen;
9271 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009272 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009273 itemlen = PyUnicode_GET_LENGTH(item);
9274 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009275 if (use_memcpy) {
9276 Py_MEMCPY(res_data,
9277 PyUnicode_DATA(item),
9278 PyUnicode_KIND_SIZE(kind, itemlen));
9279 res_data += PyUnicode_KIND_SIZE(kind, itemlen);
9280 }
9281 else {
9282 copy_characters(res, res_offset, item, 0, itemlen);
9283 res_offset += itemlen;
9284 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009285 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009286 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009287 if (use_memcpy)
9288 assert(res_data == PyUnicode_1BYTE_DATA(res)
9289 + PyUnicode_KIND_SIZE(kind, PyUnicode_GET_LENGTH(res)));
9290 else
9291 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009292
Tim Peters05eba1f2004-08-27 21:32:02 +00009293 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009294 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009295 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009296 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009297
Benjamin Peterson29060642009-01-31 22:14:21 +00009298 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009299 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009300 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009301 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009302 return NULL;
9303}
9304
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009305#define FILL(kind, data, value, start, length) \
9306 do { \
9307 Py_ssize_t i_ = 0; \
9308 assert(kind != PyUnicode_WCHAR_KIND); \
9309 switch ((kind)) { \
9310 case PyUnicode_1BYTE_KIND: { \
9311 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9312 memset(to_, (unsigned char)value, length); \
9313 break; \
9314 } \
9315 case PyUnicode_2BYTE_KIND: { \
9316 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9317 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9318 break; \
9319 } \
9320 default: { \
9321 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9322 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9323 break; \
9324 } \
9325 } \
9326 } while (0)
9327
Victor Stinner9310abb2011-10-05 00:59:23 +02009328static PyObject *
9329pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009330 Py_ssize_t left,
9331 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009332 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009333{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009334 PyObject *u;
9335 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009336 int kind;
9337 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009338
9339 if (left < 0)
9340 left = 0;
9341 if (right < 0)
9342 right = 0;
9343
Tim Peters7a29bd52001-09-12 03:03:31 +00009344 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009345 Py_INCREF(self);
9346 return self;
9347 }
9348
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009349 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9350 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009351 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9352 return NULL;
9353 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009354 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9355 if (fill > maxchar)
9356 maxchar = fill;
9357 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009358 if (!u)
9359 return NULL;
9360
9361 kind = PyUnicode_KIND(u);
9362 data = PyUnicode_DATA(u);
9363 if (left)
9364 FILL(kind, data, fill, 0, left);
9365 if (right)
9366 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009367 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009368 assert(_PyUnicode_CheckConsistency(u, 1));
9369 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009370}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009371#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009372
Alexander Belopolsky40018472011-02-26 01:02:56 +00009373PyObject *
9374PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009375{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009376 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009377
9378 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009379 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009380 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009381
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009382 switch(PyUnicode_KIND(string)) {
9383 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009384 if (PyUnicode_IS_ASCII(string))
9385 list = asciilib_splitlines(
9386 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9387 PyUnicode_GET_LENGTH(string), keepends);
9388 else
9389 list = ucs1lib_splitlines(
9390 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9391 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009392 break;
9393 case PyUnicode_2BYTE_KIND:
9394 list = ucs2lib_splitlines(
9395 (PyObject*) string, PyUnicode_2BYTE_DATA(string),
9396 PyUnicode_GET_LENGTH(string), keepends);
9397 break;
9398 case PyUnicode_4BYTE_KIND:
9399 list = ucs4lib_splitlines(
9400 (PyObject*) string, PyUnicode_4BYTE_DATA(string),
9401 PyUnicode_GET_LENGTH(string), keepends);
9402 break;
9403 default:
9404 assert(0);
9405 list = 0;
9406 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009407 Py_DECREF(string);
9408 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009409}
9410
Alexander Belopolsky40018472011-02-26 01:02:56 +00009411static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009412split(PyObject *self,
9413 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009414 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009415{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009416 int kind1, kind2, kind;
9417 void *buf1, *buf2;
9418 Py_ssize_t len1, len2;
9419 PyObject* out;
9420
Guido van Rossumd57fd912000-03-10 22:53:23 +00009421 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009422 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009423
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009424 if (PyUnicode_READY(self) == -1)
9425 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009426
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009427 if (substring == NULL)
9428 switch(PyUnicode_KIND(self)) {
9429 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009430 if (PyUnicode_IS_ASCII(self))
9431 return asciilib_split_whitespace(
9432 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9433 PyUnicode_GET_LENGTH(self), maxcount
9434 );
9435 else
9436 return ucs1lib_split_whitespace(
9437 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9438 PyUnicode_GET_LENGTH(self), maxcount
9439 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009440 case PyUnicode_2BYTE_KIND:
9441 return ucs2lib_split_whitespace(
9442 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9443 PyUnicode_GET_LENGTH(self), maxcount
9444 );
9445 case PyUnicode_4BYTE_KIND:
9446 return ucs4lib_split_whitespace(
9447 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
9448 PyUnicode_GET_LENGTH(self), maxcount
9449 );
9450 default:
9451 assert(0);
9452 return NULL;
9453 }
9454
9455 if (PyUnicode_READY(substring) == -1)
9456 return NULL;
9457
9458 kind1 = PyUnicode_KIND(self);
9459 kind2 = PyUnicode_KIND(substring);
9460 kind = kind1 > kind2 ? kind1 : kind2;
9461 buf1 = PyUnicode_DATA(self);
9462 buf2 = PyUnicode_DATA(substring);
9463 if (kind1 != kind)
9464 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9465 if (!buf1)
9466 return NULL;
9467 if (kind2 != kind)
9468 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9469 if (!buf2) {
9470 if (kind1 != kind) PyMem_Free(buf1);
9471 return NULL;
9472 }
9473 len1 = PyUnicode_GET_LENGTH(self);
9474 len2 = PyUnicode_GET_LENGTH(substring);
9475
9476 switch(kind) {
9477 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009478 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9479 out = asciilib_split(
9480 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9481 else
9482 out = ucs1lib_split(
9483 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009484 break;
9485 case PyUnicode_2BYTE_KIND:
9486 out = ucs2lib_split(
9487 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9488 break;
9489 case PyUnicode_4BYTE_KIND:
9490 out = ucs4lib_split(
9491 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9492 break;
9493 default:
9494 out = NULL;
9495 }
9496 if (kind1 != kind)
9497 PyMem_Free(buf1);
9498 if (kind2 != kind)
9499 PyMem_Free(buf2);
9500 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009501}
9502
Alexander Belopolsky40018472011-02-26 01:02:56 +00009503static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009504rsplit(PyObject *self,
9505 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009506 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009507{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009508 int kind1, kind2, kind;
9509 void *buf1, *buf2;
9510 Py_ssize_t len1, len2;
9511 PyObject* out;
9512
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009513 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009514 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009515
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009516 if (PyUnicode_READY(self) == -1)
9517 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009518
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009519 if (substring == NULL)
9520 switch(PyUnicode_KIND(self)) {
9521 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009522 if (PyUnicode_IS_ASCII(self))
9523 return asciilib_rsplit_whitespace(
9524 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9525 PyUnicode_GET_LENGTH(self), maxcount
9526 );
9527 else
9528 return ucs1lib_rsplit_whitespace(
9529 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9530 PyUnicode_GET_LENGTH(self), maxcount
9531 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009532 case PyUnicode_2BYTE_KIND:
9533 return ucs2lib_rsplit_whitespace(
9534 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9535 PyUnicode_GET_LENGTH(self), maxcount
9536 );
9537 case PyUnicode_4BYTE_KIND:
9538 return ucs4lib_rsplit_whitespace(
9539 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
9540 PyUnicode_GET_LENGTH(self), maxcount
9541 );
9542 default:
9543 assert(0);
9544 return NULL;
9545 }
9546
9547 if (PyUnicode_READY(substring) == -1)
9548 return NULL;
9549
9550 kind1 = PyUnicode_KIND(self);
9551 kind2 = PyUnicode_KIND(substring);
9552 kind = kind1 > kind2 ? kind1 : kind2;
9553 buf1 = PyUnicode_DATA(self);
9554 buf2 = PyUnicode_DATA(substring);
9555 if (kind1 != kind)
9556 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9557 if (!buf1)
9558 return NULL;
9559 if (kind2 != kind)
9560 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9561 if (!buf2) {
9562 if (kind1 != kind) PyMem_Free(buf1);
9563 return NULL;
9564 }
9565 len1 = PyUnicode_GET_LENGTH(self);
9566 len2 = PyUnicode_GET_LENGTH(substring);
9567
9568 switch(kind) {
9569 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009570 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9571 out = asciilib_rsplit(
9572 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9573 else
9574 out = ucs1lib_rsplit(
9575 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009576 break;
9577 case PyUnicode_2BYTE_KIND:
9578 out = ucs2lib_rsplit(
9579 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9580 break;
9581 case PyUnicode_4BYTE_KIND:
9582 out = ucs4lib_rsplit(
9583 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9584 break;
9585 default:
9586 out = NULL;
9587 }
9588 if (kind1 != kind)
9589 PyMem_Free(buf1);
9590 if (kind2 != kind)
9591 PyMem_Free(buf2);
9592 return out;
9593}
9594
9595static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009596anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9597 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009598{
9599 switch(kind) {
9600 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009601 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
9602 return asciilib_find(buf1, len1, buf2, len2, offset);
9603 else
9604 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009605 case PyUnicode_2BYTE_KIND:
9606 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9607 case PyUnicode_4BYTE_KIND:
9608 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9609 }
9610 assert(0);
9611 return -1;
9612}
9613
9614static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009615anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
9616 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009617{
9618 switch(kind) {
9619 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009620 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
9621 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
9622 else
9623 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009624 case PyUnicode_2BYTE_KIND:
9625 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
9626 case PyUnicode_4BYTE_KIND:
9627 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
9628 }
9629 assert(0);
9630 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009631}
9632
Alexander Belopolsky40018472011-02-26 01:02:56 +00009633static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009634replace(PyObject *self, PyObject *str1,
9635 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009636{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009637 PyObject *u;
9638 char *sbuf = PyUnicode_DATA(self);
9639 char *buf1 = PyUnicode_DATA(str1);
9640 char *buf2 = PyUnicode_DATA(str2);
9641 int srelease = 0, release1 = 0, release2 = 0;
9642 int skind = PyUnicode_KIND(self);
9643 int kind1 = PyUnicode_KIND(str1);
9644 int kind2 = PyUnicode_KIND(str2);
9645 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
9646 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
9647 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009648
9649 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009650 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009651 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009652 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009653
Victor Stinner59de0ee2011-10-07 10:01:28 +02009654 if (str1 == str2)
9655 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009656 if (skind < kind1)
9657 /* substring too wide to be present */
9658 goto nothing;
9659
9660 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +00009661 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009662 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009663 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009664 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009665 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009666 /* replace characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009667 Py_UCS4 u1, u2, maxchar;
9668 int mayshrink, rkind;
9669 u1 = PyUnicode_READ_CHAR(str1, 0);
9670 if (!findchar(sbuf, PyUnicode_KIND(self),
9671 slen, u1, 1))
Thomas Wouters477c8d52006-05-27 19:21:47 +00009672 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009673 u2 = PyUnicode_READ_CHAR(str2, 0);
9674 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9675 /* Replacing u1 with u2 may cause a maxchar reduction in the
9676 result string. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009677 if (u2 > maxchar) {
9678 maxchar = u2;
9679 mayshrink = 0;
9680 }
Victor Stinnerb9275c12011-10-05 14:01:42 +02009681 else
9682 mayshrink = maxchar > 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009683 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009684 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009685 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009686 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009687 rkind = PyUnicode_KIND(u);
9688 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
9689 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009690 if (--maxcount < 0)
9691 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009692 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009693 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009694 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +02009695 unicode_adjust_maxchar(&u);
9696 if (u == NULL)
9697 goto error;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009698 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009699 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009700 int rkind = skind;
9701 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +02009702 PyObject *rstr;
9703 Py_UCS4 maxchar;
9704
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009705 if (kind1 < rkind) {
9706 /* widen substring */
9707 buf1 = _PyUnicode_AsKind(str1, rkind);
9708 if (!buf1) goto error;
9709 release1 = 1;
9710 }
Victor Stinnerc3cec782011-10-05 21:24:08 +02009711 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009712 if (i < 0)
9713 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009714 if (rkind > kind2) {
9715 /* widen replacement */
9716 buf2 = _PyUnicode_AsKind(str2, rkind);
9717 if (!buf2) goto error;
9718 release2 = 1;
9719 }
9720 else if (rkind < kind2) {
9721 /* widen self and buf1 */
9722 rkind = kind2;
9723 if (release1) PyMem_Free(buf1);
9724 sbuf = _PyUnicode_AsKind(self, rkind);
9725 if (!sbuf) goto error;
9726 srelease = 1;
9727 buf1 = _PyUnicode_AsKind(str1, rkind);
9728 if (!buf1) goto error;
9729 release1 = 1;
9730 }
Victor Stinner25a4b292011-10-06 12:31:55 +02009731 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9732 maxchar = Py_MAX(maxchar, PyUnicode_MAX_CHAR_VALUE(str2));
9733 rstr = PyUnicode_New(slen, maxchar);
9734 if (!rstr)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009735 goto error;
Victor Stinner25a4b292011-10-06 12:31:55 +02009736 res = PyUnicode_DATA(rstr);
9737
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009738 memcpy(res, sbuf, PyUnicode_KIND_SIZE(rkind, slen));
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009739 /* change everything in-place, starting with this one */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009740 memcpy(res + PyUnicode_KIND_SIZE(rkind, i),
9741 buf2,
9742 PyUnicode_KIND_SIZE(rkind, len2));
9743 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009744
9745 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +02009746 i = anylib_find(rkind, self,
9747 sbuf+PyUnicode_KIND_SIZE(rkind, i), slen-i,
9748 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009749 if (i == -1)
9750 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009751 memcpy(res + PyUnicode_KIND_SIZE(rkind, i),
9752 buf2,
9753 PyUnicode_KIND_SIZE(rkind, len2));
9754 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009755 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009756
Victor Stinner25a4b292011-10-06 12:31:55 +02009757 u = rstr;
9758 unicode_adjust_maxchar(&u);
9759 if (!u)
9760 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009761 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009762 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009763
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009764 Py_ssize_t n, i, j, ires;
9765 Py_ssize_t product, new_size;
9766 int rkind = skind;
Victor Stinner25a4b292011-10-06 12:31:55 +02009767 PyObject *rstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009768 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +02009769 Py_UCS4 maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009770
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009771 if (kind1 < rkind) {
9772 buf1 = _PyUnicode_AsKind(str1, rkind);
9773 if (!buf1) goto error;
9774 release1 = 1;
9775 }
Victor Stinnerc3cec782011-10-05 21:24:08 +02009776 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009777 if (n == 0)
9778 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009779 if (kind2 < rkind) {
9780 buf2 = _PyUnicode_AsKind(str2, rkind);
9781 if (!buf2) goto error;
9782 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009783 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009784 else if (kind2 > rkind) {
9785 rkind = kind2;
9786 sbuf = _PyUnicode_AsKind(self, rkind);
9787 if (!sbuf) goto error;
9788 srelease = 1;
9789 if (release1) PyMem_Free(buf1);
9790 buf1 = _PyUnicode_AsKind(str1, rkind);
9791 if (!buf1) goto error;
9792 release1 = 1;
9793 }
9794 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
9795 PyUnicode_GET_LENGTH(str1))); */
9796 product = n * (len2-len1);
9797 if ((product / (len2-len1)) != n) {
9798 PyErr_SetString(PyExc_OverflowError,
9799 "replace string is too long");
9800 goto error;
9801 }
9802 new_size = slen + product;
9803 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
9804 PyErr_SetString(PyExc_OverflowError,
9805 "replace string is too long");
9806 goto error;
9807 }
Victor Stinner25a4b292011-10-06 12:31:55 +02009808 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9809 maxchar = Py_MAX(maxchar, PyUnicode_MAX_CHAR_VALUE(str2));
9810 rstr = PyUnicode_New(new_size, maxchar);
9811 if (!rstr)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009812 goto error;
Victor Stinner25a4b292011-10-06 12:31:55 +02009813 res = PyUnicode_DATA(rstr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009814 ires = i = 0;
9815 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009816 while (n-- > 0) {
9817 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +02009818 j = anylib_find(rkind, self,
9819 sbuf + PyUnicode_KIND_SIZE(rkind, i), slen-i,
9820 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009821 if (j == -1)
9822 break;
9823 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009824 /* copy unchanged part [i:j] */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009825 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9826 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9827 PyUnicode_KIND_SIZE(rkind, j-i));
9828 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009829 }
9830 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009831 if (len2 > 0) {
9832 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9833 buf2,
9834 PyUnicode_KIND_SIZE(rkind, len2));
9835 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009836 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009837 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009838 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009839 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +00009840 /* copy tail [i:] */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009841 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9842 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9843 PyUnicode_KIND_SIZE(rkind, slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00009844 } else {
9845 /* interleave */
9846 while (n > 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009847 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9848 buf2,
9849 PyUnicode_KIND_SIZE(rkind, len2));
9850 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009851 if (--n <= 0)
9852 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009853 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9854 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9855 PyUnicode_KIND_SIZE(rkind, 1));
9856 ires++;
9857 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009858 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009859 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9860 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9861 PyUnicode_KIND_SIZE(rkind, slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00009862 }
Victor Stinner25a4b292011-10-06 12:31:55 +02009863 u = rstr;
9864 unicode_adjust_maxchar(&u);
9865 if (u == NULL)
9866 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009867 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009868 if (srelease)
9869 PyMem_FREE(sbuf);
9870 if (release1)
9871 PyMem_FREE(buf1);
9872 if (release2)
9873 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009874 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009875 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009876
Benjamin Peterson29060642009-01-31 22:14:21 +00009877 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00009878 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009879 if (srelease)
9880 PyMem_FREE(sbuf);
9881 if (release1)
9882 PyMem_FREE(buf1);
9883 if (release2)
9884 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009885 if (PyUnicode_CheckExact(self)) {
9886 Py_INCREF(self);
9887 return (PyObject *) self;
9888 }
Victor Stinner034f6cf2011-09-30 02:26:44 +02009889 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009890 error:
9891 if (srelease && sbuf)
9892 PyMem_FREE(sbuf);
9893 if (release1 && buf1)
9894 PyMem_FREE(buf1);
9895 if (release2 && buf2)
9896 PyMem_FREE(buf2);
9897 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009898}
9899
9900/* --- Unicode Object Methods --------------------------------------------- */
9901
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009902PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009903 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009904\n\
9905Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009906characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009907
9908static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +02009909unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009910{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009911 return fixup(self, fixtitle);
9912}
9913
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009914PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009915 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009916\n\
9917Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +00009918have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009919
9920static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +02009921unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009922{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009923 return fixup(self, fixcapitalize);
9924}
9925
9926#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009927PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009928 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009929\n\
9930Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009931normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009932
9933static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009934unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009935{
9936 PyObject *list;
9937 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009938 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009939
Guido van Rossumd57fd912000-03-10 22:53:23 +00009940 /* Split into words */
9941 list = split(self, NULL, -1);
9942 if (!list)
9943 return NULL;
9944
9945 /* Capitalize each word */
9946 for (i = 0; i < PyList_GET_SIZE(list); i++) {
9947 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00009948 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009949 if (item == NULL)
9950 goto onError;
9951 Py_DECREF(PyList_GET_ITEM(list, i));
9952 PyList_SET_ITEM(list, i, item);
9953 }
9954
9955 /* Join the words to form a new string */
9956 item = PyUnicode_Join(NULL, list);
9957
Benjamin Peterson29060642009-01-31 22:14:21 +00009958 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009959 Py_DECREF(list);
9960 return (PyObject *)item;
9961}
9962#endif
9963
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009964/* Argument converter. Coerces to a single unicode character */
9965
9966static int
9967convert_uc(PyObject *obj, void *addr)
9968{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009969 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009970 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009971
Benjamin Peterson14339b62009-01-31 16:36:08 +00009972 uniobj = PyUnicode_FromObject(obj);
9973 if (uniobj == NULL) {
9974 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009975 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009976 return 0;
9977 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009978 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009979 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009980 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009981 Py_DECREF(uniobj);
9982 return 0;
9983 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009984 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009985 Py_DECREF(uniobj);
9986 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009987}
9988
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009989PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009990 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009991\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00009992Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009993done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009994
9995static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009996unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009997{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009998 Py_ssize_t marg, left;
9999 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010000 Py_UCS4 fillchar = ' ';
10001
Victor Stinnere9a29352011-10-01 02:14:59 +020010002 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010003 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010004
Victor Stinnere9a29352011-10-01 02:14:59 +020010005 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010006 return NULL;
10007
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010008 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010009 Py_INCREF(self);
10010 return (PyObject*) self;
10011 }
10012
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010013 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010014 left = marg / 2 + (marg & width & 1);
10015
Victor Stinner9310abb2011-10-05 00:59:23 +020010016 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010017}
10018
Marc-André Lemburge5034372000-08-08 08:04:29 +000010019#if 0
10020
10021/* This code should go into some future Unicode collation support
10022 module. The basic comparison should compare ordinals on a naive
Georg Brandlc6c31782009-06-08 13:41:29 +000010023 basis (this is what Java does and thus Jython too). */
Marc-André Lemburge5034372000-08-08 08:04:29 +000010024
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010025/* speedy UTF-16 code point order comparison */
10026/* gleaned from: */
10027/* http://www-4.ibm.com/software/developer/library/utf16.html?dwzone=unicode */
10028
Marc-André Lemburge12896e2000-07-07 17:51:08 +000010029static short utf16Fixup[32] =
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010030{
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010031 0, 0, 0, 0, 0, 0, 0, 0,
Tim Petersced69f82003-09-16 20:30:58 +000010032 0, 0, 0, 0, 0, 0, 0, 0,
10033 0, 0, 0, 0, 0, 0, 0, 0,
Marc-André Lemburge12896e2000-07-07 17:51:08 +000010034 0, 0, 0, 0x2000, -0x800, -0x800, -0x800, -0x800
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010035};
10036
Guido van Rossumd57fd912000-03-10 22:53:23 +000010037static int
10038unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
10039{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010040 Py_ssize_t len1, len2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010041
Guido van Rossumd57fd912000-03-10 22:53:23 +000010042 Py_UNICODE *s1 = str1->str;
10043 Py_UNICODE *s2 = str2->str;
10044
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010045 len1 = str1->_base._base.length;
10046 len2 = str2->_base._base.length;
Tim Petersced69f82003-09-16 20:30:58 +000010047
Guido van Rossumd57fd912000-03-10 22:53:23 +000010048 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +000010049 Py_UNICODE c1, c2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010050
10051 c1 = *s1++;
10052 c2 = *s2++;
Fredrik Lundh45714e92001-06-26 16:39:36 +000010053
Benjamin Peterson29060642009-01-31 22:14:21 +000010054 if (c1 > (1<<11) * 26)
10055 c1 += utf16Fixup[c1>>11];
10056 if (c2 > (1<<11) * 26)
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010057 c2 += utf16Fixup[c2>>11];
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010058 /* now c1 and c2 are in UTF-32-compatible order */
Fredrik Lundh45714e92001-06-26 16:39:36 +000010059
10060 if (c1 != c2)
10061 return (c1 < c2) ? -1 : 1;
Tim Petersced69f82003-09-16 20:30:58 +000010062
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010063 len1--; len2--;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010064 }
10065
10066 return (len1 < len2) ? -1 : (len1 != len2);
10067}
10068
Marc-André Lemburge5034372000-08-08 08:04:29 +000010069#else
10070
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010071/* This function assumes that str1 and str2 are readied by the caller. */
10072
Marc-André Lemburge5034372000-08-08 08:04:29 +000010073static int
10074unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
10075{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010076 int kind1, kind2;
10077 void *data1, *data2;
10078 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010079
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010080 kind1 = PyUnicode_KIND(str1);
10081 kind2 = PyUnicode_KIND(str2);
10082 data1 = PyUnicode_DATA(str1);
10083 data2 = PyUnicode_DATA(str2);
10084 len1 = PyUnicode_GET_LENGTH(str1);
10085 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010086
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010087 for (i = 0; i < len1 && i < len2; ++i) {
10088 Py_UCS4 c1, c2;
10089 c1 = PyUnicode_READ(kind1, data1, i);
10090 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010091
10092 if (c1 != c2)
10093 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010094 }
10095
10096 return (len1 < len2) ? -1 : (len1 != len2);
10097}
10098
10099#endif
10100
Alexander Belopolsky40018472011-02-26 01:02:56 +000010101int
10102PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010103{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010104 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10105 if (PyUnicode_READY(left) == -1 ||
10106 PyUnicode_READY(right) == -1)
10107 return -1;
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010108 return unicode_compare((PyUnicodeObject *)left,
10109 (PyUnicodeObject *)right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010110 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010111 PyErr_Format(PyExc_TypeError,
10112 "Can't compare %.100s and %.100s",
10113 left->ob_type->tp_name,
10114 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010115 return -1;
10116}
10117
Martin v. Löwis5b222132007-06-10 09:51:05 +000010118int
10119PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10120{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010121 Py_ssize_t i;
10122 int kind;
10123 void *data;
10124 Py_UCS4 chr;
10125
Victor Stinner910337b2011-10-03 03:20:16 +020010126 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010127 if (PyUnicode_READY(uni) == -1)
10128 return -1;
10129 kind = PyUnicode_KIND(uni);
10130 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010131 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010132 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10133 if (chr != str[i])
10134 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010135 /* This check keeps Python strings that end in '\0' from comparing equal
10136 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010137 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010138 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010139 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010140 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010141 return 0;
10142}
10143
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010144
Benjamin Peterson29060642009-01-31 22:14:21 +000010145#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010146 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010147
Alexander Belopolsky40018472011-02-26 01:02:56 +000010148PyObject *
10149PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010150{
10151 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010152
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010153 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10154 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010155 if (PyUnicode_READY(left) == -1 ||
10156 PyUnicode_READY(right) == -1)
10157 return NULL;
10158 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10159 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010160 if (op == Py_EQ) {
10161 Py_INCREF(Py_False);
10162 return Py_False;
10163 }
10164 if (op == Py_NE) {
10165 Py_INCREF(Py_True);
10166 return Py_True;
10167 }
10168 }
10169 if (left == right)
10170 result = 0;
10171 else
10172 result = unicode_compare((PyUnicodeObject *)left,
10173 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010174
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010175 /* Convert the return value to a Boolean */
10176 switch (op) {
10177 case Py_EQ:
10178 v = TEST_COND(result == 0);
10179 break;
10180 case Py_NE:
10181 v = TEST_COND(result != 0);
10182 break;
10183 case Py_LE:
10184 v = TEST_COND(result <= 0);
10185 break;
10186 case Py_GE:
10187 v = TEST_COND(result >= 0);
10188 break;
10189 case Py_LT:
10190 v = TEST_COND(result == -1);
10191 break;
10192 case Py_GT:
10193 v = TEST_COND(result == 1);
10194 break;
10195 default:
10196 PyErr_BadArgument();
10197 return NULL;
10198 }
10199 Py_INCREF(v);
10200 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010201 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010202
Brian Curtindfc80e32011-08-10 20:28:54 -050010203 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010204}
10205
Alexander Belopolsky40018472011-02-26 01:02:56 +000010206int
10207PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010208{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010209 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010210 int kind1, kind2, kind;
10211 void *buf1, *buf2;
10212 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010213 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010214
10215 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010216 sub = PyUnicode_FromObject(element);
10217 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010218 PyErr_Format(PyExc_TypeError,
10219 "'in <string>' requires string as left operand, not %s",
10220 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010221 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010222 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010223 if (PyUnicode_READY(sub) == -1)
10224 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010225
Thomas Wouters477c8d52006-05-27 19:21:47 +000010226 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010227 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010228 Py_DECREF(sub);
10229 return -1;
10230 }
10231
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010232 kind1 = PyUnicode_KIND(str);
10233 kind2 = PyUnicode_KIND(sub);
10234 kind = kind1 > kind2 ? kind1 : kind2;
10235 buf1 = PyUnicode_DATA(str);
10236 buf2 = PyUnicode_DATA(sub);
10237 if (kind1 != kind)
10238 buf1 = _PyUnicode_AsKind((PyObject*)str, kind);
10239 if (!buf1) {
10240 Py_DECREF(sub);
10241 return -1;
10242 }
10243 if (kind2 != kind)
10244 buf2 = _PyUnicode_AsKind((PyObject*)sub, kind);
10245 if (!buf2) {
10246 Py_DECREF(sub);
10247 if (kind1 != kind) PyMem_Free(buf1);
10248 return -1;
10249 }
10250 len1 = PyUnicode_GET_LENGTH(str);
10251 len2 = PyUnicode_GET_LENGTH(sub);
10252
10253 switch(kind) {
10254 case PyUnicode_1BYTE_KIND:
10255 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10256 break;
10257 case PyUnicode_2BYTE_KIND:
10258 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10259 break;
10260 case PyUnicode_4BYTE_KIND:
10261 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10262 break;
10263 default:
10264 result = -1;
10265 assert(0);
10266 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010267
10268 Py_DECREF(str);
10269 Py_DECREF(sub);
10270
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010271 if (kind1 != kind)
10272 PyMem_Free(buf1);
10273 if (kind2 != kind)
10274 PyMem_Free(buf2);
10275
Guido van Rossum403d68b2000-03-13 15:55:09 +000010276 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010277}
10278
Guido van Rossumd57fd912000-03-10 22:53:23 +000010279/* Concat to string or Unicode object giving a new Unicode object. */
10280
Alexander Belopolsky40018472011-02-26 01:02:56 +000010281PyObject *
10282PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010283{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010284 PyObject *u = NULL, *v = NULL, *w;
10285 Py_UCS4 maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010286
10287 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010288 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010289 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010290 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010291 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010292 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010293 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010294
10295 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010296 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010297 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010298 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010299 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010300 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010301 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010302 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010303 }
10304
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinnerff9e50f2011-09-28 22:17:19 +020010306 maxchar = Py_MAX(maxchar, PyUnicode_MAX_CHAR_VALUE(v));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307
Guido van Rossumd57fd912000-03-10 22:53:23 +000010308 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010309 w = PyUnicode_New(
10310 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10311 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010312 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010313 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010314 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10315 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010316 Py_DECREF(u);
10317 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010318 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010319 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010320
Benjamin Peterson29060642009-01-31 22:14:21 +000010321 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010322 Py_XDECREF(u);
10323 Py_XDECREF(v);
10324 return NULL;
10325}
10326
Victor Stinnerb0923652011-10-04 01:17:31 +020010327static void
10328unicode_append_inplace(PyObject **p_left, PyObject *right)
10329{
10330 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010331
10332 assert(PyUnicode_IS_READY(*p_left));
10333 assert(PyUnicode_IS_READY(right));
10334
10335 left_len = PyUnicode_GET_LENGTH(*p_left);
10336 right_len = PyUnicode_GET_LENGTH(right);
10337 if (left_len > PY_SSIZE_T_MAX - right_len) {
10338 PyErr_SetString(PyExc_OverflowError,
10339 "strings are too large to concat");
10340 goto error;
10341 }
10342 new_len = left_len + right_len;
10343
10344 /* Now we own the last reference to 'left', so we can resize it
10345 * in-place.
10346 */
10347 if (unicode_resize(p_left, new_len) != 0) {
10348 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10349 * deallocated so it cannot be put back into
10350 * 'variable'. The MemoryError is raised when there
10351 * is no value in 'variable', which might (very
10352 * remotely) be a cause of incompatibilities.
10353 */
10354 goto error;
10355 }
10356 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010357 copy_characters(*p_left, left_len, right, 0, right_len);
10358 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010359 return;
10360
10361error:
10362 Py_DECREF(*p_left);
10363 *p_left = NULL;
10364}
10365
Walter Dörwald1ab83302007-05-18 17:15:44 +000010366void
Victor Stinner23e56682011-10-03 03:54:37 +020010367PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010368{
Victor Stinner23e56682011-10-03 03:54:37 +020010369 PyObject *left, *res;
10370
10371 if (p_left == NULL) {
10372 if (!PyErr_Occurred())
10373 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010374 return;
10375 }
Victor Stinner23e56682011-10-03 03:54:37 +020010376 left = *p_left;
10377 if (right == NULL || !PyUnicode_Check(left)) {
10378 if (!PyErr_Occurred())
10379 PyErr_BadInternalCall();
10380 goto error;
10381 }
10382
Victor Stinnere1335c72011-10-04 20:53:03 +020010383 if (PyUnicode_READY(left))
10384 goto error;
10385 if (PyUnicode_READY(right))
10386 goto error;
10387
Victor Stinner23e56682011-10-03 03:54:37 +020010388 if (PyUnicode_CheckExact(left) && left != unicode_empty
10389 && PyUnicode_CheckExact(right) && right != unicode_empty
10390 && unicode_resizable(left)
10391 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10392 || _PyUnicode_WSTR(left) != NULL))
10393 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010394 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10395 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010396 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010397 not so different than duplicating the string. */
10398 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010399 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010400 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010401 if (p_left != NULL)
10402 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010403 return;
10404 }
10405 }
10406
10407 res = PyUnicode_Concat(left, right);
10408 if (res == NULL)
10409 goto error;
10410 Py_DECREF(left);
10411 *p_left = res;
10412 return;
10413
10414error:
10415 Py_DECREF(*p_left);
10416 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010417}
10418
10419void
10420PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10421{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010422 PyUnicode_Append(pleft, right);
10423 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010424}
10425
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010426PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010427 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010428\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010429Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010430string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010431interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010432
10433static PyObject *
10434unicode_count(PyUnicodeObject *self, PyObject *args)
10435{
10436 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010437 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010438 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010439 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010440 int kind1, kind2, kind;
10441 void *buf1, *buf2;
10442 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010443
Jesus Ceaac451502011-04-20 17:09:23 +020010444 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10445 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010446 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010447
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010448 kind1 = PyUnicode_KIND(self);
10449 kind2 = PyUnicode_KIND(substring);
10450 kind = kind1 > kind2 ? kind1 : kind2;
10451 buf1 = PyUnicode_DATA(self);
10452 buf2 = PyUnicode_DATA(substring);
10453 if (kind1 != kind)
10454 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10455 if (!buf1) {
10456 Py_DECREF(substring);
10457 return NULL;
10458 }
10459 if (kind2 != kind)
10460 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10461 if (!buf2) {
10462 Py_DECREF(substring);
10463 if (kind1 != kind) PyMem_Free(buf1);
10464 return NULL;
10465 }
10466 len1 = PyUnicode_GET_LENGTH(self);
10467 len2 = PyUnicode_GET_LENGTH(substring);
10468
10469 ADJUST_INDICES(start, end, len1);
10470 switch(kind) {
10471 case PyUnicode_1BYTE_KIND:
10472 iresult = ucs1lib_count(
10473 ((Py_UCS1*)buf1) + start, end - start,
10474 buf2, len2, PY_SSIZE_T_MAX
10475 );
10476 break;
10477 case PyUnicode_2BYTE_KIND:
10478 iresult = ucs2lib_count(
10479 ((Py_UCS2*)buf1) + start, end - start,
10480 buf2, len2, PY_SSIZE_T_MAX
10481 );
10482 break;
10483 case PyUnicode_4BYTE_KIND:
10484 iresult = ucs4lib_count(
10485 ((Py_UCS4*)buf1) + start, end - start,
10486 buf2, len2, PY_SSIZE_T_MAX
10487 );
10488 break;
10489 default:
10490 assert(0); iresult = 0;
10491 }
10492
10493 result = PyLong_FromSsize_t(iresult);
10494
10495 if (kind1 != kind)
10496 PyMem_Free(buf1);
10497 if (kind2 != kind)
10498 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010499
10500 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010501
Guido van Rossumd57fd912000-03-10 22:53:23 +000010502 return result;
10503}
10504
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010505PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010506 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010507\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010508Encode S using the codec registered for encoding. Default encoding\n\
10509is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010510handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010511a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10512'xmlcharrefreplace' as well as any other name registered with\n\
10513codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010514
10515static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +000010516unicode_encode(PyUnicodeObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010517{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010518 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010519 char *encoding = NULL;
10520 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010521
Benjamin Peterson308d6372009-09-18 21:42:35 +000010522 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10523 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010524 return NULL;
Georg Brandl3b9406b2010-12-03 07:54:09 +000010525 return PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010526}
10527
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010528PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010529 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010530\n\
10531Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010532If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010533
10534static PyObject*
10535unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
10536{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010537 Py_ssize_t i, j, line_pos, src_len, incr;
10538 Py_UCS4 ch;
10539 PyObject *u;
10540 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010541 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010542 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010543 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010544
10545 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010546 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010547
Antoine Pitrou22425222011-10-04 19:10:51 +020010548 if (PyUnicode_READY(self) == -1)
10549 return NULL;
10550
Thomas Wouters7e474022000-07-16 12:04:32 +000010551 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010552 src_len = PyUnicode_GET_LENGTH(self);
10553 i = j = line_pos = 0;
10554 kind = PyUnicode_KIND(self);
10555 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010556 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010557 for (; i < src_len; i++) {
10558 ch = PyUnicode_READ(kind, src_data, i);
10559 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010560 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010561 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010562 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010563 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010564 goto overflow;
10565 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010566 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010567 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010568 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010569 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010570 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010571 goto overflow;
10572 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010573 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010574 if (ch == '\n' || ch == '\r')
10575 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010576 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010577 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020010578 if (!found && PyUnicode_CheckExact(self)) {
10579 Py_INCREF((PyObject *) self);
10580 return (PyObject *) self;
10581 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010582
Guido van Rossumd57fd912000-03-10 22:53:23 +000010583 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010584 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010585 if (!u)
10586 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010587 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010588
Antoine Pitroue71d5742011-10-04 15:55:09 +020010589 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010590
Antoine Pitroue71d5742011-10-04 15:55:09 +020010591 for (; i < src_len; i++) {
10592 ch = PyUnicode_READ(kind, src_data, i);
10593 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010594 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010595 incr = tabsize - (line_pos % tabsize);
10596 line_pos += incr;
10597 while (incr--) {
10598 PyUnicode_WRITE(kind, dest_data, j, ' ');
10599 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010600 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010601 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010602 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010603 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010604 line_pos++;
10605 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010606 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010607 if (ch == '\n' || ch == '\r')
10608 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010609 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010610 }
10611 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020010612#ifndef DONT_MAKE_RESULT_READY
10613 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010614 Py_DECREF(u);
10615 return NULL;
10616 }
Victor Stinner17efeed2011-10-04 20:05:46 +020010617#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010618 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010619 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010620
Antoine Pitroue71d5742011-10-04 15:55:09 +020010621 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010622 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10623 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010624}
10625
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010626PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010627 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010628\n\
10629Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010630such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010631arguments start and end are interpreted as in slice notation.\n\
10632\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010633Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010634
10635static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010636unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010637{
Jesus Ceaac451502011-04-20 17:09:23 +020010638 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010639 Py_ssize_t start;
10640 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010641 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010642
Jesus Ceaac451502011-04-20 17:09:23 +020010643 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10644 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010645 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010646
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010647 if (PyUnicode_READY(self) == -1)
10648 return NULL;
10649 if (PyUnicode_READY(substring) == -1)
10650 return NULL;
10651
10652 result = any_find_slice(
Victor Stinnerc3cec782011-10-05 21:24:08 +020010653 asciilib_find_slice, ucs1lib_find_slice,
10654 ucs2lib_find_slice, ucs4lib_find_slice,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010655 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010656 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010657
10658 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010659
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010660 if (result == -2)
10661 return NULL;
10662
Christian Heimes217cfd12007-12-02 14:31:20 +000010663 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010664}
10665
10666static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010667unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010668{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010669 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
10670 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010671 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010672 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010673}
10674
Guido van Rossumc2504932007-09-18 19:42:40 +000010675/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010010676 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000010677static Py_hash_t
Neil Schemenauerf8c37d12007-09-07 20:49:04 +000010678unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010679{
Guido van Rossumc2504932007-09-18 19:42:40 +000010680 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010010681 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010682
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010683 if (_PyUnicode_HASH(self) != -1)
10684 return _PyUnicode_HASH(self);
10685 if (PyUnicode_READY(self) == -1)
10686 return -1;
10687 len = PyUnicode_GET_LENGTH(self);
10688
10689 /* The hash function as a macro, gets expanded three times below. */
10690#define HASH(P) \
10691 x = (Py_uhash_t)*P << 7; \
10692 while (--len >= 0) \
10693 x = (1000003*x) ^ (Py_uhash_t)*P++;
10694
10695 switch (PyUnicode_KIND(self)) {
10696 case PyUnicode_1BYTE_KIND: {
10697 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
10698 HASH(c);
10699 break;
10700 }
10701 case PyUnicode_2BYTE_KIND: {
10702 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
10703 HASH(s);
10704 break;
10705 }
10706 default: {
10707 Py_UCS4 *l;
10708 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
10709 "Impossible switch case in unicode_hash");
10710 l = PyUnicode_4BYTE_DATA(self);
10711 HASH(l);
10712 break;
10713 }
10714 }
10715 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
10716
Guido van Rossumc2504932007-09-18 19:42:40 +000010717 if (x == -1)
10718 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010719 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010720 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010721}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010722#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000010723
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010724PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010725 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010726\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010727Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010728
10729static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010730unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010731{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010732 Py_ssize_t result;
Jesus Ceaac451502011-04-20 17:09:23 +020010733 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010734 Py_ssize_t start;
10735 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010736
Jesus Ceaac451502011-04-20 17:09:23 +020010737 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
10738 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010739 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010740
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010741 if (PyUnicode_READY(self) == -1)
10742 return NULL;
10743 if (PyUnicode_READY(substring) == -1)
10744 return NULL;
10745
10746 result = any_find_slice(
Victor Stinnerc3cec782011-10-05 21:24:08 +020010747 asciilib_find_slice, ucs1lib_find_slice,
10748 ucs2lib_find_slice, ucs4lib_find_slice,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010749 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010750 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010751
10752 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010753
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010754 if (result == -2)
10755 return NULL;
10756
Guido van Rossumd57fd912000-03-10 22:53:23 +000010757 if (result < 0) {
10758 PyErr_SetString(PyExc_ValueError, "substring not found");
10759 return NULL;
10760 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010761
Christian Heimes217cfd12007-12-02 14:31:20 +000010762 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010763}
10764
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010765PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010766 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010767\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010768Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010769at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010770
10771static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010772unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010773{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010774 Py_ssize_t i, length;
10775 int kind;
10776 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010777 int cased;
10778
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010779 if (PyUnicode_READY(self) == -1)
10780 return NULL;
10781 length = PyUnicode_GET_LENGTH(self);
10782 kind = PyUnicode_KIND(self);
10783 data = PyUnicode_DATA(self);
10784
Guido van Rossumd57fd912000-03-10 22:53:23 +000010785 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010786 if (length == 1)
10787 return PyBool_FromLong(
10788 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010789
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010790 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010791 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010792 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010793
Guido van Rossumd57fd912000-03-10 22:53:23 +000010794 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010795 for (i = 0; i < length; i++) {
10796 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010797
Benjamin Peterson29060642009-01-31 22:14:21 +000010798 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
10799 return PyBool_FromLong(0);
10800 else if (!cased && Py_UNICODE_ISLOWER(ch))
10801 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010802 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010803 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010804}
10805
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010806PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010807 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010808\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010809Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010810at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010811
10812static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010813unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010814{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010815 Py_ssize_t i, length;
10816 int kind;
10817 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010818 int cased;
10819
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010820 if (PyUnicode_READY(self) == -1)
10821 return NULL;
10822 length = PyUnicode_GET_LENGTH(self);
10823 kind = PyUnicode_KIND(self);
10824 data = PyUnicode_DATA(self);
10825
Guido van Rossumd57fd912000-03-10 22:53:23 +000010826 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010827 if (length == 1)
10828 return PyBool_FromLong(
10829 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010830
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010831 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010832 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010833 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010834
Guido van Rossumd57fd912000-03-10 22:53:23 +000010835 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010836 for (i = 0; i < length; i++) {
10837 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010838
Benjamin Peterson29060642009-01-31 22:14:21 +000010839 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
10840 return PyBool_FromLong(0);
10841 else if (!cased && Py_UNICODE_ISUPPER(ch))
10842 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010843 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010844 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010845}
10846
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010847PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010848 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010849\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010850Return True if S is a titlecased string and there is at least one\n\
10851character in S, i.e. upper- and titlecase characters may only\n\
10852follow uncased characters and lowercase characters only cased ones.\n\
10853Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010854
10855static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010856unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010857{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010858 Py_ssize_t i, length;
10859 int kind;
10860 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010861 int cased, previous_is_cased;
10862
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010863 if (PyUnicode_READY(self) == -1)
10864 return NULL;
10865 length = PyUnicode_GET_LENGTH(self);
10866 kind = PyUnicode_KIND(self);
10867 data = PyUnicode_DATA(self);
10868
Guido van Rossumd57fd912000-03-10 22:53:23 +000010869 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010870 if (length == 1) {
10871 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10872 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
10873 (Py_UNICODE_ISUPPER(ch) != 0));
10874 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010875
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010876 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010877 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010878 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010879
Guido van Rossumd57fd912000-03-10 22:53:23 +000010880 cased = 0;
10881 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010882 for (i = 0; i < length; i++) {
10883 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010884
Benjamin Peterson29060642009-01-31 22:14:21 +000010885 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
10886 if (previous_is_cased)
10887 return PyBool_FromLong(0);
10888 previous_is_cased = 1;
10889 cased = 1;
10890 }
10891 else if (Py_UNICODE_ISLOWER(ch)) {
10892 if (!previous_is_cased)
10893 return PyBool_FromLong(0);
10894 previous_is_cased = 1;
10895 cased = 1;
10896 }
10897 else
10898 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010899 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010900 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010901}
10902
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010903PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010904 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010905\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010906Return True if all characters in S are whitespace\n\
10907and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010908
10909static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010910unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010911{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010912 Py_ssize_t i, length;
10913 int kind;
10914 void *data;
10915
10916 if (PyUnicode_READY(self) == -1)
10917 return NULL;
10918 length = PyUnicode_GET_LENGTH(self);
10919 kind = PyUnicode_KIND(self);
10920 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010921
Guido van Rossumd57fd912000-03-10 22:53:23 +000010922 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010923 if (length == 1)
10924 return PyBool_FromLong(
10925 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010926
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010927 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010928 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010929 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010930
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010931 for (i = 0; i < length; i++) {
10932 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010933 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000010934 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010935 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010936 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010937}
10938
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010939PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010940 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010941\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010942Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010943and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010944
10945static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010946unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010947{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010948 Py_ssize_t i, length;
10949 int kind;
10950 void *data;
10951
10952 if (PyUnicode_READY(self) == -1)
10953 return NULL;
10954 length = PyUnicode_GET_LENGTH(self);
10955 kind = PyUnicode_KIND(self);
10956 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010957
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010958 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010959 if (length == 1)
10960 return PyBool_FromLong(
10961 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010962
10963 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010964 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010965 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010966
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010967 for (i = 0; i < length; i++) {
10968 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010969 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010970 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010971 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010972}
10973
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010974PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010975 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010976\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010977Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010978and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010979
10980static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010981unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010982{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010983 int kind;
10984 void *data;
10985 Py_ssize_t len, i;
10986
10987 if (PyUnicode_READY(self) == -1)
10988 return NULL;
10989
10990 kind = PyUnicode_KIND(self);
10991 data = PyUnicode_DATA(self);
10992 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010993
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010994 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010995 if (len == 1) {
10996 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10997 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
10998 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010999
11000 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011001 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011002 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011003
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011004 for (i = 0; i < len; i++) {
11005 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011006 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011007 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011008 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011009 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011010}
11011
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011012PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011013 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011014\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011015Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011016False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011017
11018static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011019unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011020{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011021 Py_ssize_t i, length;
11022 int kind;
11023 void *data;
11024
11025 if (PyUnicode_READY(self) == -1)
11026 return NULL;
11027 length = PyUnicode_GET_LENGTH(self);
11028 kind = PyUnicode_KIND(self);
11029 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011030
Guido van Rossumd57fd912000-03-10 22:53:23 +000011031 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011032 if (length == 1)
11033 return PyBool_FromLong(
11034 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011035
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011036 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011037 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011038 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011039
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011040 for (i = 0; i < length; i++) {
11041 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011042 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011043 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011044 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011045}
11046
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011047PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011048 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011049\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011050Return True if all characters in S are digits\n\
11051and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011052
11053static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011054unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011055{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011056 Py_ssize_t i, length;
11057 int kind;
11058 void *data;
11059
11060 if (PyUnicode_READY(self) == -1)
11061 return NULL;
11062 length = PyUnicode_GET_LENGTH(self);
11063 kind = PyUnicode_KIND(self);
11064 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011065
Guido van Rossumd57fd912000-03-10 22:53:23 +000011066 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011067 if (length == 1) {
11068 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11069 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11070 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011071
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011072 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011073 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011074 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011075
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011076 for (i = 0; i < length; i++) {
11077 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011078 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011079 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011080 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011081}
11082
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011083PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011084 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011085\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011086Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011087False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011088
11089static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011090unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011091{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011092 Py_ssize_t i, length;
11093 int kind;
11094 void *data;
11095
11096 if (PyUnicode_READY(self) == -1)
11097 return NULL;
11098 length = PyUnicode_GET_LENGTH(self);
11099 kind = PyUnicode_KIND(self);
11100 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011101
Guido van Rossumd57fd912000-03-10 22:53:23 +000011102 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011103 if (length == 1)
11104 return PyBool_FromLong(
11105 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011106
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011107 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011108 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011109 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011110
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011111 for (i = 0; i < length; i++) {
11112 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011113 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011114 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011115 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011116}
11117
Martin v. Löwis47383402007-08-15 07:32:56 +000011118int
11119PyUnicode_IsIdentifier(PyObject *self)
11120{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011121 int kind;
11122 void *data;
11123 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011124 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011125
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011126 if (PyUnicode_READY(self) == -1) {
11127 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011128 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011129 }
11130
11131 /* Special case for empty strings */
11132 if (PyUnicode_GET_LENGTH(self) == 0)
11133 return 0;
11134 kind = PyUnicode_KIND(self);
11135 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011136
11137 /* PEP 3131 says that the first character must be in
11138 XID_Start and subsequent characters in XID_Continue,
11139 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011140 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011141 letters, digits, underscore). However, given the current
11142 definition of XID_Start and XID_Continue, it is sufficient
11143 to check just for these, except that _ must be allowed
11144 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011145 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011146 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011147 return 0;
11148
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011149 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011150 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011151 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011152 return 1;
11153}
11154
11155PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011156 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011157\n\
11158Return True if S is a valid identifier according\n\
11159to the language definition.");
11160
11161static PyObject*
11162unicode_isidentifier(PyObject *self)
11163{
11164 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11165}
11166
Georg Brandl559e5d72008-06-11 18:37:52 +000011167PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011168 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011169\n\
11170Return True if all characters in S are considered\n\
11171printable in repr() or S is empty, False otherwise.");
11172
11173static PyObject*
11174unicode_isprintable(PyObject *self)
11175{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011176 Py_ssize_t i, length;
11177 int kind;
11178 void *data;
11179
11180 if (PyUnicode_READY(self) == -1)
11181 return NULL;
11182 length = PyUnicode_GET_LENGTH(self);
11183 kind = PyUnicode_KIND(self);
11184 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011185
11186 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011187 if (length == 1)
11188 return PyBool_FromLong(
11189 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011190
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011191 for (i = 0; i < length; i++) {
11192 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011193 Py_RETURN_FALSE;
11194 }
11195 }
11196 Py_RETURN_TRUE;
11197}
11198
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011199PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011200 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011201\n\
11202Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011203iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204
11205static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011206unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011208 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011209}
11210
Martin v. Löwis18e16552006-02-15 17:27:45 +000011211static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +000011212unicode_length(PyUnicodeObject *self)
11213{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011214 if (PyUnicode_READY(self) == -1)
11215 return -1;
11216 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011217}
11218
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011219PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011220 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011221\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011222Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011223done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011224
11225static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011226unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011227{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011228 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011229 Py_UCS4 fillchar = ' ';
11230
11231 if (PyUnicode_READY(self) == -1)
11232 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011233
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011234 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011235 return NULL;
11236
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011237 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011238 Py_INCREF(self);
11239 return (PyObject*) self;
11240 }
11241
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011242 return (PyObject*) pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011243}
11244
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011245PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011246 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011247\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011248Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011249
11250static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011251unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011252{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011253 return fixup(self, fixlower);
11254}
11255
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011256#define LEFTSTRIP 0
11257#define RIGHTSTRIP 1
11258#define BOTHSTRIP 2
11259
11260/* Arrays indexed by above */
11261static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11262
11263#define STRIPNAME(i) (stripformat[i]+3)
11264
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011265/* externally visible for str.strip(unicode) */
11266PyObject *
11267_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
11268{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011269 void *data;
11270 int kind;
11271 Py_ssize_t i, j, len;
11272 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011273
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011274 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11275 return NULL;
11276
11277 kind = PyUnicode_KIND(self);
11278 data = PyUnicode_DATA(self);
11279 len = PyUnicode_GET_LENGTH(self);
11280 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11281 PyUnicode_DATA(sepobj),
11282 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011283
Benjamin Peterson14339b62009-01-31 16:36:08 +000011284 i = 0;
11285 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011286 while (i < len &&
11287 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011288 i++;
11289 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011290 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011291
Benjamin Peterson14339b62009-01-31 16:36:08 +000011292 j = len;
11293 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011294 do {
11295 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011296 } while (j >= i &&
11297 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011298 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011299 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011300
Victor Stinner12bab6d2011-10-01 01:53:49 +020011301 return PyUnicode_Substring((PyObject*)self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011302}
11303
11304PyObject*
11305PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11306{
11307 unsigned char *data;
11308 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011309 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011310
Victor Stinnerde636f32011-10-01 03:55:54 +020011311 if (PyUnicode_READY(self) == -1)
11312 return NULL;
11313
11314 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11315
Victor Stinner12bab6d2011-10-01 01:53:49 +020011316 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011317 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011318 if (PyUnicode_CheckExact(self)) {
11319 Py_INCREF(self);
11320 return self;
11321 }
11322 else
11323 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011324 }
11325
Victor Stinner12bab6d2011-10-01 01:53:49 +020011326 length = end - start;
11327 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011328 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011329
Victor Stinnerde636f32011-10-01 03:55:54 +020011330 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011331 PyErr_SetString(PyExc_IndexError, "string index out of range");
11332 return NULL;
11333 }
11334
Victor Stinnerb9275c12011-10-05 14:01:42 +020011335 if (PyUnicode_IS_ASCII(self)) {
11336 kind = PyUnicode_KIND(self);
11337 data = PyUnicode_1BYTE_DATA(self);
11338 return unicode_fromascii(data + start, length);
11339 }
11340 else {
11341 kind = PyUnicode_KIND(self);
11342 data = PyUnicode_1BYTE_DATA(self);
11343 return PyUnicode_FromKindAndData(kind,
11344 data + PyUnicode_KIND_SIZE(kind, start),
11345 length);
11346 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011347}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011348
11349static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011350do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011351{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011352 int kind;
11353 void *data;
11354 Py_ssize_t len, i, j;
11355
11356 if (PyUnicode_READY(self) == -1)
11357 return NULL;
11358
11359 kind = PyUnicode_KIND(self);
11360 data = PyUnicode_DATA(self);
11361 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011362
Benjamin Peterson14339b62009-01-31 16:36:08 +000011363 i = 0;
11364 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011365 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011366 i++;
11367 }
11368 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011369
Benjamin Peterson14339b62009-01-31 16:36:08 +000011370 j = len;
11371 if (striptype != LEFTSTRIP) {
11372 do {
11373 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011374 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011375 j++;
11376 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011377
Victor Stinner12bab6d2011-10-01 01:53:49 +020011378 return PyUnicode_Substring((PyObject*)self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011379}
11380
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011381
11382static PyObject *
11383do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
11384{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011385 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011386
Benjamin Peterson14339b62009-01-31 16:36:08 +000011387 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11388 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011389
Benjamin Peterson14339b62009-01-31 16:36:08 +000011390 if (sep != NULL && sep != Py_None) {
11391 if (PyUnicode_Check(sep))
11392 return _PyUnicode_XStrip(self, striptype, sep);
11393 else {
11394 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011395 "%s arg must be None or str",
11396 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011397 return NULL;
11398 }
11399 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011400
Benjamin Peterson14339b62009-01-31 16:36:08 +000011401 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011402}
11403
11404
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011405PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011406 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011407\n\
11408Return a copy of the string S with leading and trailing\n\
11409whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011410If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011411
11412static PyObject *
11413unicode_strip(PyUnicodeObject *self, PyObject *args)
11414{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011415 if (PyTuple_GET_SIZE(args) == 0)
11416 return do_strip(self, BOTHSTRIP); /* Common case */
11417 else
11418 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011419}
11420
11421
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011422PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011423 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011424\n\
11425Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011426If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011427
11428static PyObject *
11429unicode_lstrip(PyUnicodeObject *self, PyObject *args)
11430{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011431 if (PyTuple_GET_SIZE(args) == 0)
11432 return do_strip(self, LEFTSTRIP); /* Common case */
11433 else
11434 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011435}
11436
11437
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011438PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011439 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011440\n\
11441Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011442If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011443
11444static PyObject *
11445unicode_rstrip(PyUnicodeObject *self, PyObject *args)
11446{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011447 if (PyTuple_GET_SIZE(args) == 0)
11448 return do_strip(self, RIGHTSTRIP); /* Common case */
11449 else
11450 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011451}
11452
11453
Guido van Rossumd57fd912000-03-10 22:53:23 +000011454static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +000011455unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011456{
11457 PyUnicodeObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011458 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011459
Georg Brandl222de0f2009-04-12 12:01:50 +000011460 if (len < 1) {
11461 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011462 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011463 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011464
Tim Peters7a29bd52001-09-12 03:03:31 +000011465 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011466 /* no repeat, return original string */
11467 Py_INCREF(str);
11468 return (PyObject*) str;
11469 }
Tim Peters8f422462000-09-09 06:13:41 +000011470
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011471 if (PyUnicode_READY(str) == -1)
11472 return NULL;
11473
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011474 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011475 PyErr_SetString(PyExc_OverflowError,
11476 "repeated string is too long");
11477 return NULL;
11478 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011479 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011480
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011481 u = (PyUnicodeObject *)PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011482 if (!u)
11483 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011484 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011485
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011486 if (PyUnicode_GET_LENGTH(str) == 1) {
11487 const int kind = PyUnicode_KIND(str);
11488 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11489 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011490 if (kind == PyUnicode_1BYTE_KIND)
11491 memset(to, (unsigned char)fill_char, len);
11492 else {
11493 for (n = 0; n < len; ++n)
11494 PyUnicode_WRITE(kind, to, n, fill_char);
11495 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011496 }
11497 else {
11498 /* number of characters copied this far */
11499 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
11500 const Py_ssize_t char_size = PyUnicode_CHARACTER_SIZE(str);
11501 char *to = (char *) PyUnicode_DATA(u);
11502 Py_MEMCPY(to, PyUnicode_DATA(str),
11503 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011504 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011505 n = (done <= nchars-done) ? done : nchars-done;
11506 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011507 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011508 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011509 }
11510
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011511 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011512 return (PyObject*) u;
11513}
11514
Alexander Belopolsky40018472011-02-26 01:02:56 +000011515PyObject *
11516PyUnicode_Replace(PyObject *obj,
11517 PyObject *subobj,
11518 PyObject *replobj,
11519 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520{
11521 PyObject *self;
11522 PyObject *str1;
11523 PyObject *str2;
11524 PyObject *result;
11525
11526 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011527 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011528 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011529 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011530 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011531 Py_DECREF(self);
11532 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011533 }
11534 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011535 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011536 Py_DECREF(self);
11537 Py_DECREF(str1);
11538 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011539 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011540 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011541 Py_DECREF(self);
11542 Py_DECREF(str1);
11543 Py_DECREF(str2);
11544 return result;
11545}
11546
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011547PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011548 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011549\n\
11550Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011551old replaced by new. If the optional argument count is\n\
11552given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011553
11554static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011555unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011556{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011557 PyObject *str1;
11558 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011559 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560 PyObject *result;
11561
Martin v. Löwis18e16552006-02-15 17:27:45 +000011562 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011563 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011564 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011565 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011566 str1 = PyUnicode_FromObject(str1);
11567 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11568 return NULL;
11569 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011570 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011571 Py_DECREF(str1);
11572 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011573 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011574
11575 result = replace(self, str1, str2, maxcount);
11576
11577 Py_DECREF(str1);
11578 Py_DECREF(str2);
11579 return result;
11580}
11581
Alexander Belopolsky40018472011-02-26 01:02:56 +000011582static PyObject *
11583unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011585 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011586 Py_ssize_t isize;
11587 Py_ssize_t osize, squote, dquote, i, o;
11588 Py_UCS4 max, quote;
11589 int ikind, okind;
11590 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011591
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011592 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011593 return NULL;
11594
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011595 isize = PyUnicode_GET_LENGTH(unicode);
11596 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011597
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011598 /* Compute length of output, quote characters, and
11599 maximum character */
11600 osize = 2; /* quotes */
11601 max = 127;
11602 squote = dquote = 0;
11603 ikind = PyUnicode_KIND(unicode);
11604 for (i = 0; i < isize; i++) {
11605 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11606 switch (ch) {
11607 case '\'': squote++; osize++; break;
11608 case '"': dquote++; osize++; break;
11609 case '\\': case '\t': case '\r': case '\n':
11610 osize += 2; break;
11611 default:
11612 /* Fast-path ASCII */
11613 if (ch < ' ' || ch == 0x7f)
11614 osize += 4; /* \xHH */
11615 else if (ch < 0x7f)
11616 osize++;
11617 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11618 osize++;
11619 max = ch > max ? ch : max;
11620 }
11621 else if (ch < 0x100)
11622 osize += 4; /* \xHH */
11623 else if (ch < 0x10000)
11624 osize += 6; /* \uHHHH */
11625 else
11626 osize += 10; /* \uHHHHHHHH */
11627 }
11628 }
11629
11630 quote = '\'';
11631 if (squote) {
11632 if (dquote)
11633 /* Both squote and dquote present. Use squote,
11634 and escape them */
11635 osize += squote;
11636 else
11637 quote = '"';
11638 }
11639
11640 repr = PyUnicode_New(osize, max);
11641 if (repr == NULL)
11642 return NULL;
11643 okind = PyUnicode_KIND(repr);
11644 odata = PyUnicode_DATA(repr);
11645
11646 PyUnicode_WRITE(okind, odata, 0, quote);
11647 PyUnicode_WRITE(okind, odata, osize-1, quote);
11648
11649 for (i = 0, o = 1; i < isize; i++) {
11650 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011651
11652 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011653 if ((ch == quote) || (ch == '\\')) {
11654 PyUnicode_WRITE(okind, odata, o++, '\\');
11655 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011656 continue;
11657 }
11658
Benjamin Peterson29060642009-01-31 22:14:21 +000011659 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011660 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011661 PyUnicode_WRITE(okind, odata, o++, '\\');
11662 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011663 }
11664 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011665 PyUnicode_WRITE(okind, odata, o++, '\\');
11666 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011667 }
11668 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011669 PyUnicode_WRITE(okind, odata, o++, '\\');
11670 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011671 }
11672
11673 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011674 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011675 PyUnicode_WRITE(okind, odata, o++, '\\');
11676 PyUnicode_WRITE(okind, odata, o++, 'x');
11677 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
11678 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011679 }
11680
Georg Brandl559e5d72008-06-11 18:37:52 +000011681 /* Copy ASCII characters as-is */
11682 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011683 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011684 }
11685
Benjamin Peterson29060642009-01-31 22:14:21 +000011686 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000011687 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011688 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000011689 (categories Z* and C* except ASCII space)
11690 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011691 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011692 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011693 if (ch <= 0xff) {
11694 PyUnicode_WRITE(okind, odata, o++, '\\');
11695 PyUnicode_WRITE(okind, odata, o++, 'x');
11696 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
11697 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011698 }
11699 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011700 else if (ch >= 0x10000) {
11701 PyUnicode_WRITE(okind, odata, o++, '\\');
11702 PyUnicode_WRITE(okind, odata, o++, 'U');
11703 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 28) & 0xF]);
11704 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 24) & 0xF]);
11705 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 20) & 0xF]);
11706 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 16) & 0xF]);
11707 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
11708 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
11709 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
11710 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011711 }
11712 /* Map 16-bit characters to '\uxxxx' */
11713 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011714 PyUnicode_WRITE(okind, odata, o++, '\\');
11715 PyUnicode_WRITE(okind, odata, o++, 'u');
11716 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
11717 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
11718 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
11719 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011720 }
11721 }
11722 /* Copy characters as-is */
11723 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011724 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011725 }
11726 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000011727 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011728 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020011729 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000011730 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011731}
11732
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011733PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011734 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011735\n\
11736Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011737such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011738arguments start and end are interpreted as in slice notation.\n\
11739\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011740Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011741
11742static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011743unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011744{
Jesus Ceaac451502011-04-20 17:09:23 +020011745 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011746 Py_ssize_t start;
11747 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011748 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011749
Jesus Ceaac451502011-04-20 17:09:23 +020011750 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
11751 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000011752 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011753
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011754 if (PyUnicode_READY(self) == -1)
11755 return NULL;
11756 if (PyUnicode_READY(substring) == -1)
11757 return NULL;
11758
11759 result = any_find_slice(
Victor Stinnerc3cec782011-10-05 21:24:08 +020011760 asciilib_rfind_slice, ucs1lib_rfind_slice,
11761 ucs2lib_rfind_slice, ucs4lib_rfind_slice,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011762 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011763 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011764
11765 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011766
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011767 if (result == -2)
11768 return NULL;
11769
Christian Heimes217cfd12007-12-02 14:31:20 +000011770 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011771}
11772
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011773PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011774 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011775\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011776Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011777
11778static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011779unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011780{
Jesus Ceaac451502011-04-20 17:09:23 +020011781 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011782 Py_ssize_t start;
11783 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011784 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011785
Jesus Ceaac451502011-04-20 17:09:23 +020011786 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
11787 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000011788 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011789
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011790 if (PyUnicode_READY(self) == -1)
11791 return NULL;
11792 if (PyUnicode_READY(substring) == -1)
11793 return NULL;
11794
11795 result = any_find_slice(
Victor Stinnerc3cec782011-10-05 21:24:08 +020011796 asciilib_rfind_slice, ucs1lib_rfind_slice,
11797 ucs2lib_rfind_slice, ucs4lib_rfind_slice,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011798 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011799 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011800
11801 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011802
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011803 if (result == -2)
11804 return NULL;
11805
Guido van Rossumd57fd912000-03-10 22:53:23 +000011806 if (result < 0) {
11807 PyErr_SetString(PyExc_ValueError, "substring not found");
11808 return NULL;
11809 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011810
Christian Heimes217cfd12007-12-02 14:31:20 +000011811 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011812}
11813
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011814PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011815 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011816\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011817Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011818done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011819
11820static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011821unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011822{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011823 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011824 Py_UCS4 fillchar = ' ';
11825
Victor Stinnere9a29352011-10-01 02:14:59 +020011826 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011827 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011828
Victor Stinnere9a29352011-10-01 02:14:59 +020011829 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011830 return NULL;
11831
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011832 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011833 Py_INCREF(self);
11834 return (PyObject*) self;
11835 }
11836
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011837 return (PyObject*) pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011838}
11839
Alexander Belopolsky40018472011-02-26 01:02:56 +000011840PyObject *
11841PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011842{
11843 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000011844
Guido van Rossumd57fd912000-03-10 22:53:23 +000011845 s = PyUnicode_FromObject(s);
11846 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000011847 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000011848 if (sep != NULL) {
11849 sep = PyUnicode_FromObject(sep);
11850 if (sep == NULL) {
11851 Py_DECREF(s);
11852 return NULL;
11853 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011854 }
11855
Victor Stinner9310abb2011-10-05 00:59:23 +020011856 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011857
11858 Py_DECREF(s);
11859 Py_XDECREF(sep);
11860 return result;
11861}
11862
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011863PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011864 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011865\n\
11866Return a list of the words in S, using sep as the\n\
11867delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000011868splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000011869whitespace string is a separator and empty strings are\n\
11870removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011871
11872static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011873unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011874{
11875 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011876 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011877
Martin v. Löwis18e16552006-02-15 17:27:45 +000011878 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011879 return NULL;
11880
11881 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000011882 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011883 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020011884 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011885 else
Benjamin Peterson29060642009-01-31 22:14:21 +000011886 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011887}
11888
Thomas Wouters477c8d52006-05-27 19:21:47 +000011889PyObject *
11890PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
11891{
11892 PyObject* str_obj;
11893 PyObject* sep_obj;
11894 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011895 int kind1, kind2, kind;
11896 void *buf1 = NULL, *buf2 = NULL;
11897 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011898
11899 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020011900 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011901 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011902 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011903 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000011904 Py_DECREF(str_obj);
11905 return NULL;
11906 }
11907
Victor Stinner14f8f022011-10-05 20:58:25 +020011908 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011909 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020011910 kind = Py_MAX(kind1, kind2);
11911 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011912 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020011913 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011914 if (!buf1)
11915 goto onError;
11916 buf2 = PyUnicode_DATA(sep_obj);
11917 if (kind2 != kind)
11918 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11919 if (!buf2)
11920 goto onError;
11921 len1 = PyUnicode_GET_LENGTH(str_obj);
11922 len2 = PyUnicode_GET_LENGTH(sep_obj);
11923
Victor Stinner14f8f022011-10-05 20:58:25 +020011924 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011925 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020011926 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
11927 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11928 else
11929 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011930 break;
11931 case PyUnicode_2BYTE_KIND:
11932 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11933 break;
11934 case PyUnicode_4BYTE_KIND:
11935 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11936 break;
11937 default:
11938 assert(0);
11939 out = 0;
11940 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011941
11942 Py_DECREF(sep_obj);
11943 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011944 if (kind1 != kind)
11945 PyMem_Free(buf1);
11946 if (kind2 != kind)
11947 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011948
11949 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011950 onError:
11951 Py_DECREF(sep_obj);
11952 Py_DECREF(str_obj);
11953 if (kind1 != kind && buf1)
11954 PyMem_Free(buf1);
11955 if (kind2 != kind && buf2)
11956 PyMem_Free(buf2);
11957 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011958}
11959
11960
11961PyObject *
11962PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
11963{
11964 PyObject* str_obj;
11965 PyObject* sep_obj;
11966 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011967 int kind1, kind2, kind;
11968 void *buf1 = NULL, *buf2 = NULL;
11969 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011970
11971 str_obj = PyUnicode_FromObject(str_in);
11972 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000011973 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011974 sep_obj = PyUnicode_FromObject(sep_in);
11975 if (!sep_obj) {
11976 Py_DECREF(str_obj);
11977 return NULL;
11978 }
11979
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011980 kind1 = PyUnicode_KIND(str_in);
11981 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020011982 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011983 buf1 = PyUnicode_DATA(str_in);
11984 if (kind1 != kind)
11985 buf1 = _PyUnicode_AsKind(str_in, kind);
11986 if (!buf1)
11987 goto onError;
11988 buf2 = PyUnicode_DATA(sep_obj);
11989 if (kind2 != kind)
11990 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11991 if (!buf2)
11992 goto onError;
11993 len1 = PyUnicode_GET_LENGTH(str_obj);
11994 len2 = PyUnicode_GET_LENGTH(sep_obj);
11995
11996 switch(PyUnicode_KIND(str_in)) {
11997 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020011998 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
11999 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12000 else
12001 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012002 break;
12003 case PyUnicode_2BYTE_KIND:
12004 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12005 break;
12006 case PyUnicode_4BYTE_KIND:
12007 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12008 break;
12009 default:
12010 assert(0);
12011 out = 0;
12012 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012013
12014 Py_DECREF(sep_obj);
12015 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012016 if (kind1 != kind)
12017 PyMem_Free(buf1);
12018 if (kind2 != kind)
12019 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012020
12021 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012022 onError:
12023 Py_DECREF(sep_obj);
12024 Py_DECREF(str_obj);
12025 if (kind1 != kind && buf1)
12026 PyMem_Free(buf1);
12027 if (kind2 != kind && buf2)
12028 PyMem_Free(buf2);
12029 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012030}
12031
12032PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012033 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012034\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012035Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012036the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012037found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012038
12039static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012040unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012041{
Victor Stinner9310abb2011-10-05 00:59:23 +020012042 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012043}
12044
12045PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012046 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012047\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012048Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012049the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012050separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012051
12052static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012053unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012054{
Victor Stinner9310abb2011-10-05 00:59:23 +020012055 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012056}
12057
Alexander Belopolsky40018472011-02-26 01:02:56 +000012058PyObject *
12059PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012060{
12061 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012062
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012063 s = PyUnicode_FromObject(s);
12064 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012065 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012066 if (sep != NULL) {
12067 sep = PyUnicode_FromObject(sep);
12068 if (sep == NULL) {
12069 Py_DECREF(s);
12070 return NULL;
12071 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012072 }
12073
Victor Stinner9310abb2011-10-05 00:59:23 +020012074 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012075
12076 Py_DECREF(s);
12077 Py_XDECREF(sep);
12078 return result;
12079}
12080
12081PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012082 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012083\n\
12084Return a list of the words in S, using sep as the\n\
12085delimiter string, starting at the end of the string and\n\
12086working to the front. If maxsplit is given, at most maxsplit\n\
12087splits are done. If sep is not specified, any whitespace string\n\
12088is a separator.");
12089
12090static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012091unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012092{
12093 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012094 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012095
Martin v. Löwis18e16552006-02-15 17:27:45 +000012096 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012097 return NULL;
12098
12099 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012100 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012101 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012102 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012103 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012104 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012105}
12106
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012107PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012108 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012109\n\
12110Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012111Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012112is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012113
12114static PyObject*
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012115unicode_splitlines(PyUnicodeObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012116{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012117 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012118 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012119
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012120 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12121 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012122 return NULL;
12123
Guido van Rossum86662912000-04-11 15:38:46 +000012124 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012125}
12126
12127static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012128PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012129{
Walter Dörwald346737f2007-05-31 10:44:43 +000012130 if (PyUnicode_CheckExact(self)) {
12131 Py_INCREF(self);
12132 return self;
12133 } else
12134 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012135 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012136}
12137
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012138PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012139 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012140\n\
12141Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012142and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012143
12144static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012145unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012146{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012147 return fixup(self, fixswapcase);
12148}
12149
Georg Brandlceee0772007-11-27 23:48:05 +000012150PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012151 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012152\n\
12153Return a translation table usable for str.translate().\n\
12154If there is only one argument, it must be a dictionary mapping Unicode\n\
12155ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012156Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012157If there are two arguments, they must be strings of equal length, and\n\
12158in the resulting dictionary, each character in x will be mapped to the\n\
12159character at the same position in y. If there is a third argument, it\n\
12160must be a string, whose characters will be mapped to None in the result.");
12161
12162static PyObject*
12163unicode_maketrans(PyUnicodeObject *null, PyObject *args)
12164{
12165 PyObject *x, *y = NULL, *z = NULL;
12166 PyObject *new = NULL, *key, *value;
12167 Py_ssize_t i = 0;
12168 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012169
Georg Brandlceee0772007-11-27 23:48:05 +000012170 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12171 return NULL;
12172 new = PyDict_New();
12173 if (!new)
12174 return NULL;
12175 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012176 int x_kind, y_kind, z_kind;
12177 void *x_data, *y_data, *z_data;
12178
Georg Brandlceee0772007-11-27 23:48:05 +000012179 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012180 if (!PyUnicode_Check(x)) {
12181 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12182 "be a string if there is a second argument");
12183 goto err;
12184 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012185 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012186 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12187 "arguments must have equal length");
12188 goto err;
12189 }
12190 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012191 x_kind = PyUnicode_KIND(x);
12192 y_kind = PyUnicode_KIND(y);
12193 x_data = PyUnicode_DATA(x);
12194 y_data = PyUnicode_DATA(y);
12195 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12196 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12197 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012198 if (!key || !value)
12199 goto err;
12200 res = PyDict_SetItem(new, key, value);
12201 Py_DECREF(key);
12202 Py_DECREF(value);
12203 if (res < 0)
12204 goto err;
12205 }
12206 /* create entries for deleting chars in z */
12207 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012208 z_kind = PyUnicode_KIND(z);
12209 z_data = PyUnicode_DATA(z);
Georg Brandlceee0772007-11-27 23:48:05 +000012210 for (i = 0; i < PyUnicode_GET_SIZE(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012211 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012212 if (!key)
12213 goto err;
12214 res = PyDict_SetItem(new, key, Py_None);
12215 Py_DECREF(key);
12216 if (res < 0)
12217 goto err;
12218 }
12219 }
12220 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012221 int kind;
12222 void *data;
12223
Georg Brandlceee0772007-11-27 23:48:05 +000012224 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012225 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012226 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12227 "to maketrans it must be a dict");
12228 goto err;
12229 }
12230 /* copy entries into the new dict, converting string keys to int keys */
12231 while (PyDict_Next(x, &i, &key, &value)) {
12232 if (PyUnicode_Check(key)) {
12233 /* convert string keys to integer keys */
12234 PyObject *newkey;
12235 if (PyUnicode_GET_SIZE(key) != 1) {
12236 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12237 "table must be of length 1");
12238 goto err;
12239 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012240 kind = PyUnicode_KIND(key);
12241 data = PyUnicode_DATA(key);
12242 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012243 if (!newkey)
12244 goto err;
12245 res = PyDict_SetItem(new, newkey, value);
12246 Py_DECREF(newkey);
12247 if (res < 0)
12248 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012249 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012250 /* just keep integer keys */
12251 if (PyDict_SetItem(new, key, value) < 0)
12252 goto err;
12253 } else {
12254 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12255 "be strings or integers");
12256 goto err;
12257 }
12258 }
12259 }
12260 return new;
12261 err:
12262 Py_DECREF(new);
12263 return NULL;
12264}
12265
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012266PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012267 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012268\n\
12269Return a copy of the string S, where all characters have been mapped\n\
12270through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012271Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012272Unmapped characters are left untouched. Characters mapped to None\n\
12273are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012274
12275static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012276unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012277{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012278 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012279}
12280
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012281PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012282 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012283\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012284Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012285
12286static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012287unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012288{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012289 return fixup(self, fixupper);
12290}
12291
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012292PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012293 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012294\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012295Pad a numeric string S with zeros on the left, to fill a field\n\
12296of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012297
12298static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012299unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012300{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012301 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012302 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012303 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012304 int kind;
12305 void *data;
12306 Py_UCS4 chr;
12307
12308 if (PyUnicode_READY(self) == -1)
12309 return NULL;
12310
Martin v. Löwis18e16552006-02-15 17:27:45 +000012311 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012312 return NULL;
12313
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012314 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012315 if (PyUnicode_CheckExact(self)) {
12316 Py_INCREF(self);
12317 return (PyObject*) self;
12318 }
12319 else
Victor Stinner2219e0a2011-10-01 01:16:59 +020012320 return PyUnicode_Copy((PyObject*)self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012321 }
12322
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012323 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012324
12325 u = pad(self, fill, 0, '0');
12326
Walter Dörwald068325e2002-04-15 13:36:47 +000012327 if (u == NULL)
12328 return NULL;
12329
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012330 kind = PyUnicode_KIND(u);
12331 data = PyUnicode_DATA(u);
12332 chr = PyUnicode_READ(kind, data, fill);
12333
12334 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012335 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012336 PyUnicode_WRITE(kind, data, 0, chr);
12337 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012338 }
12339
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012340 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012341 return (PyObject*) u;
12342}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012343
12344#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012345static PyObject *
12346unicode__decimal2ascii(PyObject *self)
12347{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012348 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012349}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012350#endif
12351
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012352PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012353 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012354\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012355Return True if S starts with the specified prefix, False otherwise.\n\
12356With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012357With optional end, stop comparing S at that position.\n\
12358prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012359
12360static PyObject *
12361unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012362 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012363{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012364 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012365 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012366 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012367 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012368 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012369
Jesus Ceaac451502011-04-20 17:09:23 +020012370 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012371 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012372 if (PyTuple_Check(subobj)) {
12373 Py_ssize_t i;
12374 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
12375 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012376 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012377 if (substring == NULL)
12378 return NULL;
12379 result = tailmatch(self, substring, start, end, -1);
12380 Py_DECREF(substring);
12381 if (result) {
12382 Py_RETURN_TRUE;
12383 }
12384 }
12385 /* nothing matched */
12386 Py_RETURN_FALSE;
12387 }
12388 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012389 if (substring == NULL) {
12390 if (PyErr_ExceptionMatches(PyExc_TypeError))
12391 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12392 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012393 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012394 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012395 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012396 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012397 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012398}
12399
12400
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012401PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012402 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012403\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012404Return True if S ends with the specified suffix, False otherwise.\n\
12405With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012406With optional end, stop comparing S at that position.\n\
12407suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012408
12409static PyObject *
12410unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012411 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012412{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012413 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012414 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012415 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012416 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012417 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012418
Jesus Ceaac451502011-04-20 17:09:23 +020012419 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012420 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012421 if (PyTuple_Check(subobj)) {
12422 Py_ssize_t i;
12423 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
12424 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012425 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012426 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012427 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012428 result = tailmatch(self, substring, start, end, +1);
12429 Py_DECREF(substring);
12430 if (result) {
12431 Py_RETURN_TRUE;
12432 }
12433 }
12434 Py_RETURN_FALSE;
12435 }
12436 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012437 if (substring == NULL) {
12438 if (PyErr_ExceptionMatches(PyExc_TypeError))
12439 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12440 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012441 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012442 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012443 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012444 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012445 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012446}
12447
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012448#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012449
12450PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012451 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012452\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012453Return a formatted version of S, using substitutions from args and kwargs.\n\
12454The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012455
Eric Smith27bbca62010-11-04 17:06:58 +000012456PyDoc_STRVAR(format_map__doc__,
12457 "S.format_map(mapping) -> str\n\
12458\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012459Return a formatted version of S, using substitutions from mapping.\n\
12460The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012461
Eric Smith4a7d76d2008-05-30 18:10:19 +000012462static PyObject *
12463unicode__format__(PyObject* self, PyObject* args)
12464{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012465 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012466
12467 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12468 return NULL;
12469
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012470 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012471 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012472 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012473}
12474
Eric Smith8c663262007-08-25 02:26:07 +000012475PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012476 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012477\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012478Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012479
12480static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012481unicode__sizeof__(PyUnicodeObject *v)
12482{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012483 Py_ssize_t size;
12484
12485 /* If it's a compact object, account for base structure +
12486 character data. */
12487 if (PyUnicode_IS_COMPACT_ASCII(v))
12488 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12489 else if (PyUnicode_IS_COMPACT(v))
12490 size = sizeof(PyCompactUnicodeObject) +
12491 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_CHARACTER_SIZE(v);
12492 else {
12493 /* If it is a two-block object, account for base object, and
12494 for character block if present. */
12495 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012496 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012497 size += (PyUnicode_GET_LENGTH(v) + 1) *
12498 PyUnicode_CHARACTER_SIZE(v);
12499 }
12500 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012501 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012502 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012503 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012504 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012505 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012506
12507 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012508}
12509
12510PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012511 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012512
12513static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012514unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012515{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012516 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012517 if (!copy)
12518 return NULL;
12519 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012520}
12521
Guido van Rossumd57fd912000-03-10 22:53:23 +000012522static PyMethodDef unicode_methods[] = {
12523
12524 /* Order is according to common usage: often used methods should
12525 appear first, since lookup is done sequentially. */
12526
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012527 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012528 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12529 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012530 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012531 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12532 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12533 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12534 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12535 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12536 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12537 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012538 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012539 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12540 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12541 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012542 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012543 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12544 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12545 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012546 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012547 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012548 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012549 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012550 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12551 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12552 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12553 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12554 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12555 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12556 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12557 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12558 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12559 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12560 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12561 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12562 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12563 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012564 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012565 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012566 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012567 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012568 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012569 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012570 {"maketrans", (PyCFunction) unicode_maketrans,
12571 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012572 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012573#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012574 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012575#endif
12576
12577#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012578 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012579 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012580#endif
12581
Benjamin Peterson14339b62009-01-31 16:36:08 +000012582 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012583 {NULL, NULL}
12584};
12585
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012586static PyObject *
12587unicode_mod(PyObject *v, PyObject *w)
12588{
Brian Curtindfc80e32011-08-10 20:28:54 -050012589 if (!PyUnicode_Check(v))
12590 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012591 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012592}
12593
12594static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012595 0, /*nb_add*/
12596 0, /*nb_subtract*/
12597 0, /*nb_multiply*/
12598 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012599};
12600
Guido van Rossumd57fd912000-03-10 22:53:23 +000012601static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012602 (lenfunc) unicode_length, /* sq_length */
12603 PyUnicode_Concat, /* sq_concat */
12604 (ssizeargfunc) unicode_repeat, /* sq_repeat */
12605 (ssizeargfunc) unicode_getitem, /* sq_item */
12606 0, /* sq_slice */
12607 0, /* sq_ass_item */
12608 0, /* sq_ass_slice */
12609 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012610};
12611
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012612static PyObject*
12613unicode_subscript(PyUnicodeObject* self, PyObject* item)
12614{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012615 if (PyUnicode_READY(self) == -1)
12616 return NULL;
12617
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000012618 if (PyIndex_Check(item)) {
12619 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012620 if (i == -1 && PyErr_Occurred())
12621 return NULL;
12622 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012623 i += PyUnicode_GET_LENGTH(self);
Victor Stinner2fe5ced2011-10-02 00:25:40 +020012624 return unicode_getitem((PyObject*)self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012625 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000012626 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012627 PyObject *result;
12628 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012629 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012630 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012631
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012632 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000012633 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012634 return NULL;
12635 }
12636
12637 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012638 return PyUnicode_New(0, 0);
12639 } else if (start == 0 && step == 1 &&
12640 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000012641 PyUnicode_CheckExact(self)) {
12642 Py_INCREF(self);
12643 return (PyObject *)self;
12644 } else if (step == 1) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012645 return PyUnicode_Substring((PyObject*)self,
12646 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012647 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012648 /* General case */
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012649 max_char = 0;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012650 src_kind = PyUnicode_KIND(self);
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012651 kind_limit = kind_maxchar_limit(src_kind);
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012652 src_data = PyUnicode_DATA(self);
12653 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
12654 ch = PyUnicode_READ(src_kind, src_data, cur);
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012655 if (ch > max_char) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012656 max_char = ch;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012657 if (max_char >= kind_limit)
12658 break;
12659 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012660 }
12661 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012662 if (result == NULL)
12663 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012664 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012665 dest_data = PyUnicode_DATA(result);
12666
12667 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012668 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
12669 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012670 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012671 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012672 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012673 } else {
12674 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
12675 return NULL;
12676 }
12677}
12678
12679static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012680 (lenfunc)unicode_length, /* mp_length */
12681 (binaryfunc)unicode_subscript, /* mp_subscript */
12682 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012683};
12684
Guido van Rossumd57fd912000-03-10 22:53:23 +000012685
Guido van Rossumd57fd912000-03-10 22:53:23 +000012686/* Helpers for PyUnicode_Format() */
12687
12688static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000012689getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012690{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012691 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012692 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012693 (*p_argidx)++;
12694 if (arglen < 0)
12695 return args;
12696 else
12697 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012698 }
12699 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012700 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012701 return NULL;
12702}
12703
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012704/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012705
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012706static PyObject *
12707formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012708{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012709 char *p;
12710 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012711 double x;
Tim Petersced69f82003-09-16 20:30:58 +000012712
Guido van Rossumd57fd912000-03-10 22:53:23 +000012713 x = PyFloat_AsDouble(v);
12714 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012715 return NULL;
12716
Guido van Rossumd57fd912000-03-10 22:53:23 +000012717 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012718 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000012719
Eric Smith0923d1d2009-04-16 20:16:10 +000012720 p = PyOS_double_to_string(x, type, prec,
12721 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012722 if (p == NULL)
12723 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012724 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000012725 PyMem_Free(p);
12726 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012727}
12728
Tim Peters38fd5b62000-09-21 05:43:11 +000012729static PyObject*
12730formatlong(PyObject *val, int flags, int prec, int type)
12731{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012732 char *buf;
12733 int len;
12734 PyObject *str; /* temporary string object. */
12735 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000012736
Benjamin Peterson14339b62009-01-31 16:36:08 +000012737 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
12738 if (!str)
12739 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012740 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012741 Py_DECREF(str);
12742 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000012743}
12744
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012745static Py_UCS4
12746formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012747{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000012748 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012749 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012750 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012751 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000012752 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012753 goto onError;
12754 }
12755 else {
12756 /* Integer input truncated to a character */
12757 long x;
12758 x = PyLong_AsLong(v);
12759 if (x == -1 && PyErr_Occurred())
12760 goto onError;
12761
12762 if (x < 0 || x > 0x10ffff) {
12763 PyErr_SetString(PyExc_OverflowError,
12764 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012765 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000012766 }
12767
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012768 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012769 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000012770
Benjamin Peterson29060642009-01-31 22:14:21 +000012771 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012772 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012773 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012774 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012775}
12776
Antoine Pitrou978b9d22011-10-07 12:35:48 +020012777static int
12778repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
12779{
12780 int r;
12781 assert(count > 0);
12782 assert(PyUnicode_Check(obj));
12783 if (count > 5) {
12784 PyObject *repeated = unicode_repeat((PyUnicodeObject *) obj, count);
12785 if (repeated == NULL)
12786 return -1;
12787 r = _PyAccu_Accumulate(acc, repeated);
12788 Py_DECREF(repeated);
12789 return r;
12790 }
12791 else {
12792 do {
12793 if (_PyAccu_Accumulate(acc, obj))
12794 return -1;
12795 } while (--count);
12796 return 0;
12797 }
12798}
12799
Alexander Belopolsky40018472011-02-26 01:02:56 +000012800PyObject *
12801PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012802{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012803 void *fmt;
12804 int fmtkind;
12805 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012806 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012807 int r;
12808 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012809 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012810 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012811 PyObject *temp = NULL;
12812 PyObject *second = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012813 PyUnicodeObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012814 _PyAccu acc;
12815 static PyObject *plus, *minus, *blank, *zero, *percent;
12816
12817 if (!plus && !(plus = get_latin1_char('+')))
12818 return NULL;
12819 if (!minus && !(minus = get_latin1_char('-')))
12820 return NULL;
12821 if (!blank && !(blank = get_latin1_char(' ')))
12822 return NULL;
12823 if (!zero && !(zero = get_latin1_char('0')))
12824 return NULL;
12825 if (!percent && !(percent = get_latin1_char('%')))
12826 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000012827
Guido van Rossumd57fd912000-03-10 22:53:23 +000012828 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012829 PyErr_BadInternalCall();
12830 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012831 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012832 uformat = (PyUnicodeObject*)PyUnicode_FromObject(format);
12833 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012834 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012835 if (_PyAccu_Init(&acc))
12836 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012837 fmt = PyUnicode_DATA(uformat);
12838 fmtkind = PyUnicode_KIND(uformat);
12839 fmtcnt = PyUnicode_GET_LENGTH(uformat);
12840 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012841
Guido van Rossumd57fd912000-03-10 22:53:23 +000012842 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012843 arglen = PyTuple_Size(args);
12844 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012845 }
12846 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012847 arglen = -1;
12848 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012849 }
Christian Heimes90aa7642007-12-19 02:45:37 +000012850 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000012851 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000012852 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012853
12854 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012855 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012856 PyObject *nonfmt;
12857 Py_ssize_t nonfmtpos;
12858 nonfmtpos = fmtpos++;
12859 while (fmtcnt >= 0 &&
12860 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
12861 fmtpos++;
12862 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012863 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012864 nonfmt = PyUnicode_Substring((PyObject *) uformat, nonfmtpos, fmtpos);
12865 if (nonfmt == NULL)
12866 goto onError;
12867 r = _PyAccu_Accumulate(&acc, nonfmt);
12868 Py_DECREF(nonfmt);
12869 if (r)
12870 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012871 }
12872 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012873 /* Got a format specifier */
12874 int flags = 0;
12875 Py_ssize_t width = -1;
12876 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012877 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012878 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000012879 int isnumok;
12880 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012881 void *pbuf = NULL;
12882 Py_ssize_t pindex, len;
12883 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012884
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012885 fmtpos++;
12886 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
12887 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000012888 Py_ssize_t keylen;
12889 PyObject *key;
12890 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000012891
Benjamin Peterson29060642009-01-31 22:14:21 +000012892 if (dict == NULL) {
12893 PyErr_SetString(PyExc_TypeError,
12894 "format requires a mapping");
12895 goto onError;
12896 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012897 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000012898 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012899 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000012900 /* Skip over balanced parentheses */
12901 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012902 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000012903 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012904 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000012905 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012906 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000012907 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012908 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000012909 if (fmtcnt < 0 || pcount > 0) {
12910 PyErr_SetString(PyExc_ValueError,
12911 "incomplete format key");
12912 goto onError;
12913 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020012914 key = PyUnicode_Substring((PyObject*)uformat,
12915 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000012916 if (key == NULL)
12917 goto onError;
12918 if (args_owned) {
12919 Py_DECREF(args);
12920 args_owned = 0;
12921 }
12922 args = PyObject_GetItem(dict, key);
12923 Py_DECREF(key);
12924 if (args == NULL) {
12925 goto onError;
12926 }
12927 args_owned = 1;
12928 arglen = -1;
12929 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012930 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012931 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012932 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012933 case '-': flags |= F_LJUST; continue;
12934 case '+': flags |= F_SIGN; continue;
12935 case ' ': flags |= F_BLANK; continue;
12936 case '#': flags |= F_ALT; continue;
12937 case '0': flags |= F_ZERO; continue;
12938 }
12939 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012940 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012941 if (c == '*') {
12942 v = getnextarg(args, arglen, &argidx);
12943 if (v == NULL)
12944 goto onError;
12945 if (!PyLong_Check(v)) {
12946 PyErr_SetString(PyExc_TypeError,
12947 "* wants int");
12948 goto onError;
12949 }
12950 width = PyLong_AsLong(v);
12951 if (width == -1 && PyErr_Occurred())
12952 goto onError;
12953 if (width < 0) {
12954 flags |= F_LJUST;
12955 width = -width;
12956 }
12957 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012958 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012959 }
12960 else if (c >= '0' && c <= '9') {
12961 width = c - '0';
12962 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012963 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012964 if (c < '0' || c > '9')
12965 break;
12966 if ((width*10) / 10 != width) {
12967 PyErr_SetString(PyExc_ValueError,
12968 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000012969 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000012970 }
12971 width = width*10 + (c - '0');
12972 }
12973 }
12974 if (c == '.') {
12975 prec = 0;
12976 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012977 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012978 if (c == '*') {
12979 v = getnextarg(args, arglen, &argidx);
12980 if (v == NULL)
12981 goto onError;
12982 if (!PyLong_Check(v)) {
12983 PyErr_SetString(PyExc_TypeError,
12984 "* wants int");
12985 goto onError;
12986 }
12987 prec = PyLong_AsLong(v);
12988 if (prec == -1 && PyErr_Occurred())
12989 goto onError;
12990 if (prec < 0)
12991 prec = 0;
12992 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012993 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012994 }
12995 else if (c >= '0' && c <= '9') {
12996 prec = c - '0';
12997 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012998 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012999 if (c < '0' || c > '9')
13000 break;
13001 if ((prec*10) / 10 != prec) {
13002 PyErr_SetString(PyExc_ValueError,
13003 "prec too big");
13004 goto onError;
13005 }
13006 prec = prec*10 + (c - '0');
13007 }
13008 }
13009 } /* prec */
13010 if (fmtcnt >= 0) {
13011 if (c == 'h' || c == 'l' || c == 'L') {
13012 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013013 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013014 }
13015 }
13016 if (fmtcnt < 0) {
13017 PyErr_SetString(PyExc_ValueError,
13018 "incomplete format");
13019 goto onError;
13020 }
13021 if (c != '%') {
13022 v = getnextarg(args, arglen, &argidx);
13023 if (v == NULL)
13024 goto onError;
13025 }
13026 sign = 0;
13027 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013028 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013029 switch (c) {
13030
13031 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013032 _PyAccu_Accumulate(&acc, percent);
13033 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013034
13035 case 's':
13036 case 'r':
13037 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013038 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013039 temp = v;
13040 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013041 }
13042 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013043 if (c == 's')
13044 temp = PyObject_Str(v);
13045 else if (c == 'r')
13046 temp = PyObject_Repr(v);
13047 else
13048 temp = PyObject_ASCII(v);
13049 if (temp == NULL)
13050 goto onError;
13051 if (PyUnicode_Check(temp))
13052 /* nothing to do */;
13053 else {
13054 Py_DECREF(temp);
13055 PyErr_SetString(PyExc_TypeError,
13056 "%s argument has non-string str()");
13057 goto onError;
13058 }
13059 }
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 if (prec >= 0 && len > prec)
13068 len = prec;
13069 break;
13070
13071 case 'i':
13072 case 'd':
13073 case 'u':
13074 case 'o':
13075 case 'x':
13076 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013077 isnumok = 0;
13078 if (PyNumber_Check(v)) {
13079 PyObject *iobj=NULL;
13080
13081 if (PyLong_Check(v)) {
13082 iobj = v;
13083 Py_INCREF(iobj);
13084 }
13085 else {
13086 iobj = PyNumber_Long(v);
13087 }
13088 if (iobj!=NULL) {
13089 if (PyLong_Check(iobj)) {
13090 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013091 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013092 Py_DECREF(iobj);
13093 if (!temp)
13094 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013095 if (PyUnicode_READY(temp) == -1) {
13096 Py_CLEAR(temp);
13097 goto onError;
13098 }
13099 pbuf = PyUnicode_DATA(temp);
13100 kind = PyUnicode_KIND(temp);
13101 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013102 sign = 1;
13103 }
13104 else {
13105 Py_DECREF(iobj);
13106 }
13107 }
13108 }
13109 if (!isnumok) {
13110 PyErr_Format(PyExc_TypeError,
13111 "%%%c format: a number is required, "
13112 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13113 goto onError;
13114 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013115 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013116 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013117 fillobj = zero;
13118 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013119 break;
13120
13121 case 'e':
13122 case 'E':
13123 case 'f':
13124 case 'F':
13125 case 'g':
13126 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013127 temp = formatfloat(v, flags, prec, c);
13128 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013129 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013130 if (PyUnicode_READY(temp) == -1) {
13131 Py_CLEAR(temp);
13132 goto onError;
13133 }
13134 pbuf = PyUnicode_DATA(temp);
13135 kind = PyUnicode_KIND(temp);
13136 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013137 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013138 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013139 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013140 fillobj = zero;
13141 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013142 break;
13143
13144 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013145 {
13146 Py_UCS4 ch = formatchar(v);
13147 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013148 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013149 temp = _PyUnicode_FromUCS4(&ch, 1);
13150 if (temp == NULL)
13151 goto onError;
13152 pbuf = PyUnicode_DATA(temp);
13153 kind = PyUnicode_KIND(temp);
13154 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013155 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013156 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013157
13158 default:
13159 PyErr_Format(PyExc_ValueError,
13160 "unsupported format character '%c' (0x%x) "
13161 "at index %zd",
13162 (31<=c && c<=126) ? (char)c : '?',
13163 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013164 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013165 goto onError;
13166 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013167 /* pbuf is initialized here. */
13168 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013169 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013170 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13171 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013172 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013173 pindex++;
13174 }
13175 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13176 signobj = plus;
13177 len--;
13178 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013179 }
13180 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013181 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013182 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013183 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013184 else
13185 sign = 0;
13186 }
13187 if (width < len)
13188 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013189 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013190 if (fill != ' ') {
13191 assert(signobj != NULL);
13192 if (_PyAccu_Accumulate(&acc, signobj))
13193 goto onError;
13194 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013195 if (width > len)
13196 width--;
13197 }
13198 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013199 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013200 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013201 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013202 second = get_latin1_char(
13203 PyUnicode_READ(kind, pbuf, pindex + 1));
13204 pindex += 2;
13205 if (second == NULL ||
13206 _PyAccu_Accumulate(&acc, zero) ||
13207 _PyAccu_Accumulate(&acc, second))
13208 goto onError;
13209 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013210 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013211 width -= 2;
13212 if (width < 0)
13213 width = 0;
13214 len -= 2;
13215 }
13216 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013217 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013218 if (repeat_accumulate(&acc, fillobj, width - len))
13219 goto onError;
13220 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013221 }
13222 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013223 if (sign) {
13224 assert(signobj != NULL);
13225 if (_PyAccu_Accumulate(&acc, signobj))
13226 goto onError;
13227 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013228 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013229 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13230 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013231 second = get_latin1_char(
13232 PyUnicode_READ(kind, pbuf, pindex + 1));
13233 pindex += 2;
13234 if (second == NULL ||
13235 _PyAccu_Accumulate(&acc, zero) ||
13236 _PyAccu_Accumulate(&acc, second))
13237 goto onError;
13238 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013239 }
13240 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013241 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013242 if (temp != NULL) {
13243 assert(pbuf == PyUnicode_DATA(temp));
13244 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013245 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013246 else {
13247 const char *p = (const char *) pbuf;
13248 assert(pbuf != NULL);
13249 p = p + PyUnicode_KIND_SIZE(kind, pindex);
13250 v = PyUnicode_FromKindAndData(kind, p, len);
13251 }
13252 if (v == NULL)
13253 goto onError;
13254 r = _PyAccu_Accumulate(&acc, v);
13255 Py_DECREF(v);
13256 if (r)
13257 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013258 if (width > len && repeat_accumulate(&acc, blank, width - len))
13259 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013260 if (dict && (argidx < arglen) && c != '%') {
13261 PyErr_SetString(PyExc_TypeError,
13262 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013263 goto onError;
13264 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013265 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013266 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013267 } /* until end */
13268 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013269 PyErr_SetString(PyExc_TypeError,
13270 "not all arguments converted during string formatting");
13271 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013272 }
13273
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013274 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013275 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013276 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013277 }
13278 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013279 Py_XDECREF(temp);
13280 Py_XDECREF(second);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013281 return (PyObject *)result;
13282
Benjamin Peterson29060642009-01-31 22:14:21 +000013283 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013284 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013285 Py_XDECREF(temp);
13286 Py_XDECREF(second);
13287 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013288 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013289 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013290 }
13291 return NULL;
13292}
13293
Jeremy Hylton938ace62002-07-17 16:30:39 +000013294static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013295unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13296
Tim Peters6d6c1a32001-08-02 04:15:00 +000013297static PyObject *
13298unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13299{
Benjamin Peterson29060642009-01-31 22:14:21 +000013300 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013301 static char *kwlist[] = {"object", "encoding", "errors", 0};
13302 char *encoding = NULL;
13303 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013304
Benjamin Peterson14339b62009-01-31 16:36:08 +000013305 if (type != &PyUnicode_Type)
13306 return unicode_subtype_new(type, args, kwds);
13307 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013308 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013309 return NULL;
13310 if (x == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013311 return (PyObject *)PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013312 if (encoding == NULL && errors == NULL)
13313 return PyObject_Str(x);
13314 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013315 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013316}
13317
Guido van Rossume023fe02001-08-30 03:12:59 +000013318static PyObject *
13319unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13320{
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013321 PyUnicodeObject *unicode, *self;
13322 Py_ssize_t length, char_size;
13323 int share_wstr, share_utf8;
13324 unsigned int kind;
13325 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013326
Benjamin Peterson14339b62009-01-31 16:36:08 +000013327 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013328
13329 unicode = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
13330 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013331 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013332 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013333 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013334 return NULL;
13335
13336 self = (PyUnicodeObject *) type->tp_alloc(type, 0);
13337 if (self == NULL) {
13338 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013339 return NULL;
13340 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013341 kind = PyUnicode_KIND(unicode);
13342 length = PyUnicode_GET_LENGTH(unicode);
13343
13344 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013345#ifdef Py_DEBUG
13346 _PyUnicode_HASH(self) = -1;
13347#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013348 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013349#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013350 _PyUnicode_STATE(self).interned = 0;
13351 _PyUnicode_STATE(self).kind = kind;
13352 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013353 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013354 _PyUnicode_STATE(self).ready = 1;
13355 _PyUnicode_WSTR(self) = NULL;
13356 _PyUnicode_UTF8_LENGTH(self) = 0;
13357 _PyUnicode_UTF8(self) = NULL;
13358 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013359 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013360
13361 share_utf8 = 0;
13362 share_wstr = 0;
13363 if (kind == PyUnicode_1BYTE_KIND) {
13364 char_size = 1;
13365 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13366 share_utf8 = 1;
13367 }
13368 else if (kind == PyUnicode_2BYTE_KIND) {
13369 char_size = 2;
13370 if (sizeof(wchar_t) == 2)
13371 share_wstr = 1;
13372 }
13373 else {
13374 assert(kind == PyUnicode_4BYTE_KIND);
13375 char_size = 4;
13376 if (sizeof(wchar_t) == 4)
13377 share_wstr = 1;
13378 }
13379
13380 /* Ensure we won't overflow the length. */
13381 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13382 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013383 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013384 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013385 data = PyObject_MALLOC((length + 1) * char_size);
13386 if (data == NULL) {
13387 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013388 goto onError;
13389 }
13390
Victor Stinnerc3c74152011-10-02 20:39:55 +020013391 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013392 if (share_utf8) {
13393 _PyUnicode_UTF8_LENGTH(self) = length;
13394 _PyUnicode_UTF8(self) = data;
13395 }
13396 if (share_wstr) {
13397 _PyUnicode_WSTR_LENGTH(self) = length;
13398 _PyUnicode_WSTR(self) = (wchar_t *)data;
13399 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013400
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013401 Py_MEMCPY(data, PyUnicode_DATA(unicode),
13402 PyUnicode_KIND_SIZE(kind, length + 1));
13403 Py_DECREF(unicode);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013404 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013405#ifdef Py_DEBUG
13406 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13407#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013408 return (PyObject *)self;
13409
13410onError:
13411 Py_DECREF(unicode);
13412 Py_DECREF(self);
13413 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013414}
13415
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013416PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013417 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013418\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013419Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013420encoding defaults to the current default string encoding.\n\
13421errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013422
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013423static PyObject *unicode_iter(PyObject *seq);
13424
Guido van Rossumd57fd912000-03-10 22:53:23 +000013425PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013426 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013427 "str", /* tp_name */
13428 sizeof(PyUnicodeObject), /* tp_size */
13429 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013430 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013431 (destructor)unicode_dealloc, /* tp_dealloc */
13432 0, /* tp_print */
13433 0, /* tp_getattr */
13434 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013435 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013436 unicode_repr, /* tp_repr */
13437 &unicode_as_number, /* tp_as_number */
13438 &unicode_as_sequence, /* tp_as_sequence */
13439 &unicode_as_mapping, /* tp_as_mapping */
13440 (hashfunc) unicode_hash, /* tp_hash*/
13441 0, /* tp_call*/
13442 (reprfunc) unicode_str, /* tp_str */
13443 PyObject_GenericGetAttr, /* tp_getattro */
13444 0, /* tp_setattro */
13445 0, /* tp_as_buffer */
13446 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013447 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013448 unicode_doc, /* tp_doc */
13449 0, /* tp_traverse */
13450 0, /* tp_clear */
13451 PyUnicode_RichCompare, /* tp_richcompare */
13452 0, /* tp_weaklistoffset */
13453 unicode_iter, /* tp_iter */
13454 0, /* tp_iternext */
13455 unicode_methods, /* tp_methods */
13456 0, /* tp_members */
13457 0, /* tp_getset */
13458 &PyBaseObject_Type, /* tp_base */
13459 0, /* tp_dict */
13460 0, /* tp_descr_get */
13461 0, /* tp_descr_set */
13462 0, /* tp_dictoffset */
13463 0, /* tp_init */
13464 0, /* tp_alloc */
13465 unicode_new, /* tp_new */
13466 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013467};
13468
13469/* Initialize the Unicode implementation */
13470
Thomas Wouters78890102000-07-22 19:25:51 +000013471void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013472{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013473 int i;
13474
Thomas Wouters477c8d52006-05-27 19:21:47 +000013475 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013476 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013477 0x000A, /* LINE FEED */
13478 0x000D, /* CARRIAGE RETURN */
13479 0x001C, /* FILE SEPARATOR */
13480 0x001D, /* GROUP SEPARATOR */
13481 0x001E, /* RECORD SEPARATOR */
13482 0x0085, /* NEXT LINE */
13483 0x2028, /* LINE SEPARATOR */
13484 0x2029, /* PARAGRAPH SEPARATOR */
13485 };
13486
Fred Drakee4315f52000-05-09 19:53:39 +000013487 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013488 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013489 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013490 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013491 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013492
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013493 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013494 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013495 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013496 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013497
13498 /* initialize the linebreak bloom filter */
13499 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013500 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013501 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013502
13503 PyType_Ready(&EncodingMapType);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013504}
13505
13506/* Finalize the Unicode implementation */
13507
Christian Heimesa156e092008-02-16 07:38:31 +000013508int
13509PyUnicode_ClearFreeList(void)
13510{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013511 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013512}
13513
Guido van Rossumd57fd912000-03-10 22:53:23 +000013514void
Thomas Wouters78890102000-07-22 19:25:51 +000013515_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013516{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013517 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013518
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013519 Py_XDECREF(unicode_empty);
13520 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013521
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013522 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013523 if (unicode_latin1[i]) {
13524 Py_DECREF(unicode_latin1[i]);
13525 unicode_latin1[i] = NULL;
13526 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013527 }
Christian Heimesa156e092008-02-16 07:38:31 +000013528 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013529}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013530
Walter Dörwald16807132007-05-25 13:52:07 +000013531void
13532PyUnicode_InternInPlace(PyObject **p)
13533{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013534 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
13535 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013536#ifdef Py_DEBUG
13537 assert(s != NULL);
13538 assert(_PyUnicode_CHECK(s));
13539#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013540 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013541 return;
13542#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013543 /* If it's a subclass, we don't really know what putting
13544 it in the interned dict might do. */
13545 if (!PyUnicode_CheckExact(s))
13546 return;
13547 if (PyUnicode_CHECK_INTERNED(s))
13548 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013549 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013550 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013551 return;
13552 }
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013553 s = (PyUnicodeObject *)(*p);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013554 if (interned == NULL) {
13555 interned = PyDict_New();
13556 if (interned == NULL) {
13557 PyErr_Clear(); /* Don't leave an exception */
13558 return;
13559 }
13560 }
13561 /* It might be that the GetItem call fails even
13562 though the key is present in the dictionary,
13563 namely when this happens during a stack overflow. */
13564 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000013565 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013566 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013567
Benjamin Peterson29060642009-01-31 22:14:21 +000013568 if (t) {
13569 Py_INCREF(t);
13570 Py_DECREF(*p);
13571 *p = t;
13572 return;
13573 }
Walter Dörwald16807132007-05-25 13:52:07 +000013574
Benjamin Peterson14339b62009-01-31 16:36:08 +000013575 PyThreadState_GET()->recursion_critical = 1;
13576 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
13577 PyErr_Clear();
13578 PyThreadState_GET()->recursion_critical = 0;
13579 return;
13580 }
13581 PyThreadState_GET()->recursion_critical = 0;
13582 /* The two references in interned are not counted by refcnt.
13583 The deallocator will take care of this */
13584 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013585 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013586}
13587
13588void
13589PyUnicode_InternImmortal(PyObject **p)
13590{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013591 PyUnicodeObject *u = (PyUnicodeObject *)*p;
13592
Benjamin Peterson14339b62009-01-31 16:36:08 +000013593 PyUnicode_InternInPlace(p);
13594 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013595 _PyUnicode_STATE(u).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013596 Py_INCREF(*p);
13597 }
Walter Dörwald16807132007-05-25 13:52:07 +000013598}
13599
13600PyObject *
13601PyUnicode_InternFromString(const char *cp)
13602{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013603 PyObject *s = PyUnicode_FromString(cp);
13604 if (s == NULL)
13605 return NULL;
13606 PyUnicode_InternInPlace(&s);
13607 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000013608}
13609
Alexander Belopolsky40018472011-02-26 01:02:56 +000013610void
13611_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000013612{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013613 PyObject *keys;
13614 PyUnicodeObject *s;
13615 Py_ssize_t i, n;
13616 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000013617
Benjamin Peterson14339b62009-01-31 16:36:08 +000013618 if (interned == NULL || !PyDict_Check(interned))
13619 return;
13620 keys = PyDict_Keys(interned);
13621 if (keys == NULL || !PyList_Check(keys)) {
13622 PyErr_Clear();
13623 return;
13624 }
Walter Dörwald16807132007-05-25 13:52:07 +000013625
Benjamin Peterson14339b62009-01-31 16:36:08 +000013626 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
13627 detector, interned unicode strings are not forcibly deallocated;
13628 rather, we give them their stolen references back, and then clear
13629 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000013630
Benjamin Peterson14339b62009-01-31 16:36:08 +000013631 n = PyList_GET_SIZE(keys);
13632 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000013633 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013634 for (i = 0; i < n; i++) {
13635 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013636 if (PyUnicode_READY(s) == -1) {
13637 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013638 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013639 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013640 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013641 case SSTATE_NOT_INTERNED:
13642 /* XXX Shouldn't happen */
13643 break;
13644 case SSTATE_INTERNED_IMMORTAL:
13645 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013646 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013647 break;
13648 case SSTATE_INTERNED_MORTAL:
13649 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013650 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013651 break;
13652 default:
13653 Py_FatalError("Inconsistent interned string state.");
13654 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013655 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013656 }
13657 fprintf(stderr, "total size of all interned strings: "
13658 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
13659 "mortal/immortal\n", mortal_size, immortal_size);
13660 Py_DECREF(keys);
13661 PyDict_Clear(interned);
13662 Py_DECREF(interned);
13663 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000013664}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013665
13666
13667/********************* Unicode Iterator **************************/
13668
13669typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013670 PyObject_HEAD
13671 Py_ssize_t it_index;
13672 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013673} unicodeiterobject;
13674
13675static void
13676unicodeiter_dealloc(unicodeiterobject *it)
13677{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013678 _PyObject_GC_UNTRACK(it);
13679 Py_XDECREF(it->it_seq);
13680 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013681}
13682
13683static int
13684unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
13685{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013686 Py_VISIT(it->it_seq);
13687 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013688}
13689
13690static PyObject *
13691unicodeiter_next(unicodeiterobject *it)
13692{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013693 PyUnicodeObject *seq;
13694 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013695
Benjamin Peterson14339b62009-01-31 16:36:08 +000013696 assert(it != NULL);
13697 seq = it->it_seq;
13698 if (seq == NULL)
13699 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013700 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013701
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013702 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
13703 int kind = PyUnicode_KIND(seq);
13704 void *data = PyUnicode_DATA(seq);
13705 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
13706 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013707 if (item != NULL)
13708 ++it->it_index;
13709 return item;
13710 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013711
Benjamin Peterson14339b62009-01-31 16:36:08 +000013712 Py_DECREF(seq);
13713 it->it_seq = NULL;
13714 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013715}
13716
13717static PyObject *
13718unicodeiter_len(unicodeiterobject *it)
13719{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013720 Py_ssize_t len = 0;
13721 if (it->it_seq)
13722 len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index;
13723 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013724}
13725
13726PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
13727
13728static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013729 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000013730 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000013731 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013732};
13733
13734PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013735 PyVarObject_HEAD_INIT(&PyType_Type, 0)
13736 "str_iterator", /* tp_name */
13737 sizeof(unicodeiterobject), /* tp_basicsize */
13738 0, /* tp_itemsize */
13739 /* methods */
13740 (destructor)unicodeiter_dealloc, /* tp_dealloc */
13741 0, /* tp_print */
13742 0, /* tp_getattr */
13743 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013744 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013745 0, /* tp_repr */
13746 0, /* tp_as_number */
13747 0, /* tp_as_sequence */
13748 0, /* tp_as_mapping */
13749 0, /* tp_hash */
13750 0, /* tp_call */
13751 0, /* tp_str */
13752 PyObject_GenericGetAttr, /* tp_getattro */
13753 0, /* tp_setattro */
13754 0, /* tp_as_buffer */
13755 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
13756 0, /* tp_doc */
13757 (traverseproc)unicodeiter_traverse, /* tp_traverse */
13758 0, /* tp_clear */
13759 0, /* tp_richcompare */
13760 0, /* tp_weaklistoffset */
13761 PyObject_SelfIter, /* tp_iter */
13762 (iternextfunc)unicodeiter_next, /* tp_iternext */
13763 unicodeiter_methods, /* tp_methods */
13764 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013765};
13766
13767static PyObject *
13768unicode_iter(PyObject *seq)
13769{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013770 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013771
Benjamin Peterson14339b62009-01-31 16:36:08 +000013772 if (!PyUnicode_Check(seq)) {
13773 PyErr_BadInternalCall();
13774 return NULL;
13775 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013776 if (PyUnicode_READY(seq) == -1)
13777 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013778 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
13779 if (it == NULL)
13780 return NULL;
13781 it->it_index = 0;
13782 Py_INCREF(seq);
13783 it->it_seq = (PyUnicodeObject *)seq;
13784 _PyObject_GC_TRACK(it);
13785 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013786}
13787
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013788#define UNIOP(x) Py_UNICODE_##x
13789#define UNIOP_t Py_UNICODE
13790#include "uniops.h"
13791#undef UNIOP
13792#undef UNIOP_t
13793#define UNIOP(x) Py_UCS4_##x
13794#define UNIOP_t Py_UCS4
13795#include "uniops.h"
13796#undef UNIOP
13797#undef UNIOP_t
Victor Stinner331ea922010-08-10 16:37:20 +000013798
Victor Stinner71133ff2010-09-01 23:43:53 +000013799Py_UNICODE*
Victor Stinner46408602010-09-03 16:18:00 +000013800PyUnicode_AsUnicodeCopy(PyObject *object)
Victor Stinner71133ff2010-09-01 23:43:53 +000013801{
13802 PyUnicodeObject *unicode = (PyUnicodeObject *)object;
13803 Py_UNICODE *copy;
13804 Py_ssize_t size;
13805
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013806 if (!PyUnicode_Check(unicode)) {
13807 PyErr_BadArgument();
13808 return NULL;
13809 }
Victor Stinner71133ff2010-09-01 23:43:53 +000013810 /* Ensure we won't overflow the size. */
13811 if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
13812 PyErr_NoMemory();
13813 return NULL;
13814 }
13815 size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
13816 size *= sizeof(Py_UNICODE);
13817 copy = PyMem_Malloc(size);
13818 if (copy == NULL) {
13819 PyErr_NoMemory();
13820 return NULL;
13821 }
13822 memcpy(copy, PyUnicode_AS_UNICODE(unicode), size);
13823 return copy;
13824}
Martin v. Löwis5b222132007-06-10 09:51:05 +000013825
Georg Brandl66c221e2010-10-14 07:04:07 +000013826/* A _string module, to export formatter_parser and formatter_field_name_split
13827 to the string.Formatter class implemented in Python. */
13828
13829static PyMethodDef _string_methods[] = {
13830 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
13831 METH_O, PyDoc_STR("split the argument as a field name")},
13832 {"formatter_parser", (PyCFunction) formatter_parser,
13833 METH_O, PyDoc_STR("parse the argument as a format string")},
13834 {NULL, NULL}
13835};
13836
13837static struct PyModuleDef _string_module = {
13838 PyModuleDef_HEAD_INIT,
13839 "_string",
13840 PyDoc_STR("string helper module"),
13841 0,
13842 _string_methods,
13843 NULL,
13844 NULL,
13845 NULL,
13846 NULL
13847};
13848
13849PyMODINIT_FUNC
13850PyInit__string(void)
13851{
13852 return PyModule_Create(&_string_module);
13853}
13854
13855
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013856#ifdef __cplusplus
13857}
13858#endif