blob: 990b5bf10a9f923593f364d72c46d6b1b9a3bb23 [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)
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200473 return (char*)s + kind * i;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200474 }
475 else {
476 for(i = size-1; i >= 0; i--)
477 if (PyUnicode_READ(kind, s, i) == ch)
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200478 return (char*)s + kind * i;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200479 }
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));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200492 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200493 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);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200543 char_size = PyUnicode_KIND(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) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001008 Py_MEMCPY((char*)to_data + to_kind * to_start,
1009 (char*)from_data + from_kind * from_start,
1010 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001011 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001012 else if (from_kind == PyUnicode_1BYTE_KIND
1013 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001014 {
1015 _PyUnicode_CONVERT_BYTES(
1016 Py_UCS1, Py_UCS2,
1017 PyUnicode_1BYTE_DATA(from) + from_start,
1018 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1019 PyUnicode_2BYTE_DATA(to) + to_start
1020 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001021 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001022 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001023 && to_kind == PyUnicode_4BYTE_KIND)
1024 {
1025 _PyUnicode_CONVERT_BYTES(
1026 Py_UCS1, Py_UCS4,
1027 PyUnicode_1BYTE_DATA(from) + from_start,
1028 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1029 PyUnicode_4BYTE_DATA(to) + to_start
1030 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001031 }
1032 else if (from_kind == PyUnicode_2BYTE_KIND
1033 && to_kind == PyUnicode_4BYTE_KIND)
1034 {
1035 _PyUnicode_CONVERT_BYTES(
1036 Py_UCS2, Py_UCS4,
1037 PyUnicode_2BYTE_DATA(from) + from_start,
1038 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1039 PyUnicode_4BYTE_DATA(to) + to_start
1040 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001041 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001042 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001043 /* check if max_char(from substring) <= max_char(to) */
1044 if (from_kind > to_kind
1045 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001046 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001047 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001048 /* slow path to check for character overflow */
1049 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001050 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001051 Py_ssize_t i;
1052
Victor Stinner56c161a2011-10-06 02:47:11 +02001053#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001054 for (i=0; i < how_many; i++) {
1055 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001056 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001057 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1058 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001059#else
1060 if (!check_maxchar) {
1061 for (i=0; i < how_many; i++) {
1062 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1063 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1064 }
1065 }
1066 else {
1067 for (i=0; i < how_many; i++) {
1068 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1069 if (ch > to_maxchar)
1070 return 1;
1071 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1072 }
1073 }
1074#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001075 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001076 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001077 assert(0 && "inconsistent state");
1078 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001079 }
1080 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001081 return 0;
1082}
1083
1084static void
1085copy_characters(PyObject *to, Py_ssize_t to_start,
1086 PyObject *from, Py_ssize_t from_start,
1087 Py_ssize_t how_many)
1088{
1089 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1090}
1091
1092Py_ssize_t
1093PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1094 PyObject *from, Py_ssize_t from_start,
1095 Py_ssize_t how_many)
1096{
1097 int err;
1098
1099 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1100 PyErr_BadInternalCall();
1101 return -1;
1102 }
1103
1104 if (PyUnicode_READY(from))
1105 return -1;
1106 if (PyUnicode_READY(to))
1107 return -1;
1108
1109 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1110 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1111 PyErr_Format(PyExc_SystemError,
1112 "Cannot write %zi characters at %zi "
1113 "in a string of %zi characters",
1114 how_many, to_start, PyUnicode_GET_LENGTH(to));
1115 return -1;
1116 }
1117
1118 if (how_many == 0)
1119 return 0;
1120
1121 if (_PyUnicode_Dirty(to))
1122 return -1;
1123
1124 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1125 if (err) {
1126 PyErr_Format(PyExc_SystemError,
1127 "Cannot copy %s characters "
1128 "into a string of %s characters",
1129 unicode_kind_name(from),
1130 unicode_kind_name(to));
1131 return -1;
1132 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001133 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001134}
1135
Victor Stinner17222162011-09-28 22:15:37 +02001136/* Find the maximum code point and count the number of surrogate pairs so a
1137 correct string length can be computed before converting a string to UCS4.
1138 This function counts single surrogates as a character and not as a pair.
1139
1140 Return 0 on success, or -1 on error. */
1141static int
1142find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1143 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001144{
1145 const wchar_t *iter;
1146
Victor Stinnerc53be962011-10-02 21:33:54 +02001147 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001148 *num_surrogates = 0;
1149 *maxchar = 0;
1150
1151 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001152 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001153 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001154#if SIZEOF_WCHAR_T != 2
1155 if (*maxchar >= 0x10000)
1156 return 0;
1157#endif
1158 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001159#if SIZEOF_WCHAR_T == 2
1160 if (*iter >= 0xD800 && *iter <= 0xDBFF
1161 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1162 {
1163 Py_UCS4 surrogate_val;
1164 surrogate_val = (((iter[0] & 0x3FF)<<10)
1165 | (iter[1] & 0x3FF)) + 0x10000;
1166 ++(*num_surrogates);
1167 if (surrogate_val > *maxchar)
1168 *maxchar = surrogate_val;
1169 iter += 2;
1170 }
1171 else
1172 iter++;
1173#else
1174 iter++;
1175#endif
1176 }
1177 return 0;
1178}
1179
1180#ifdef Py_DEBUG
1181int unicode_ready_calls = 0;
1182#endif
1183
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001184static int
1185unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001186{
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001187 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001188 wchar_t *end;
1189 Py_UCS4 maxchar = 0;
1190 Py_ssize_t num_surrogates;
1191#if SIZEOF_WCHAR_T == 2
1192 Py_ssize_t length_wo_surrogates;
1193#endif
1194
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001195 assert(p_obj != NULL);
1196 unicode = (PyUnicodeObject *)*p_obj;
1197
Georg Brandl7597add2011-10-05 16:36:47 +02001198 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001199 strings were created using _PyObject_New() and where no canonical
1200 representation (the str field) has been set yet aka strings
1201 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001202 assert(_PyUnicode_CHECK(unicode));
1203 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001204 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001205 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001206 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001207 /* Actually, it should neither be interned nor be anything else: */
1208 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001209
1210#ifdef Py_DEBUG
1211 ++unicode_ready_calls;
1212#endif
1213
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001214#ifdef Py_DEBUG
1215 assert(!replace || Py_REFCNT(unicode) == 1);
1216#else
1217 if (replace && Py_REFCNT(unicode) != 1)
1218 replace = 0;
1219#endif
1220 if (replace) {
1221 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1222 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1223 /* Optimization for empty strings */
1224 if (len == 0) {
1225 Py_INCREF(unicode_empty);
1226 Py_DECREF(*p_obj);
1227 *p_obj = unicode_empty;
1228 return 0;
1229 }
1230 if (len == 1 && wstr[0] < 256) {
1231 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1232 if (latin1_char == NULL)
1233 return -1;
1234 Py_DECREF(*p_obj);
1235 *p_obj = latin1_char;
1236 return 0;
1237 }
1238 }
1239
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001240 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001241 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001242 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001243 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001244
1245 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001246 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1247 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001248 PyErr_NoMemory();
1249 return -1;
1250 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001251 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001252 _PyUnicode_WSTR(unicode), end,
1253 PyUnicode_1BYTE_DATA(unicode));
1254 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1255 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1256 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1257 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001258 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001259 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001260 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001261 }
1262 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001263 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001264 _PyUnicode_UTF8(unicode) = NULL;
1265 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001266 }
1267 PyObject_FREE(_PyUnicode_WSTR(unicode));
1268 _PyUnicode_WSTR(unicode) = NULL;
1269 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1270 }
1271 /* In this case we might have to convert down from 4-byte native
1272 wchar_t to 2-byte unicode. */
1273 else if (maxchar < 65536) {
1274 assert(num_surrogates == 0 &&
1275 "FindMaxCharAndNumSurrogatePairs() messed up");
1276
Victor Stinner506f5922011-09-28 22:34:18 +02001277#if SIZEOF_WCHAR_T == 2
1278 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001279 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001280 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1281 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1282 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001283 _PyUnicode_UTF8(unicode) = NULL;
1284 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001285#else
1286 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001287 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001288 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001289 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001290 PyErr_NoMemory();
1291 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001292 }
Victor Stinner506f5922011-09-28 22:34:18 +02001293 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1294 _PyUnicode_WSTR(unicode), end,
1295 PyUnicode_2BYTE_DATA(unicode));
1296 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1297 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1298 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001299 _PyUnicode_UTF8(unicode) = NULL;
1300 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001301 PyObject_FREE(_PyUnicode_WSTR(unicode));
1302 _PyUnicode_WSTR(unicode) = NULL;
1303 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1304#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001305 }
1306 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1307 else {
1308#if SIZEOF_WCHAR_T == 2
1309 /* in case the native representation is 2-bytes, we need to allocate a
1310 new normalized 4-byte version. */
1311 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001312 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1313 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001314 PyErr_NoMemory();
1315 return -1;
1316 }
1317 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1318 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001319 _PyUnicode_UTF8(unicode) = NULL;
1320 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001321 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1322 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001323 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001324 PyObject_FREE(_PyUnicode_WSTR(unicode));
1325 _PyUnicode_WSTR(unicode) = NULL;
1326 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1327#else
1328 assert(num_surrogates == 0);
1329
Victor Stinnerc3c74152011-10-02 20:39:55 +02001330 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001331 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001332 _PyUnicode_UTF8(unicode) = NULL;
1333 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001334 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1335#endif
1336 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1337 }
1338 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001339 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001340 return 0;
1341}
1342
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001343int
1344_PyUnicode_ReadyReplace(PyObject **op)
1345{
1346 return unicode_ready(op, 1);
1347}
1348
1349int
1350_PyUnicode_Ready(PyObject *op)
1351{
1352 return unicode_ready(&op, 0);
1353}
1354
Alexander Belopolsky40018472011-02-26 01:02:56 +00001355static void
1356unicode_dealloc(register PyUnicodeObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001357{
Walter Dörwald16807132007-05-25 13:52:07 +00001358 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001359 case SSTATE_NOT_INTERNED:
1360 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001361
Benjamin Peterson29060642009-01-31 22:14:21 +00001362 case SSTATE_INTERNED_MORTAL:
1363 /* revive dead object temporarily for DelItem */
1364 Py_REFCNT(unicode) = 3;
1365 if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
1366 Py_FatalError(
1367 "deletion of interned string failed");
1368 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001369
Benjamin Peterson29060642009-01-31 22:14:21 +00001370 case SSTATE_INTERNED_IMMORTAL:
1371 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001372
Benjamin Peterson29060642009-01-31 22:14:21 +00001373 default:
1374 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001375 }
1376
Victor Stinner03490912011-10-03 23:45:12 +02001377 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001378 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001379 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001380 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001381
1382 if (PyUnicode_IS_COMPACT(unicode)) {
1383 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001384 }
1385 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001386 if (_PyUnicode_DATA_ANY(unicode))
1387 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Benjamin Peterson29060642009-01-31 22:14:21 +00001388 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001389 }
1390}
1391
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001392#ifdef Py_DEBUG
1393static int
1394unicode_is_singleton(PyObject *unicode)
1395{
1396 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1397 if (unicode == unicode_empty)
1398 return 1;
1399 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1400 {
1401 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1402 if (ch < 256 && unicode_latin1[ch] == unicode)
1403 return 1;
1404 }
1405 return 0;
1406}
1407#endif
1408
Alexander Belopolsky40018472011-02-26 01:02:56 +00001409static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001410unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001411{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001412 if (Py_REFCNT(unicode) != 1)
1413 return 0;
1414 if (PyUnicode_CHECK_INTERNED(unicode))
1415 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001416#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001417 /* singleton refcount is greater than 1 */
1418 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001419#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001420 return 1;
1421}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001422
Victor Stinnerfe226c02011-10-03 03:52:20 +02001423static int
1424unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1425{
1426 PyObject *unicode;
1427 Py_ssize_t old_length;
1428
1429 assert(p_unicode != NULL);
1430 unicode = *p_unicode;
1431
1432 assert(unicode != NULL);
1433 assert(PyUnicode_Check(unicode));
1434 assert(0 <= length);
1435
Victor Stinner910337b2011-10-03 03:20:16 +02001436 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001437 old_length = PyUnicode_WSTR_LENGTH(unicode);
1438 else
1439 old_length = PyUnicode_GET_LENGTH(unicode);
1440 if (old_length == length)
1441 return 0;
1442
Victor Stinnerfe226c02011-10-03 03:52:20 +02001443 if (!unicode_resizable(unicode)) {
1444 PyObject *copy = resize_copy(unicode, length);
1445 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001446 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001447 Py_DECREF(*p_unicode);
1448 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001449 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001450 }
1451
Victor Stinnerfe226c02011-10-03 03:52:20 +02001452 if (PyUnicode_IS_COMPACT(unicode)) {
1453 *p_unicode = resize_compact(unicode, length);
1454 if (*p_unicode == NULL)
1455 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001456 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001457 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001458 }
1459 return resize_inplace((PyUnicodeObject*)unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001460}
1461
Alexander Belopolsky40018472011-02-26 01:02:56 +00001462int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001463PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001464{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001465 PyObject *unicode;
1466 if (p_unicode == NULL) {
1467 PyErr_BadInternalCall();
1468 return -1;
1469 }
1470 unicode = *p_unicode;
1471 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0
1472 || _PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND)
1473 {
1474 PyErr_BadInternalCall();
1475 return -1;
1476 }
1477 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001478}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001479
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001480static PyObject*
1481get_latin1_char(unsigned char ch)
1482{
Victor Stinnera464fc12011-10-02 20:39:30 +02001483 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001484 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001485 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001486 if (!unicode)
1487 return NULL;
1488 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001489 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001490 unicode_latin1[ch] = unicode;
1491 }
1492 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001493 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001494}
1495
Alexander Belopolsky40018472011-02-26 01:02:56 +00001496PyObject *
1497PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001498{
1499 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001500 Py_UCS4 maxchar = 0;
1501 Py_ssize_t num_surrogates;
1502
1503 if (u == NULL)
1504 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001505
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001506 /* If the Unicode data is known at construction time, we can apply
1507 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001508
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001509 /* Optimization for empty strings */
1510 if (size == 0 && unicode_empty != NULL) {
1511 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001512 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001513 }
Tim Petersced69f82003-09-16 20:30:58 +00001514
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001515 /* Single character Unicode objects in the Latin-1 range are
1516 shared when using this constructor */
1517 if (size == 1 && *u < 256)
1518 return get_latin1_char((unsigned char)*u);
1519
1520 /* If not empty and not single character, copy the Unicode data
1521 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001522 if (find_maxchar_surrogates(u, u + size,
1523 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001524 return NULL;
1525
1526 unicode = (PyUnicodeObject *) PyUnicode_New(size - num_surrogates,
1527 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001528 if (!unicode)
1529 return NULL;
1530
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001531 switch (PyUnicode_KIND(unicode)) {
1532 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001533 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001534 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1535 break;
1536 case PyUnicode_2BYTE_KIND:
1537#if Py_UNICODE_SIZE == 2
1538 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1539#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001540 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001541 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1542#endif
1543 break;
1544 case PyUnicode_4BYTE_KIND:
1545#if SIZEOF_WCHAR_T == 2
1546 /* This is the only case which has to process surrogates, thus
1547 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001548 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001549#else
1550 assert(num_surrogates == 0);
1551 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1552#endif
1553 break;
1554 default:
1555 assert(0 && "Impossible state");
1556 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001557
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001558 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001559 return (PyObject *)unicode;
1560}
1561
Alexander Belopolsky40018472011-02-26 01:02:56 +00001562PyObject *
1563PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001564{
1565 PyUnicodeObject *unicode;
Christian Heimes33fe8092008-04-13 13:53:33 +00001566
Benjamin Peterson14339b62009-01-31 16:36:08 +00001567 if (size < 0) {
1568 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001569 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001570 return NULL;
1571 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001572
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001573 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001574 some optimizations which share commonly used objects.
1575 Also, this means the input must be UTF-8, so fall back to the
1576 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001577 if (u != NULL) {
1578
Benjamin Peterson29060642009-01-31 22:14:21 +00001579 /* Optimization for empty strings */
1580 if (size == 0 && unicode_empty != NULL) {
1581 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001582 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001583 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001584
1585 /* Single characters are shared when using this constructor.
1586 Restrict to ASCII, since the input must be UTF-8. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001587 if (size == 1 && Py_CHARMASK(*u) < 128)
1588 return get_latin1_char(Py_CHARMASK(*u));
Martin v. Löwis9c121062007-08-05 20:26:11 +00001589
1590 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001591 }
1592
Walter Dörwald55507312007-05-18 13:12:10 +00001593 unicode = _PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001594 if (!unicode)
1595 return NULL;
1596
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001597 return (PyObject *)unicode;
1598}
1599
Alexander Belopolsky40018472011-02-26 01:02:56 +00001600PyObject *
1601PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001602{
1603 size_t size = strlen(u);
1604 if (size > PY_SSIZE_T_MAX) {
1605 PyErr_SetString(PyExc_OverflowError, "input too long");
1606 return NULL;
1607 }
1608
1609 return PyUnicode_FromStringAndSize(u, size);
1610}
1611
Victor Stinnere57b1c02011-09-28 22:20:48 +02001612static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001613unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001614{
Victor Stinner0617b6e2011-10-05 23:26:01 +02001615 PyObject *res;
1616#ifdef Py_DEBUG
1617 const unsigned char *p;
1618 const unsigned char *end = s + size;
1619 for (p=s; p < end; p++) {
1620 assert(*p < 128);
1621 }
1622#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001623 if (size == 1)
1624 return get_latin1_char(s[0]);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001625 res = PyUnicode_New(size, 127);
Victor Stinner702c7342011-10-05 13:50:52 +02001626 if (!res)
1627 return NULL;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001628 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
Victor Stinner702c7342011-10-05 13:50:52 +02001629 return res;
1630}
1631
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001632static Py_UCS4
1633kind_maxchar_limit(unsigned int kind)
1634{
1635 switch(kind) {
1636 case PyUnicode_1BYTE_KIND:
1637 return 0x80;
1638 case PyUnicode_2BYTE_KIND:
1639 return 0x100;
1640 case PyUnicode_4BYTE_KIND:
1641 return 0x10000;
1642 default:
1643 assert(0 && "invalid kind");
1644 return 0x10ffff;
1645 }
1646}
1647
Victor Stinner702c7342011-10-05 13:50:52 +02001648static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001649_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001650{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001651 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001652 unsigned char max_char = 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001653 Py_ssize_t i;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001654
1655 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001656 if (size == 1)
1657 return get_latin1_char(u[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001658 for (i = 0; i < size; i++) {
1659 if (u[i] & 0x80) {
Victor Stinnerb9275c12011-10-05 14:01:42 +02001660 max_char = 255;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001661 break;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001662 }
1663 }
Victor Stinnerb9275c12011-10-05 14:01:42 +02001664 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001665 if (!res)
1666 return NULL;
1667 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001668 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001669 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001670}
1671
Victor Stinnere57b1c02011-09-28 22:20:48 +02001672static PyObject*
1673_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001674{
1675 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001676 Py_UCS2 max_char = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001677 Py_ssize_t i;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001678
1679 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001680 if (size == 1 && u[0] < 256)
1681 return get_latin1_char(u[0]);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001682 for (i = 0; i < size; i++) {
1683 if (u[i] > max_char) {
1684 max_char = u[i];
1685 if (max_char >= 256)
1686 break;
1687 }
1688 }
1689 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001690 if (!res)
1691 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001692 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001693 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
1694 else
1695 for (i = 0; i < size; i++)
1696 PyUnicode_1BYTE_DATA(res)[i] = (Py_UCS1)u[i];
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001697 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001698 return res;
1699}
1700
Victor Stinnere57b1c02011-09-28 22:20:48 +02001701static PyObject*
1702_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001703{
1704 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001705 Py_UCS4 max_char = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001706 Py_ssize_t i;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001707
1708 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001709 if (size == 1 && u[0] < 256)
1710 return get_latin1_char(u[0]);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001711 for (i = 0; i < size; i++) {
1712 if (u[i] > max_char) {
1713 max_char = u[i];
1714 if (max_char >= 0x10000)
1715 break;
1716 }
1717 }
1718 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001719 if (!res)
1720 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001721 if (max_char >= 0x10000)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001722 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
1723 else {
1724 int kind = PyUnicode_KIND(res);
1725 void *data = PyUnicode_DATA(res);
1726 for (i = 0; i < size; i++)
1727 PyUnicode_WRITE(kind, data, i, u[i]);
1728 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001729 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001730 return res;
1731}
1732
1733PyObject*
1734PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1735{
1736 switch(kind) {
1737 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001738 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001739 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001740 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001741 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001742 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001743 default:
1744 assert(0 && "invalid kind");
1745 PyErr_SetString(PyExc_SystemError, "invalid kind");
1746 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001747 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001748}
1749
Victor Stinner25a4b292011-10-06 12:31:55 +02001750/* Ensure that a string uses the most efficient storage, if it is not the
1751 case: create a new string with of the right kind. Write NULL into *p_unicode
1752 on error. */
1753void
1754unicode_adjust_maxchar(PyObject **p_unicode)
1755{
1756 PyObject *unicode, *copy;
1757 Py_UCS4 max_char;
1758 Py_ssize_t i, len;
1759 unsigned int kind;
1760
1761 assert(p_unicode != NULL);
1762 unicode = *p_unicode;
1763 assert(PyUnicode_IS_READY(unicode));
1764 if (PyUnicode_IS_ASCII(unicode))
1765 return;
1766
1767 len = PyUnicode_GET_LENGTH(unicode);
1768 kind = PyUnicode_KIND(unicode);
1769 if (kind == PyUnicode_1BYTE_KIND) {
1770 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
1771 for (i = 0; i < len; i++) {
1772 if (u[i] & 0x80)
1773 return;
1774 }
1775 max_char = 127;
1776 }
1777 else if (kind == PyUnicode_2BYTE_KIND) {
1778 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
1779 max_char = 0;
1780 for (i = 0; i < len; i++) {
1781 if (u[i] > max_char) {
1782 max_char = u[i];
1783 if (max_char >= 256)
1784 return;
1785 }
1786 }
1787 }
1788 else {
Antoine Pitrou15a66cf2011-10-06 15:25:32 +02001789 const Py_UCS4 *u;
Victor Stinner25a4b292011-10-06 12:31:55 +02001790 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitrou15a66cf2011-10-06 15:25:32 +02001791 u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001792 max_char = 0;
1793 for (i = 0; i < len; i++) {
1794 if (u[i] > max_char) {
1795 max_char = u[i];
1796 if (max_char >= 0x10000)
1797 return;
1798 }
1799 }
1800 }
Victor Stinner200f2132011-10-06 13:27:56 +02001801 assert(max_char < PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinner25a4b292011-10-06 12:31:55 +02001802 copy = PyUnicode_New(len, max_char);
1803 copy_characters(copy, 0, unicode, 0, len);
1804 Py_DECREF(unicode);
1805 *p_unicode = copy;
1806}
1807
Victor Stinner034f6cf2011-09-30 02:26:44 +02001808PyObject*
1809PyUnicode_Copy(PyObject *unicode)
1810{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001811 Py_ssize_t size;
1812 PyObject *copy;
1813 void *data;
1814
Victor Stinner034f6cf2011-09-30 02:26:44 +02001815 if (!PyUnicode_Check(unicode)) {
1816 PyErr_BadInternalCall();
1817 return NULL;
1818 }
1819 if (PyUnicode_READY(unicode))
1820 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001821
1822 size = PyUnicode_GET_LENGTH(unicode);
1823 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1824 if (!copy)
1825 return NULL;
1826 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1827
1828 data = PyUnicode_DATA(unicode);
1829 switch (PyUnicode_KIND(unicode))
1830 {
1831 case PyUnicode_1BYTE_KIND:
1832 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1833 break;
1834 case PyUnicode_2BYTE_KIND:
1835 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1836 break;
1837 case PyUnicode_4BYTE_KIND:
1838 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1839 break;
1840 default:
1841 assert(0);
1842 break;
1843 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001844 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001845 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001846}
1847
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001848
Victor Stinnerbc603d12011-10-02 01:00:40 +02001849/* Widen Unicode objects to larger buffers. Don't write terminating null
1850 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001851
1852void*
1853_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1854{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001855 Py_ssize_t len;
1856 void *result;
1857 unsigned int skind;
1858
1859 if (PyUnicode_READY(s))
1860 return NULL;
1861
1862 len = PyUnicode_GET_LENGTH(s);
1863 skind = PyUnicode_KIND(s);
1864 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001865 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001866 return NULL;
1867 }
1868 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001869 case PyUnicode_2BYTE_KIND:
1870 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1871 if (!result)
1872 return PyErr_NoMemory();
1873 assert(skind == PyUnicode_1BYTE_KIND);
1874 _PyUnicode_CONVERT_BYTES(
1875 Py_UCS1, Py_UCS2,
1876 PyUnicode_1BYTE_DATA(s),
1877 PyUnicode_1BYTE_DATA(s) + len,
1878 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001879 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001880 case PyUnicode_4BYTE_KIND:
1881 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1882 if (!result)
1883 return PyErr_NoMemory();
1884 if (skind == PyUnicode_2BYTE_KIND) {
1885 _PyUnicode_CONVERT_BYTES(
1886 Py_UCS2, Py_UCS4,
1887 PyUnicode_2BYTE_DATA(s),
1888 PyUnicode_2BYTE_DATA(s) + len,
1889 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001890 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001891 else {
1892 assert(skind == PyUnicode_1BYTE_KIND);
1893 _PyUnicode_CONVERT_BYTES(
1894 Py_UCS1, Py_UCS4,
1895 PyUnicode_1BYTE_DATA(s),
1896 PyUnicode_1BYTE_DATA(s) + len,
1897 result);
1898 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001899 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001900 default:
1901 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001902 }
Victor Stinner01698042011-10-04 00:04:26 +02001903 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001904 return NULL;
1905}
1906
1907static Py_UCS4*
1908as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1909 int copy_null)
1910{
1911 int kind;
1912 void *data;
1913 Py_ssize_t len, targetlen;
1914 if (PyUnicode_READY(string) == -1)
1915 return NULL;
1916 kind = PyUnicode_KIND(string);
1917 data = PyUnicode_DATA(string);
1918 len = PyUnicode_GET_LENGTH(string);
1919 targetlen = len;
1920 if (copy_null)
1921 targetlen++;
1922 if (!target) {
1923 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
1924 PyErr_NoMemory();
1925 return NULL;
1926 }
1927 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
1928 if (!target) {
1929 PyErr_NoMemory();
1930 return NULL;
1931 }
1932 }
1933 else {
1934 if (targetsize < targetlen) {
1935 PyErr_Format(PyExc_SystemError,
1936 "string is longer than the buffer");
1937 if (copy_null && 0 < targetsize)
1938 target[0] = 0;
1939 return NULL;
1940 }
1941 }
1942 if (kind != PyUnicode_4BYTE_KIND) {
1943 Py_ssize_t i;
1944 for (i = 0; i < len; i++)
1945 target[i] = PyUnicode_READ(kind, data, i);
1946 }
1947 else
1948 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
1949 if (copy_null)
1950 target[len] = 0;
1951 return target;
1952}
1953
1954Py_UCS4*
1955PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1956 int copy_null)
1957{
1958 if (target == NULL || targetsize < 1) {
1959 PyErr_BadInternalCall();
1960 return NULL;
1961 }
1962 return as_ucs4(string, target, targetsize, copy_null);
1963}
1964
1965Py_UCS4*
1966PyUnicode_AsUCS4Copy(PyObject *string)
1967{
1968 return as_ucs4(string, NULL, 0, 1);
1969}
1970
1971#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00001972
Alexander Belopolsky40018472011-02-26 01:02:56 +00001973PyObject *
1974PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001975{
Guido van Rossumd57fd912000-03-10 22:53:23 +00001976 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00001977 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001978 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00001979 PyErr_BadInternalCall();
1980 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001981 }
1982
Martin v. Löwis790465f2008-04-05 20:41:37 +00001983 if (size == -1) {
1984 size = wcslen(w);
1985 }
1986
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001987 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001988}
1989
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001990#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00001991
Walter Dörwald346737f2007-05-31 10:44:43 +00001992static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001993makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
1994 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00001995{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001996 *fmt++ = '%';
1997 if (width) {
1998 if (zeropad)
1999 *fmt++ = '0';
2000 fmt += sprintf(fmt, "%d", width);
2001 }
2002 if (precision)
2003 fmt += sprintf(fmt, ".%d", precision);
2004 if (longflag)
2005 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002006 else if (longlongflag) {
2007 /* longlongflag should only ever be nonzero on machines with
2008 HAVE_LONG_LONG defined */
2009#ifdef HAVE_LONG_LONG
2010 char *f = PY_FORMAT_LONG_LONG;
2011 while (*f)
2012 *fmt++ = *f++;
2013#else
2014 /* we shouldn't ever get here */
2015 assert(0);
2016 *fmt++ = 'l';
2017#endif
2018 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002019 else if (size_tflag) {
2020 char *f = PY_FORMAT_SIZE_T;
2021 while (*f)
2022 *fmt++ = *f++;
2023 }
2024 *fmt++ = c;
2025 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002026}
2027
Victor Stinner96865452011-03-01 23:44:09 +00002028/* helper for PyUnicode_FromFormatV() */
2029
2030static const char*
2031parse_format_flags(const char *f,
2032 int *p_width, int *p_precision,
2033 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2034{
2035 int width, precision, longflag, longlongflag, size_tflag;
2036
2037 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2038 f++;
2039 width = 0;
2040 while (Py_ISDIGIT((unsigned)*f))
2041 width = (width*10) + *f++ - '0';
2042 precision = 0;
2043 if (*f == '.') {
2044 f++;
2045 while (Py_ISDIGIT((unsigned)*f))
2046 precision = (precision*10) + *f++ - '0';
2047 if (*f == '%') {
2048 /* "%.3%s" => f points to "3" */
2049 f--;
2050 }
2051 }
2052 if (*f == '\0') {
2053 /* bogus format "%.1" => go backward, f points to "1" */
2054 f--;
2055 }
2056 if (p_width != NULL)
2057 *p_width = width;
2058 if (p_precision != NULL)
2059 *p_precision = precision;
2060
2061 /* Handle %ld, %lu, %lld and %llu. */
2062 longflag = 0;
2063 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002064 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002065
2066 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002067 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002068 longflag = 1;
2069 ++f;
2070 }
2071#ifdef HAVE_LONG_LONG
2072 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002073 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002074 longlongflag = 1;
2075 f += 2;
2076 }
2077#endif
2078 }
2079 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002080 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002081 size_tflag = 1;
2082 ++f;
2083 }
2084 if (p_longflag != NULL)
2085 *p_longflag = longflag;
2086 if (p_longlongflag != NULL)
2087 *p_longlongflag = longlongflag;
2088 if (p_size_tflag != NULL)
2089 *p_size_tflag = size_tflag;
2090 return f;
2091}
2092
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002093/* maximum number of characters required for output of %ld. 21 characters
2094 allows for 64-bit integers (in decimal) and an optional sign. */
2095#define MAX_LONG_CHARS 21
2096/* maximum number of characters required for output of %lld.
2097 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2098 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2099#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2100
Walter Dörwaldd2034312007-05-18 16:29:38 +00002101PyObject *
2102PyUnicode_FromFormatV(const char *format, va_list vargs)
2103{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002104 va_list count;
2105 Py_ssize_t callcount = 0;
2106 PyObject **callresults = NULL;
2107 PyObject **callresult = NULL;
2108 Py_ssize_t n = 0;
2109 int width = 0;
2110 int precision = 0;
2111 int zeropad;
2112 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002113 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002114 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002115 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002116 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2117 Py_UCS4 argmaxchar;
2118 Py_ssize_t numbersize = 0;
2119 char *numberresults = NULL;
2120 char *numberresult = NULL;
2121 Py_ssize_t i;
2122 int kind;
2123 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002124
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002125 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002126 /* step 1: count the number of %S/%R/%A/%s format specifications
2127 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2128 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002129 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002130 * also estimate a upper bound for all the number formats in the string,
2131 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002132 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002133 for (f = format; *f; f++) {
2134 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002135 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002136 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2137 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2138 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2139 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002140
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002141 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002142#ifdef HAVE_LONG_LONG
2143 if (longlongflag) {
2144 if (width < MAX_LONG_LONG_CHARS)
2145 width = MAX_LONG_LONG_CHARS;
2146 }
2147 else
2148#endif
2149 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2150 including sign. Decimal takes the most space. This
2151 isn't enough for octal. If a width is specified we
2152 need more (which we allocate later). */
2153 if (width < MAX_LONG_CHARS)
2154 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002155
2156 /* account for the size + '\0' to separate numbers
2157 inside of the numberresults buffer */
2158 numbersize += (width + 1);
2159 }
2160 }
2161 else if ((unsigned char)*f > 127) {
2162 PyErr_Format(PyExc_ValueError,
2163 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2164 "string, got a non-ASCII byte: 0x%02x",
2165 (unsigned char)*f);
2166 return NULL;
2167 }
2168 }
2169 /* step 2: allocate memory for the results of
2170 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2171 if (callcount) {
2172 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2173 if (!callresults) {
2174 PyErr_NoMemory();
2175 return NULL;
2176 }
2177 callresult = callresults;
2178 }
2179 /* step 2.5: allocate memory for the results of formating numbers */
2180 if (numbersize) {
2181 numberresults = PyObject_Malloc(numbersize);
2182 if (!numberresults) {
2183 PyErr_NoMemory();
2184 goto fail;
2185 }
2186 numberresult = numberresults;
2187 }
2188
2189 /* step 3: format numbers and figure out how large a buffer we need */
2190 for (f = format; *f; f++) {
2191 if (*f == '%') {
2192 const char* p;
2193 int longflag;
2194 int longlongflag;
2195 int size_tflag;
2196 int numprinted;
2197
2198 p = f;
2199 zeropad = (f[1] == '0');
2200 f = parse_format_flags(f, &width, &precision,
2201 &longflag, &longlongflag, &size_tflag);
2202 switch (*f) {
2203 case 'c':
2204 {
2205 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002206 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002207 n++;
2208 break;
2209 }
2210 case '%':
2211 n++;
2212 break;
2213 case 'i':
2214 case 'd':
2215 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2216 width, precision, *f);
2217 if (longflag)
2218 numprinted = sprintf(numberresult, fmt,
2219 va_arg(count, long));
2220#ifdef HAVE_LONG_LONG
2221 else if (longlongflag)
2222 numprinted = sprintf(numberresult, fmt,
2223 va_arg(count, PY_LONG_LONG));
2224#endif
2225 else if (size_tflag)
2226 numprinted = sprintf(numberresult, fmt,
2227 va_arg(count, Py_ssize_t));
2228 else
2229 numprinted = sprintf(numberresult, fmt,
2230 va_arg(count, int));
2231 n += numprinted;
2232 /* advance by +1 to skip over the '\0' */
2233 numberresult += (numprinted + 1);
2234 assert(*(numberresult - 1) == '\0');
2235 assert(*(numberresult - 2) != '\0');
2236 assert(numprinted >= 0);
2237 assert(numberresult <= numberresults + numbersize);
2238 break;
2239 case 'u':
2240 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2241 width, precision, 'u');
2242 if (longflag)
2243 numprinted = sprintf(numberresult, fmt,
2244 va_arg(count, unsigned long));
2245#ifdef HAVE_LONG_LONG
2246 else if (longlongflag)
2247 numprinted = sprintf(numberresult, fmt,
2248 va_arg(count, unsigned PY_LONG_LONG));
2249#endif
2250 else if (size_tflag)
2251 numprinted = sprintf(numberresult, fmt,
2252 va_arg(count, size_t));
2253 else
2254 numprinted = sprintf(numberresult, fmt,
2255 va_arg(count, unsigned int));
2256 n += numprinted;
2257 numberresult += (numprinted + 1);
2258 assert(*(numberresult - 1) == '\0');
2259 assert(*(numberresult - 2) != '\0');
2260 assert(numprinted >= 0);
2261 assert(numberresult <= numberresults + numbersize);
2262 break;
2263 case 'x':
2264 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2265 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2266 n += numprinted;
2267 numberresult += (numprinted + 1);
2268 assert(*(numberresult - 1) == '\0');
2269 assert(*(numberresult - 2) != '\0');
2270 assert(numprinted >= 0);
2271 assert(numberresult <= numberresults + numbersize);
2272 break;
2273 case 'p':
2274 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2275 /* %p is ill-defined: ensure leading 0x. */
2276 if (numberresult[1] == 'X')
2277 numberresult[1] = 'x';
2278 else if (numberresult[1] != 'x') {
2279 memmove(numberresult + 2, numberresult,
2280 strlen(numberresult) + 1);
2281 numberresult[0] = '0';
2282 numberresult[1] = 'x';
2283 numprinted += 2;
2284 }
2285 n += numprinted;
2286 numberresult += (numprinted + 1);
2287 assert(*(numberresult - 1) == '\0');
2288 assert(*(numberresult - 2) != '\0');
2289 assert(numprinted >= 0);
2290 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002291 break;
2292 case 's':
2293 {
2294 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002295 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002296 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2297 if (!str)
2298 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002299 /* since PyUnicode_DecodeUTF8 returns already flexible
2300 unicode objects, there is no need to call ready on them */
2301 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002302 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002303 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002304 /* Remember the str and switch to the next slot */
2305 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002306 break;
2307 }
2308 case 'U':
2309 {
2310 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002311 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002312 if (PyUnicode_READY(obj) == -1)
2313 goto fail;
2314 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002315 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002316 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002317 break;
2318 }
2319 case 'V':
2320 {
2321 PyObject *obj = va_arg(count, PyObject *);
2322 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002323 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002324 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002325 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002326 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002327 if (PyUnicode_READY(obj) == -1)
2328 goto fail;
2329 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002330 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002331 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002332 *callresult++ = NULL;
2333 }
2334 else {
2335 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2336 if (!str_obj)
2337 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002338 if (PyUnicode_READY(str_obj)) {
2339 Py_DECREF(str_obj);
2340 goto fail;
2341 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002342 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002343 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002344 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002345 *callresult++ = str_obj;
2346 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002347 break;
2348 }
2349 case 'S':
2350 {
2351 PyObject *obj = va_arg(count, PyObject *);
2352 PyObject *str;
2353 assert(obj);
2354 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002355 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002356 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002357 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002358 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002359 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002360 /* Remember the str and switch to the next slot */
2361 *callresult++ = str;
2362 break;
2363 }
2364 case 'R':
2365 {
2366 PyObject *obj = va_arg(count, PyObject *);
2367 PyObject *repr;
2368 assert(obj);
2369 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002370 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002371 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002372 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002373 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002374 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002375 /* Remember the repr and switch to the next slot */
2376 *callresult++ = repr;
2377 break;
2378 }
2379 case 'A':
2380 {
2381 PyObject *obj = va_arg(count, PyObject *);
2382 PyObject *ascii;
2383 assert(obj);
2384 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002385 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002386 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002387 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002388 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002389 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002390 /* Remember the repr and switch to the next slot */
2391 *callresult++ = ascii;
2392 break;
2393 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002394 default:
2395 /* if we stumble upon an unknown
2396 formatting code, copy the rest of
2397 the format string to the output
2398 string. (we cannot just skip the
2399 code, since there's no way to know
2400 what's in the argument list) */
2401 n += strlen(p);
2402 goto expand;
2403 }
2404 } else
2405 n++;
2406 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002407 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002408 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002409 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002410 we don't have to resize the string.
2411 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002412 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002413 if (!string)
2414 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002415 kind = PyUnicode_KIND(string);
2416 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002417 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002418 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002419
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002420 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002421 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002422 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002423
2424 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002425 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2426 /* checking for == because the last argument could be a empty
2427 string, which causes i to point to end, the assert at the end of
2428 the loop */
2429 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002430
Benjamin Peterson14339b62009-01-31 16:36:08 +00002431 switch (*f) {
2432 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002433 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002434 const int ordinal = va_arg(vargs, int);
2435 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002436 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002437 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002438 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002439 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002440 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002441 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002442 case 'p':
2443 /* unused, since we already have the result */
2444 if (*f == 'p')
2445 (void) va_arg(vargs, void *);
2446 else
2447 (void) va_arg(vargs, int);
2448 /* extract the result from numberresults and append. */
2449 for (; *numberresult; ++i, ++numberresult)
2450 PyUnicode_WRITE(kind, data, i, *numberresult);
2451 /* skip over the separating '\0' */
2452 assert(*numberresult == '\0');
2453 numberresult++;
2454 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002455 break;
2456 case 's':
2457 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002458 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002459 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002460 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002461 size = PyUnicode_GET_LENGTH(*callresult);
2462 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002463 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002464 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002465 /* We're done with the unicode()/repr() => forget it */
2466 Py_DECREF(*callresult);
2467 /* switch to next unicode()/repr() result */
2468 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002469 break;
2470 }
2471 case 'U':
2472 {
2473 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002474 Py_ssize_t size;
2475 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2476 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002477 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002478 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002479 break;
2480 }
2481 case 'V':
2482 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002483 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002484 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002485 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002486 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002487 size = PyUnicode_GET_LENGTH(obj);
2488 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002489 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002490 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002491 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002492 size = PyUnicode_GET_LENGTH(*callresult);
2493 assert(PyUnicode_KIND(*callresult) <=
2494 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002495 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002496 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002497 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002498 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002499 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002500 break;
2501 }
2502 case 'S':
2503 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002504 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002505 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002506 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002507 /* unused, since we already have the result */
2508 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002509 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002510 copy_characters(string, i, *callresult, 0, size);
2511 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002512 /* We're done with the unicode()/repr() => forget it */
2513 Py_DECREF(*callresult);
2514 /* switch to next unicode()/repr() result */
2515 ++callresult;
2516 break;
2517 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002518 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002519 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002520 break;
2521 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002522 for (; *p; ++p, ++i)
2523 PyUnicode_WRITE(kind, data, i, *p);
2524 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002525 goto end;
2526 }
Victor Stinner1205f272010-09-11 00:54:47 +00002527 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002528 else {
2529 assert(i < PyUnicode_GET_LENGTH(string));
2530 PyUnicode_WRITE(kind, data, i++, *f);
2531 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002532 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002533 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002534
Benjamin Peterson29060642009-01-31 22:14:21 +00002535 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002536 if (callresults)
2537 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002538 if (numberresults)
2539 PyObject_Free(numberresults);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002540 assert(_PyUnicode_CheckConsistency(string, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002541 return (PyObject *)string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002542 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002543 if (callresults) {
2544 PyObject **callresult2 = callresults;
2545 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002546 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002547 ++callresult2;
2548 }
2549 PyObject_Free(callresults);
2550 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002551 if (numberresults)
2552 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002553 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002554}
2555
Walter Dörwaldd2034312007-05-18 16:29:38 +00002556PyObject *
2557PyUnicode_FromFormat(const char *format, ...)
2558{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002559 PyObject* ret;
2560 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002561
2562#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002563 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002564#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002565 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002566#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002567 ret = PyUnicode_FromFormatV(format, vargs);
2568 va_end(vargs);
2569 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002570}
2571
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002572#ifdef HAVE_WCHAR_H
2573
Victor Stinner5593d8a2010-10-02 11:11:27 +00002574/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2575 convert a Unicode object to a wide character string.
2576
Victor Stinnerd88d9832011-09-06 02:00:05 +02002577 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002578 character) required to convert the unicode object. Ignore size argument.
2579
Victor Stinnerd88d9832011-09-06 02:00:05 +02002580 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002581 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002582 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002583static Py_ssize_t
Victor Stinner137c34c2010-09-29 10:25:54 +00002584unicode_aswidechar(PyUnicodeObject *unicode,
2585 wchar_t *w,
2586 Py_ssize_t size)
2587{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002588 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002589 const wchar_t *wstr;
2590
2591 wstr = PyUnicode_AsUnicodeAndSize((PyObject *)unicode, &res);
2592 if (wstr == NULL)
2593 return -1;
2594
Victor Stinner5593d8a2010-10-02 11:11:27 +00002595 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002596 if (size > res)
2597 size = res + 1;
2598 else
2599 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002600 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002601 return res;
2602 }
2603 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002604 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002605}
2606
2607Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002608PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002609 wchar_t *w,
2610 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002611{
2612 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002613 PyErr_BadInternalCall();
2614 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002615 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002616 return unicode_aswidechar((PyUnicodeObject*)unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002617}
2618
Victor Stinner137c34c2010-09-29 10:25:54 +00002619wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002620PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002621 Py_ssize_t *size)
2622{
2623 wchar_t* buffer;
2624 Py_ssize_t buflen;
2625
2626 if (unicode == NULL) {
2627 PyErr_BadInternalCall();
2628 return NULL;
2629 }
2630
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002631 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002632 if (buflen == -1)
2633 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002634 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002635 PyErr_NoMemory();
2636 return NULL;
2637 }
2638
Victor Stinner137c34c2010-09-29 10:25:54 +00002639 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2640 if (buffer == NULL) {
2641 PyErr_NoMemory();
2642 return NULL;
2643 }
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002644 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002645 if (buflen == -1)
2646 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002647 if (size != NULL)
2648 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002649 return buffer;
2650}
2651
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002652#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002653
Alexander Belopolsky40018472011-02-26 01:02:56 +00002654PyObject *
2655PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002656{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002657 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002658 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002659 PyErr_SetString(PyExc_ValueError,
2660 "chr() arg not in range(0x110000)");
2661 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002662 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002663
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002664 if (ordinal < 256)
2665 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002666
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002667 v = PyUnicode_New(1, ordinal);
2668 if (v == NULL)
2669 return NULL;
2670 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002671 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002672 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002673}
2674
Alexander Belopolsky40018472011-02-26 01:02:56 +00002675PyObject *
2676PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002677{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002678 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002679 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002680 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002681 if (PyUnicode_READY(obj))
2682 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002683 Py_INCREF(obj);
2684 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002685 }
2686 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002687 /* For a Unicode subtype that's not a Unicode object,
2688 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002689 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002690 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002691 PyErr_Format(PyExc_TypeError,
2692 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002693 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002694 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002695}
2696
Alexander Belopolsky40018472011-02-26 01:02:56 +00002697PyObject *
2698PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002699 const char *encoding,
2700 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002701{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002702 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002703 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002704
Guido van Rossumd57fd912000-03-10 22:53:23 +00002705 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002706 PyErr_BadInternalCall();
2707 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002708 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002709
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002710 /* Decoding bytes objects is the most common case and should be fast */
2711 if (PyBytes_Check(obj)) {
2712 if (PyBytes_GET_SIZE(obj) == 0) {
2713 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002714 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002715 }
2716 else {
2717 v = PyUnicode_Decode(
2718 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2719 encoding, errors);
2720 }
2721 return v;
2722 }
2723
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002724 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002725 PyErr_SetString(PyExc_TypeError,
2726 "decoding str is not supported");
2727 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002728 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002729
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002730 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2731 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2732 PyErr_Format(PyExc_TypeError,
2733 "coercing to str: need bytes, bytearray "
2734 "or buffer-like object, %.80s found",
2735 Py_TYPE(obj)->tp_name);
2736 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002737 }
Tim Petersced69f82003-09-16 20:30:58 +00002738
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002739 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002740 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002741 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002742 }
Tim Petersced69f82003-09-16 20:30:58 +00002743 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002744 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002745
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002746 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002747 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002748}
2749
Victor Stinner600d3be2010-06-10 12:00:55 +00002750/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002751 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2752 1 on success. */
2753static int
2754normalize_encoding(const char *encoding,
2755 char *lower,
2756 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002757{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002758 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002759 char *l;
2760 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002761
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002762 e = encoding;
2763 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002764 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002765 while (*e) {
2766 if (l == l_end)
2767 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002768 if (Py_ISUPPER(*e)) {
2769 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002770 }
2771 else if (*e == '_') {
2772 *l++ = '-';
2773 e++;
2774 }
2775 else {
2776 *l++ = *e++;
2777 }
2778 }
2779 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002780 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002781}
2782
Alexander Belopolsky40018472011-02-26 01:02:56 +00002783PyObject *
2784PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002785 Py_ssize_t size,
2786 const char *encoding,
2787 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002788{
2789 PyObject *buffer = NULL, *unicode;
2790 Py_buffer info;
2791 char lower[11]; /* Enough for any encoding shortcut */
2792
2793 if (encoding == NULL)
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002794 return PyUnicode_DecodeUTF8(s, size, errors);
Fred Drakee4315f52000-05-09 19:53:39 +00002795
2796 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002797 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002798 if ((strcmp(lower, "utf-8") == 0) ||
2799 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002800 return PyUnicode_DecodeUTF8(s, size, errors);
2801 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002802 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002803 (strcmp(lower, "iso-8859-1") == 0))
2804 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002805#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002806 else if (strcmp(lower, "mbcs") == 0)
2807 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002808#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002809 else if (strcmp(lower, "ascii") == 0)
2810 return PyUnicode_DecodeASCII(s, size, errors);
2811 else if (strcmp(lower, "utf-16") == 0)
2812 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2813 else if (strcmp(lower, "utf-32") == 0)
2814 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2815 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002816
2817 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002818 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002819 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002820 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002821 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002822 if (buffer == NULL)
2823 goto onError;
2824 unicode = PyCodec_Decode(buffer, encoding, errors);
2825 if (unicode == NULL)
2826 goto onError;
2827 if (!PyUnicode_Check(unicode)) {
2828 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002829 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002830 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002831 Py_DECREF(unicode);
2832 goto onError;
2833 }
2834 Py_DECREF(buffer);
Victor Stinner17efeed2011-10-04 20:05:46 +02002835#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002836 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002837 Py_DECREF(unicode);
2838 return NULL;
2839 }
Victor Stinner17efeed2011-10-04 20:05:46 +02002840#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002841 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00002842 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002843
Benjamin Peterson29060642009-01-31 22:14:21 +00002844 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002845 Py_XDECREF(buffer);
2846 return NULL;
2847}
2848
Alexander Belopolsky40018472011-02-26 01:02:56 +00002849PyObject *
2850PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002851 const char *encoding,
2852 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002853{
2854 PyObject *v;
2855
2856 if (!PyUnicode_Check(unicode)) {
2857 PyErr_BadArgument();
2858 goto onError;
2859 }
2860
2861 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002862 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002863
2864 /* Decode via the codec registry */
2865 v = PyCodec_Decode(unicode, encoding, errors);
2866 if (v == NULL)
2867 goto onError;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002868 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002869 return v;
2870
Benjamin Peterson29060642009-01-31 22:14:21 +00002871 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002872 return NULL;
2873}
2874
Alexander Belopolsky40018472011-02-26 01:02:56 +00002875PyObject *
2876PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002877 const char *encoding,
2878 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002879{
2880 PyObject *v;
2881
2882 if (!PyUnicode_Check(unicode)) {
2883 PyErr_BadArgument();
2884 goto onError;
2885 }
2886
2887 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002888 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002889
2890 /* Decode via the codec registry */
2891 v = PyCodec_Decode(unicode, encoding, errors);
2892 if (v == NULL)
2893 goto onError;
2894 if (!PyUnicode_Check(v)) {
2895 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002896 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002897 Py_TYPE(v)->tp_name);
2898 Py_DECREF(v);
2899 goto onError;
2900 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002901 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002902 return v;
2903
Benjamin Peterson29060642009-01-31 22:14:21 +00002904 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002905 return NULL;
2906}
2907
Alexander Belopolsky40018472011-02-26 01:02:56 +00002908PyObject *
2909PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002910 Py_ssize_t size,
2911 const char *encoding,
2912 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002913{
2914 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002915
Guido van Rossumd57fd912000-03-10 22:53:23 +00002916 unicode = PyUnicode_FromUnicode(s, size);
2917 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002918 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002919 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
2920 Py_DECREF(unicode);
2921 return v;
2922}
2923
Alexander Belopolsky40018472011-02-26 01:02:56 +00002924PyObject *
2925PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002926 const char *encoding,
2927 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002928{
2929 PyObject *v;
2930
2931 if (!PyUnicode_Check(unicode)) {
2932 PyErr_BadArgument();
2933 goto onError;
2934 }
2935
2936 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002937 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002938
2939 /* Encode via the codec registry */
2940 v = PyCodec_Encode(unicode, encoding, errors);
2941 if (v == NULL)
2942 goto onError;
2943 return v;
2944
Benjamin Peterson29060642009-01-31 22:14:21 +00002945 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002946 return NULL;
2947}
2948
Victor Stinnerad158722010-10-27 00:25:46 +00002949PyObject *
2950PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00002951{
Victor Stinner99b95382011-07-04 14:23:54 +02002952#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00002953 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
2954 PyUnicode_GET_SIZE(unicode),
2955 NULL);
2956#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002957 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00002958#else
Victor Stinner793b5312011-04-27 00:24:21 +02002959 PyInterpreterState *interp = PyThreadState_GET()->interp;
2960 /* Bootstrap check: if the filesystem codec is implemented in Python, we
2961 cannot use it to encode and decode filenames before it is loaded. Load
2962 the Python codec requires to encode at least its own filename. Use the C
2963 version of the locale codec until the codec registry is initialized and
2964 the Python codec is loaded.
2965
2966 Py_FileSystemDefaultEncoding is shared between all interpreters, we
2967 cannot only rely on it: check also interp->fscodec_initialized for
2968 subinterpreters. */
2969 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00002970 return PyUnicode_AsEncodedString(unicode,
2971 Py_FileSystemDefaultEncoding,
2972 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00002973 }
2974 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002975 /* locale encoding with surrogateescape */
2976 wchar_t *wchar;
2977 char *bytes;
2978 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00002979 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002980
2981 wchar = PyUnicode_AsWideCharString(unicode, NULL);
2982 if (wchar == NULL)
2983 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00002984 bytes = _Py_wchar2char(wchar, &error_pos);
2985 if (bytes == NULL) {
2986 if (error_pos != (size_t)-1) {
2987 char *errmsg = strerror(errno);
2988 PyObject *exc = NULL;
2989 if (errmsg == NULL)
2990 errmsg = "Py_wchar2char() failed";
2991 raise_encode_exception(&exc,
2992 "filesystemencoding",
2993 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
2994 error_pos, error_pos+1,
2995 errmsg);
2996 Py_XDECREF(exc);
2997 }
2998 else
2999 PyErr_NoMemory();
3000 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003001 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003002 }
3003 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003004
3005 bytes_obj = PyBytes_FromString(bytes);
3006 PyMem_Free(bytes);
3007 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003008 }
Victor Stinnerad158722010-10-27 00:25:46 +00003009#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003010}
3011
Alexander Belopolsky40018472011-02-26 01:02:56 +00003012PyObject *
3013PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003014 const char *encoding,
3015 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003016{
3017 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003018 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003019
Guido van Rossumd57fd912000-03-10 22:53:23 +00003020 if (!PyUnicode_Check(unicode)) {
3021 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003022 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003023 }
Fred Drakee4315f52000-05-09 19:53:39 +00003024
Victor Stinner2f283c22011-03-02 01:21:46 +00003025 if (encoding == NULL) {
3026 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003027 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003028 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003029 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner2f283c22011-03-02 01:21:46 +00003030 }
Fred Drakee4315f52000-05-09 19:53:39 +00003031
3032 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003033 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003034 if ((strcmp(lower, "utf-8") == 0) ||
3035 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003036 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003037 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003038 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003039 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003040 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003041 }
Victor Stinner37296e82010-06-10 13:36:23 +00003042 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003043 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003044 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003045 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003046#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003047 else if (strcmp(lower, "mbcs") == 0)
3048 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3049 PyUnicode_GET_SIZE(unicode),
3050 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003051#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003052 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003053 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003054 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003055
3056 /* Encode via the codec registry */
3057 v = PyCodec_Encode(unicode, encoding, errors);
3058 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003059 return NULL;
3060
3061 /* The normal path */
3062 if (PyBytes_Check(v))
3063 return v;
3064
3065 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003066 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003067 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003068 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003069
3070 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3071 "encoder %s returned bytearray instead of bytes",
3072 encoding);
3073 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003074 Py_DECREF(v);
3075 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003076 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003077
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003078 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3079 Py_DECREF(v);
3080 return b;
3081 }
3082
3083 PyErr_Format(PyExc_TypeError,
3084 "encoder did not return a bytes object (type=%.400s)",
3085 Py_TYPE(v)->tp_name);
3086 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003087 return NULL;
3088}
3089
Alexander Belopolsky40018472011-02-26 01:02:56 +00003090PyObject *
3091PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003092 const char *encoding,
3093 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003094{
3095 PyObject *v;
3096
3097 if (!PyUnicode_Check(unicode)) {
3098 PyErr_BadArgument();
3099 goto onError;
3100 }
3101
3102 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003103 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003104
3105 /* Encode via the codec registry */
3106 v = PyCodec_Encode(unicode, encoding, errors);
3107 if (v == NULL)
3108 goto onError;
3109 if (!PyUnicode_Check(v)) {
3110 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003111 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003112 Py_TYPE(v)->tp_name);
3113 Py_DECREF(v);
3114 goto onError;
3115 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003116 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003117
Benjamin Peterson29060642009-01-31 22:14:21 +00003118 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003119 return NULL;
3120}
3121
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003122PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003123PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003124 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003125 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3126}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003127
Christian Heimes5894ba72007-11-04 11:43:14 +00003128PyObject*
3129PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3130{
Victor Stinner99b95382011-07-04 14:23:54 +02003131#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003132 return PyUnicode_DecodeMBCS(s, size, NULL);
3133#elif defined(__APPLE__)
3134 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3135#else
Victor Stinner793b5312011-04-27 00:24:21 +02003136 PyInterpreterState *interp = PyThreadState_GET()->interp;
3137 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3138 cannot use it to encode and decode filenames before it is loaded. Load
3139 the Python codec requires to encode at least its own filename. Use the C
3140 version of the locale codec until the codec registry is initialized and
3141 the Python codec is loaded.
3142
3143 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3144 cannot only rely on it: check also interp->fscodec_initialized for
3145 subinterpreters. */
3146 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003147 return PyUnicode_Decode(s, size,
3148 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003149 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003150 }
3151 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003152 /* locale encoding with surrogateescape */
3153 wchar_t *wchar;
3154 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003155 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003156
3157 if (s[size] != '\0' || size != strlen(s)) {
3158 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3159 return NULL;
3160 }
3161
Victor Stinner168e1172010-10-16 23:16:16 +00003162 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003163 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003164 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003165
Victor Stinner168e1172010-10-16 23:16:16 +00003166 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003167 PyMem_Free(wchar);
3168 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003169 }
Victor Stinnerad158722010-10-27 00:25:46 +00003170#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003171}
3172
Martin v. Löwis011e8422009-05-05 04:43:17 +00003173
3174int
3175PyUnicode_FSConverter(PyObject* arg, void* addr)
3176{
3177 PyObject *output = NULL;
3178 Py_ssize_t size;
3179 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003180 if (arg == NULL) {
3181 Py_DECREF(*(PyObject**)addr);
3182 return 1;
3183 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003184 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003185 output = arg;
3186 Py_INCREF(output);
3187 }
3188 else {
3189 arg = PyUnicode_FromObject(arg);
3190 if (!arg)
3191 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003192 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003193 Py_DECREF(arg);
3194 if (!output)
3195 return 0;
3196 if (!PyBytes_Check(output)) {
3197 Py_DECREF(output);
3198 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3199 return 0;
3200 }
3201 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003202 size = PyBytes_GET_SIZE(output);
3203 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003204 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003205 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003206 Py_DECREF(output);
3207 return 0;
3208 }
3209 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003210 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003211}
3212
3213
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003214int
3215PyUnicode_FSDecoder(PyObject* arg, void* addr)
3216{
3217 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003218 if (arg == NULL) {
3219 Py_DECREF(*(PyObject**)addr);
3220 return 1;
3221 }
3222 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003223 if (PyUnicode_READY(arg))
3224 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003225 output = arg;
3226 Py_INCREF(output);
3227 }
3228 else {
3229 arg = PyBytes_FromObject(arg);
3230 if (!arg)
3231 return 0;
3232 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3233 PyBytes_GET_SIZE(arg));
3234 Py_DECREF(arg);
3235 if (!output)
3236 return 0;
3237 if (!PyUnicode_Check(output)) {
3238 Py_DECREF(output);
3239 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3240 return 0;
3241 }
3242 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003243 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
3244 PyUnicode_GET_LENGTH(output), 0, 1)) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003245 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3246 Py_DECREF(output);
3247 return 0;
3248 }
3249 *(PyObject**)addr = output;
3250 return Py_CLEANUP_SUPPORTED;
3251}
3252
3253
Martin v. Löwis5b222132007-06-10 09:51:05 +00003254char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003255PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003256{
Christian Heimesf3863112007-11-22 07:46:41 +00003257 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003258 PyUnicodeObject *u = (PyUnicodeObject *)unicode;
3259
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003260 if (!PyUnicode_Check(unicode)) {
3261 PyErr_BadArgument();
3262 return NULL;
3263 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003264 if (PyUnicode_READY(u) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003265 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003266
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003267 if (PyUnicode_UTF8(unicode) == NULL) {
3268 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003269 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3270 if (bytes == NULL)
3271 return NULL;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003272 _PyUnicode_UTF8(u) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3273 if (_PyUnicode_UTF8(u) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003274 Py_DECREF(bytes);
3275 return NULL;
3276 }
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003277 _PyUnicode_UTF8_LENGTH(u) = PyBytes_GET_SIZE(bytes);
3278 Py_MEMCPY(_PyUnicode_UTF8(u), PyBytes_AS_STRING(bytes), _PyUnicode_UTF8_LENGTH(u) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003279 Py_DECREF(bytes);
3280 }
3281
3282 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003283 *psize = PyUnicode_UTF8_LENGTH(unicode);
3284 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003285}
3286
3287char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003288PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003289{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003290 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3291}
3292
3293#ifdef Py_DEBUG
3294int unicode_as_unicode_calls = 0;
3295#endif
3296
3297
3298Py_UNICODE *
3299PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3300{
3301 PyUnicodeObject *u;
3302 const unsigned char *one_byte;
3303#if SIZEOF_WCHAR_T == 4
3304 const Py_UCS2 *two_bytes;
3305#else
3306 const Py_UCS4 *four_bytes;
3307 const Py_UCS4 *ucs4_end;
3308 Py_ssize_t num_surrogates;
3309#endif
3310 wchar_t *w;
3311 wchar_t *wchar_end;
3312
3313 if (!PyUnicode_Check(unicode)) {
3314 PyErr_BadArgument();
3315 return NULL;
3316 }
3317 u = (PyUnicodeObject*)unicode;
3318 if (_PyUnicode_WSTR(u) == NULL) {
3319 /* Non-ASCII compact unicode object */
3320 assert(_PyUnicode_KIND(u) != 0);
3321 assert(PyUnicode_IS_READY(u));
3322
3323#ifdef Py_DEBUG
3324 ++unicode_as_unicode_calls;
3325#endif
3326
3327 if (PyUnicode_KIND(u) == PyUnicode_4BYTE_KIND) {
3328#if SIZEOF_WCHAR_T == 2
3329 four_bytes = PyUnicode_4BYTE_DATA(u);
3330 ucs4_end = four_bytes + _PyUnicode_LENGTH(u);
3331 num_surrogates = 0;
3332
3333 for (; four_bytes < ucs4_end; ++four_bytes) {
3334 if (*four_bytes > 0xFFFF)
3335 ++num_surrogates;
3336 }
3337
3338 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(
3339 sizeof(wchar_t) * (_PyUnicode_LENGTH(u) + 1 + num_surrogates));
3340 if (!_PyUnicode_WSTR(u)) {
3341 PyErr_NoMemory();
3342 return NULL;
3343 }
3344 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u) + num_surrogates;
3345
3346 w = _PyUnicode_WSTR(u);
3347 wchar_end = w + _PyUnicode_WSTR_LENGTH(u);
3348 four_bytes = PyUnicode_4BYTE_DATA(u);
3349 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3350 if (*four_bytes > 0xFFFF) {
3351 /* encode surrogate pair in this case */
3352 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3353 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3354 }
3355 else
3356 *w = *four_bytes;
3357
3358 if (w > wchar_end) {
3359 assert(0 && "Miscalculated string end");
3360 }
3361 }
3362 *w = 0;
3363#else
3364 /* sizeof(wchar_t) == 4 */
3365 Py_FatalError("Impossible unicode object state, wstr and str "
3366 "should share memory already.");
3367 return NULL;
3368#endif
3369 }
3370 else {
3371 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3372 (_PyUnicode_LENGTH(u) + 1));
3373 if (!_PyUnicode_WSTR(u)) {
3374 PyErr_NoMemory();
3375 return NULL;
3376 }
3377 if (!PyUnicode_IS_COMPACT_ASCII(u))
3378 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u);
3379 w = _PyUnicode_WSTR(u);
3380 wchar_end = w + _PyUnicode_LENGTH(u);
3381
3382 if (PyUnicode_KIND(u) == PyUnicode_1BYTE_KIND) {
3383 one_byte = PyUnicode_1BYTE_DATA(u);
3384 for (; w < wchar_end; ++one_byte, ++w)
3385 *w = *one_byte;
3386 /* null-terminate the wstr */
3387 *w = 0;
3388 }
3389 else if (PyUnicode_KIND(u) == PyUnicode_2BYTE_KIND) {
3390#if SIZEOF_WCHAR_T == 4
3391 two_bytes = PyUnicode_2BYTE_DATA(u);
3392 for (; w < wchar_end; ++two_bytes, ++w)
3393 *w = *two_bytes;
3394 /* null-terminate the wstr */
3395 *w = 0;
3396#else
3397 /* sizeof(wchar_t) == 2 */
3398 PyObject_FREE(_PyUnicode_WSTR(u));
3399 _PyUnicode_WSTR(u) = NULL;
3400 Py_FatalError("Impossible unicode object state, wstr "
3401 "and str should share memory already.");
3402 return NULL;
3403#endif
3404 }
3405 else {
3406 assert(0 && "This should never happen.");
3407 }
3408 }
3409 }
3410 if (size != NULL)
3411 *size = PyUnicode_WSTR_LENGTH(u);
3412 return _PyUnicode_WSTR(u);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003413}
3414
Alexander Belopolsky40018472011-02-26 01:02:56 +00003415Py_UNICODE *
3416PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003417{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003418 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003419}
3420
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003421
Alexander Belopolsky40018472011-02-26 01:02:56 +00003422Py_ssize_t
3423PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003424{
3425 if (!PyUnicode_Check(unicode)) {
3426 PyErr_BadArgument();
3427 goto onError;
3428 }
3429 return PyUnicode_GET_SIZE(unicode);
3430
Benjamin Peterson29060642009-01-31 22:14:21 +00003431 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003432 return -1;
3433}
3434
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003435Py_ssize_t
3436PyUnicode_GetLength(PyObject *unicode)
3437{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003438 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003439 PyErr_BadArgument();
3440 return -1;
3441 }
3442
3443 return PyUnicode_GET_LENGTH(unicode);
3444}
3445
3446Py_UCS4
3447PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3448{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003449 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3450 PyErr_BadArgument();
3451 return (Py_UCS4)-1;
3452 }
3453 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3454 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003455 return (Py_UCS4)-1;
3456 }
3457 return PyUnicode_READ_CHAR(unicode, index);
3458}
3459
3460int
3461PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3462{
3463 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003464 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003465 return -1;
3466 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003467 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3468 PyErr_SetString(PyExc_IndexError, "string index out of range");
3469 return -1;
3470 }
3471 if (_PyUnicode_Dirty(unicode))
3472 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003473 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3474 index, ch);
3475 return 0;
3476}
3477
Alexander Belopolsky40018472011-02-26 01:02:56 +00003478const char *
3479PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003480{
Victor Stinner42cb4622010-09-01 19:39:01 +00003481 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003482}
3483
Victor Stinner554f3f02010-06-16 23:33:54 +00003484/* create or adjust a UnicodeDecodeError */
3485static void
3486make_decode_exception(PyObject **exceptionObject,
3487 const char *encoding,
3488 const char *input, Py_ssize_t length,
3489 Py_ssize_t startpos, Py_ssize_t endpos,
3490 const char *reason)
3491{
3492 if (*exceptionObject == NULL) {
3493 *exceptionObject = PyUnicodeDecodeError_Create(
3494 encoding, input, length, startpos, endpos, reason);
3495 }
3496 else {
3497 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3498 goto onError;
3499 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3500 goto onError;
3501 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3502 goto onError;
3503 }
3504 return;
3505
3506onError:
3507 Py_DECREF(*exceptionObject);
3508 *exceptionObject = NULL;
3509}
3510
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003511/* error handling callback helper:
3512 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003513 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003514 and adjust various state variables.
3515 return 0 on success, -1 on error
3516*/
3517
Alexander Belopolsky40018472011-02-26 01:02:56 +00003518static int
3519unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003520 const char *encoding, const char *reason,
3521 const char **input, const char **inend, Py_ssize_t *startinpos,
3522 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3523 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003524{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003525 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003526
3527 PyObject *restuple = NULL;
3528 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003529 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003530 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003531 Py_ssize_t requiredsize;
3532 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003533 const Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003534 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003535 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003536 int res = -1;
3537
3538 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003539 *errorHandler = PyCodec_LookupError(errors);
3540 if (*errorHandler == NULL)
3541 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003542 }
3543
Victor Stinner554f3f02010-06-16 23:33:54 +00003544 make_decode_exception(exceptionObject,
3545 encoding,
3546 *input, *inend - *input,
3547 *startinpos, *endinpos,
3548 reason);
3549 if (*exceptionObject == NULL)
3550 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003551
3552 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3553 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003554 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003555 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003556 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003557 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003558 }
3559 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003560 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003561
3562 /* Copy back the bytes variables, which might have been modified by the
3563 callback */
3564 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3565 if (!inputobj)
3566 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003567 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003568 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003569 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003570 *input = PyBytes_AS_STRING(inputobj);
3571 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003572 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003573 /* we can DECREF safely, as the exception has another reference,
3574 so the object won't go away. */
3575 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003576
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003577 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003578 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003579 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003580 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3581 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003582 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003583
3584 /* need more space? (at least enough for what we
3585 have+the replacement+the rest of the string (starting
3586 at the new input position), so we won't have to check space
3587 when there are no errors in the rest of the string) */
3588 repptr = PyUnicode_AS_UNICODE(repunicode);
3589 repsize = PyUnicode_GET_SIZE(repunicode);
3590 requiredsize = *outpos + repsize + insize-newpos;
3591 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003592 if (requiredsize<2*outsize)
3593 requiredsize = 2*outsize;
Victor Stinnerfe226c02011-10-03 03:52:20 +02003594 if (PyUnicode_Resize((PyObject**)output, requiredsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003595 goto onError;
3596 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003597 }
3598 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003599 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003600 Py_UNICODE_COPY(*outptr, repptr, repsize);
3601 *outptr += repsize;
3602 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003603
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003604 /* we made it! */
3605 res = 0;
3606
Benjamin Peterson29060642009-01-31 22:14:21 +00003607 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003608 Py_XDECREF(restuple);
3609 return res;
3610}
3611
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003612/* --- UTF-7 Codec -------------------------------------------------------- */
3613
Antoine Pitrou244651a2009-05-04 18:56:13 +00003614/* See RFC2152 for details. We encode conservatively and decode liberally. */
3615
3616/* Three simple macros defining base-64. */
3617
3618/* Is c a base-64 character? */
3619
3620#define IS_BASE64(c) \
3621 (((c) >= 'A' && (c) <= 'Z') || \
3622 ((c) >= 'a' && (c) <= 'z') || \
3623 ((c) >= '0' && (c) <= '9') || \
3624 (c) == '+' || (c) == '/')
3625
3626/* given that c is a base-64 character, what is its base-64 value? */
3627
3628#define FROM_BASE64(c) \
3629 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3630 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3631 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3632 (c) == '+' ? 62 : 63)
3633
3634/* What is the base-64 character of the bottom 6 bits of n? */
3635
3636#define TO_BASE64(n) \
3637 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3638
3639/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3640 * decoded as itself. We are permissive on decoding; the only ASCII
3641 * byte not decoding to itself is the + which begins a base64
3642 * string. */
3643
3644#define DECODE_DIRECT(c) \
3645 ((c) <= 127 && (c) != '+')
3646
3647/* The UTF-7 encoder treats ASCII characters differently according to
3648 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3649 * the above). See RFC2152. This array identifies these different
3650 * sets:
3651 * 0 : "Set D"
3652 * alphanumeric and '(),-./:?
3653 * 1 : "Set O"
3654 * !"#$%&*;<=>@[]^_`{|}
3655 * 2 : "whitespace"
3656 * ht nl cr sp
3657 * 3 : special (must be base64 encoded)
3658 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3659 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003660
Tim Petersced69f82003-09-16 20:30:58 +00003661static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003662char utf7_category[128] = {
3663/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3664 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3665/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3666 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3667/* sp ! " # $ % & ' ( ) * + , - . / */
3668 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3669/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3670 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3671/* @ A B C D E F G H I J K L M N O */
3672 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3673/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3674 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3675/* ` a b c d e f g h i j k l m n o */
3676 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3677/* p q r s t u v w x y z { | } ~ del */
3678 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003679};
3680
Antoine Pitrou244651a2009-05-04 18:56:13 +00003681/* ENCODE_DIRECT: this character should be encoded as itself. The
3682 * answer depends on whether we are encoding set O as itself, and also
3683 * on whether we are encoding whitespace as itself. RFC2152 makes it
3684 * clear that the answers to these questions vary between
3685 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003686
Antoine Pitrou244651a2009-05-04 18:56:13 +00003687#define ENCODE_DIRECT(c, directO, directWS) \
3688 ((c) < 128 && (c) > 0 && \
3689 ((utf7_category[(c)] == 0) || \
3690 (directWS && (utf7_category[(c)] == 2)) || \
3691 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003692
Alexander Belopolsky40018472011-02-26 01:02:56 +00003693PyObject *
3694PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003695 Py_ssize_t size,
3696 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003697{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003698 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3699}
3700
Antoine Pitrou244651a2009-05-04 18:56:13 +00003701/* The decoder. The only state we preserve is our read position,
3702 * i.e. how many characters we have consumed. So if we end in the
3703 * middle of a shift sequence we have to back off the read position
3704 * and the output to the beginning of the sequence, otherwise we lose
3705 * all the shift state (seen bits, number of bits seen, high
3706 * surrogate). */
3707
Alexander Belopolsky40018472011-02-26 01:02:56 +00003708PyObject *
3709PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003710 Py_ssize_t size,
3711 const char *errors,
3712 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003713{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003714 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003715 Py_ssize_t startinpos;
3716 Py_ssize_t endinpos;
3717 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003718 const char *e;
3719 PyUnicodeObject *unicode;
3720 Py_UNICODE *p;
3721 const char *errmsg = "";
3722 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003723 Py_UNICODE *shiftOutStart;
3724 unsigned int base64bits = 0;
3725 unsigned long base64buffer = 0;
3726 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003727 PyObject *errorHandler = NULL;
3728 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003729
3730 unicode = _PyUnicode_New(size);
3731 if (!unicode)
3732 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003733 if (size == 0) {
3734 if (consumed)
3735 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003736 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003737 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003738
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003739 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitrou244651a2009-05-04 18:56:13 +00003740 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003741 e = s + size;
3742
3743 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003744 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003745 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003746 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003747
Antoine Pitrou244651a2009-05-04 18:56:13 +00003748 if (inShift) { /* in a base-64 section */
3749 if (IS_BASE64(ch)) { /* consume a base-64 character */
3750 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3751 base64bits += 6;
3752 s++;
3753 if (base64bits >= 16) {
3754 /* we have enough bits for a UTF-16 value */
3755 Py_UNICODE outCh = (Py_UNICODE)
3756 (base64buffer >> (base64bits-16));
3757 base64bits -= 16;
3758 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3759 if (surrogate) {
3760 /* expecting a second surrogate */
3761 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3762#ifdef Py_UNICODE_WIDE
3763 *p++ = (((surrogate & 0x3FF)<<10)
3764 | (outCh & 0x3FF)) + 0x10000;
3765#else
3766 *p++ = surrogate;
3767 *p++ = outCh;
3768#endif
3769 surrogate = 0;
3770 }
3771 else {
3772 surrogate = 0;
3773 errmsg = "second surrogate missing";
3774 goto utf7Error;
3775 }
3776 }
3777 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3778 /* first surrogate */
3779 surrogate = outCh;
3780 }
3781 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3782 errmsg = "unexpected second surrogate";
3783 goto utf7Error;
3784 }
3785 else {
3786 *p++ = outCh;
3787 }
3788 }
3789 }
3790 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003791 inShift = 0;
3792 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003793 if (surrogate) {
3794 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003795 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003796 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003797 if (base64bits > 0) { /* left-over bits */
3798 if (base64bits >= 6) {
3799 /* We've seen at least one base-64 character */
3800 errmsg = "partial character in shift sequence";
3801 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003802 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003803 else {
3804 /* Some bits remain; they should be zero */
3805 if (base64buffer != 0) {
3806 errmsg = "non-zero padding bits in shift sequence";
3807 goto utf7Error;
3808 }
3809 }
3810 }
3811 if (ch != '-') {
3812 /* '-' is absorbed; other terminating
3813 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003814 *p++ = ch;
3815 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003816 }
3817 }
3818 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003819 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003820 s++; /* consume '+' */
3821 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003822 s++;
3823 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00003824 }
3825 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003826 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003827 shiftOutStart = p;
3828 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003829 }
3830 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003831 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003832 *p++ = ch;
3833 s++;
3834 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003835 else {
3836 startinpos = s-starts;
3837 s++;
3838 errmsg = "unexpected special character";
3839 goto utf7Error;
3840 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003841 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003842utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003843 outpos = p-PyUnicode_AS_UNICODE(unicode);
3844 endinpos = s-starts;
3845 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003846 errors, &errorHandler,
3847 "utf7", errmsg,
3848 &starts, &e, &startinpos, &endinpos, &exc, &s,
3849 &unicode, &outpos, &p))
3850 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003851 }
3852
Antoine Pitrou244651a2009-05-04 18:56:13 +00003853 /* end of string */
3854
3855 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3856 /* if we're in an inconsistent state, that's an error */
3857 if (surrogate ||
3858 (base64bits >= 6) ||
3859 (base64bits > 0 && base64buffer != 0)) {
3860 outpos = p-PyUnicode_AS_UNICODE(unicode);
3861 endinpos = size;
3862 if (unicode_decode_call_errorhandler(
3863 errors, &errorHandler,
3864 "utf7", "unterminated shift sequence",
3865 &starts, &e, &startinpos, &endinpos, &exc, &s,
3866 &unicode, &outpos, &p))
3867 goto onError;
3868 if (s < e)
3869 goto restart;
3870 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003871 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003872
3873 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003874 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003875 if (inShift) {
3876 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003877 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003878 }
3879 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003880 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003881 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003882 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003883
Victor Stinnerfe226c02011-10-03 03:52:20 +02003884 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003885 goto onError;
3886
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003887 Py_XDECREF(errorHandler);
3888 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02003889#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02003890 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003891 Py_DECREF(unicode);
3892 return NULL;
3893 }
Victor Stinner17efeed2011-10-04 20:05:46 +02003894#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003895 assert(_PyUnicode_CheckConsistency(unicode, 1));
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003896 return (PyObject *)unicode;
3897
Benjamin Peterson29060642009-01-31 22:14:21 +00003898 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003899 Py_XDECREF(errorHandler);
3900 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003901 Py_DECREF(unicode);
3902 return NULL;
3903}
3904
3905
Alexander Belopolsky40018472011-02-26 01:02:56 +00003906PyObject *
3907PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003908 Py_ssize_t size,
3909 int base64SetO,
3910 int base64WhiteSpace,
3911 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003912{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003913 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003914 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003915 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003916 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003917 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003918 unsigned int base64bits = 0;
3919 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003920 char * out;
3921 char * start;
3922
3923 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003924 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003925
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003926 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003927 return PyErr_NoMemory();
3928
Antoine Pitrou244651a2009-05-04 18:56:13 +00003929 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003930 if (v == NULL)
3931 return NULL;
3932
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003933 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003934 for (;i < size; ++i) {
3935 Py_UNICODE ch = s[i];
3936
Antoine Pitrou244651a2009-05-04 18:56:13 +00003937 if (inShift) {
3938 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
3939 /* shifting out */
3940 if (base64bits) { /* output remaining bits */
3941 *out++ = TO_BASE64(base64buffer << (6-base64bits));
3942 base64buffer = 0;
3943 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003944 }
3945 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003946 /* Characters not in the BASE64 set implicitly unshift the sequence
3947 so no '-' is required, except if the character is itself a '-' */
3948 if (IS_BASE64(ch) || ch == '-') {
3949 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003950 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003951 *out++ = (char) ch;
3952 }
3953 else {
3954 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00003955 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003956 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003957 else { /* not in a shift sequence */
3958 if (ch == '+') {
3959 *out++ = '+';
3960 *out++ = '-';
3961 }
3962 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
3963 *out++ = (char) ch;
3964 }
3965 else {
3966 *out++ = '+';
3967 inShift = 1;
3968 goto encode_char;
3969 }
3970 }
3971 continue;
3972encode_char:
3973#ifdef Py_UNICODE_WIDE
3974 if (ch >= 0x10000) {
3975 /* code first surrogate */
3976 base64bits += 16;
3977 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
3978 while (base64bits >= 6) {
3979 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
3980 base64bits -= 6;
3981 }
3982 /* prepare second surrogate */
3983 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
3984 }
3985#endif
3986 base64bits += 16;
3987 base64buffer = (base64buffer << 16) | ch;
3988 while (base64bits >= 6) {
3989 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
3990 base64bits -= 6;
3991 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00003992 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003993 if (base64bits)
3994 *out++= TO_BASE64(base64buffer << (6-base64bits) );
3995 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003996 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003997 if (_PyBytes_Resize(&v, out - start) < 0)
3998 return NULL;
3999 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004000}
4001
Antoine Pitrou244651a2009-05-04 18:56:13 +00004002#undef IS_BASE64
4003#undef FROM_BASE64
4004#undef TO_BASE64
4005#undef DECODE_DIRECT
4006#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004007
Guido van Rossumd57fd912000-03-10 22:53:23 +00004008/* --- UTF-8 Codec -------------------------------------------------------- */
4009
Tim Petersced69f82003-09-16 20:30:58 +00004010static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004011char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004012 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4013 illegal prefix. See RFC 3629 for details */
4014 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4015 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004016 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004017 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4018 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4019 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,
Ezio Melotti57221d02010-07-01 07:32:02 +00004021 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4022 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 +00004023 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4024 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004025 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4026 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4027 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4028 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4029 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 +00004030};
4031
Alexander Belopolsky40018472011-02-26 01:02:56 +00004032PyObject *
4033PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004034 Py_ssize_t size,
4035 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004036{
Walter Dörwald69652032004-09-07 20:24:22 +00004037 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4038}
4039
Antoine Pitrouab868312009-01-10 15:40:25 +00004040/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4041#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4042
4043/* Mask to quickly check whether a C 'long' contains a
4044 non-ASCII, UTF8-encoded char. */
4045#if (SIZEOF_LONG == 8)
4046# define ASCII_CHAR_MASK 0x8080808080808080L
4047#elif (SIZEOF_LONG == 4)
4048# define ASCII_CHAR_MASK 0x80808080L
4049#else
4050# error C 'long' size should be either 4 or 8!
4051#endif
4052
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004053/* Scans a UTF-8 string and returns the maximum character to be expected,
4054 the size of the decoded unicode string and if any major errors were
4055 encountered.
4056
4057 This function does check basic UTF-8 sanity, it does however NOT CHECK
4058 if the string contains surrogates, and if all continuation bytes are
4059 within the correct ranges, these checks are performed in
4060 PyUnicode_DecodeUTF8Stateful.
4061
4062 If it sets has_errors to 1, it means the value of unicode_size and max_char
4063 will be bogus and you should not rely on useful information in them.
4064 */
4065static Py_UCS4
4066utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
4067 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
4068 int *has_errors)
4069{
4070 Py_ssize_t n;
4071 Py_ssize_t char_count = 0;
4072 Py_UCS4 max_char = 127, new_max;
4073 Py_UCS4 upper_bound;
4074 const unsigned char *p = (const unsigned char *)s;
4075 const unsigned char *end = p + string_size;
4076 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
4077 int err = 0;
4078
4079 for (; p < end && !err; ++p, ++char_count) {
4080 /* Only check value if it's not a ASCII char... */
4081 if (*p < 0x80) {
4082 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4083 an explanation. */
4084 if (!((size_t) p & LONG_PTR_MASK)) {
4085 /* Help register allocation */
4086 register const unsigned char *_p = p;
4087 while (_p < aligned_end) {
4088 unsigned long value = *(unsigned long *) _p;
4089 if (value & ASCII_CHAR_MASK)
4090 break;
4091 _p += SIZEOF_LONG;
4092 char_count += SIZEOF_LONG;
4093 }
4094 p = _p;
4095 if (p == end)
4096 break;
4097 }
4098 }
4099 if (*p >= 0x80) {
4100 n = utf8_code_length[*p];
4101 new_max = max_char;
4102 switch (n) {
4103 /* invalid start byte */
4104 case 0:
4105 err = 1;
4106 break;
4107 case 2:
4108 /* Code points between 0x00FF and 0x07FF inclusive.
4109 Approximate the upper bound of the code point,
4110 if this flips over 255 we can be sure it will be more
4111 than 255 and the string will need 2 bytes per code coint,
4112 if it stays under or equal to 255, we can be sure 1 byte
4113 is enough.
4114 ((*p & 0b00011111) << 6) | 0b00111111 */
4115 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
4116 if (max_char < upper_bound)
4117 new_max = upper_bound;
4118 /* Ensure we track at least that we left ASCII space. */
4119 if (new_max < 128)
4120 new_max = 128;
4121 break;
4122 case 3:
4123 /* Between 0x0FFF and 0xFFFF inclusive, so values are
4124 always > 255 and <= 65535 and will always need 2 bytes. */
4125 if (max_char < 65535)
4126 new_max = 65535;
4127 break;
4128 case 4:
4129 /* Code point will be above 0xFFFF for sure in this case. */
4130 new_max = 65537;
4131 break;
4132 /* Internal error, this should be caught by the first if */
4133 case 1:
4134 default:
4135 assert(0 && "Impossible case in utf8_max_char_and_size");
4136 err = 1;
4137 }
4138 /* Instead of number of overall bytes for this code point,
Georg Brandl7597add2011-10-05 16:36:47 +02004139 n contains the number of following bytes: */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004140 --n;
4141 /* Check if the follow up chars are all valid continuation bytes */
4142 if (n >= 1) {
4143 const unsigned char *cont;
4144 if ((p + n) >= end) {
4145 if (consumed == 0)
4146 /* incomplete data, non-incremental decoding */
4147 err = 1;
4148 break;
4149 }
4150 for (cont = p + 1; cont < (p + n); ++cont) {
4151 if ((*cont & 0xc0) != 0x80) {
4152 err = 1;
4153 break;
4154 }
4155 }
4156 p += n;
4157 }
4158 else
4159 err = 1;
4160 max_char = new_max;
4161 }
4162 }
4163
4164 if (unicode_size)
4165 *unicode_size = char_count;
4166 if (has_errors)
4167 *has_errors = err;
4168 return max_char;
4169}
4170
4171/* Similar to PyUnicode_WRITE but can also write into wstr field
4172 of the legacy unicode representation */
4173#define WRITE_FLEXIBLE_OR_WSTR(kind, buf, index, value) \
4174 do { \
4175 const int k_ = (kind); \
4176 if (k_ == PyUnicode_WCHAR_KIND) \
4177 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
4178 else if (k_ == PyUnicode_1BYTE_KIND) \
4179 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
4180 else if (k_ == PyUnicode_2BYTE_KIND) \
4181 ((Py_UCS2 *)(buf))[(index)] = (Py_UCS2)(value); \
4182 else \
4183 ((Py_UCS4 *)(buf))[(index)] = (Py_UCS4)(value); \
4184 } while (0)
4185
Alexander Belopolsky40018472011-02-26 01:02:56 +00004186PyObject *
4187PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004188 Py_ssize_t size,
4189 const char *errors,
4190 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004191{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004192 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004193 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004194 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004195 Py_ssize_t startinpos;
4196 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004197 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004198 PyUnicodeObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004199 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004200 PyObject *errorHandler = NULL;
4201 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004202 Py_UCS4 maxchar = 0;
4203 Py_ssize_t unicode_size;
4204 Py_ssize_t i;
4205 int kind;
4206 void *data;
4207 int has_errors;
4208 Py_UNICODE *error_outptr;
4209#if SIZEOF_WCHAR_T == 2
4210 Py_ssize_t wchar_offset = 0;
4211#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004212
Walter Dörwald69652032004-09-07 20:24:22 +00004213 if (size == 0) {
4214 if (consumed)
4215 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004216 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004217 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004218 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
4219 consumed, &has_errors);
4220 if (has_errors) {
4221 unicode = _PyUnicode_New(size);
4222 if (!unicode)
4223 return NULL;
4224 kind = PyUnicode_WCHAR_KIND;
4225 data = PyUnicode_AS_UNICODE(unicode);
4226 assert(data != NULL);
4227 }
4228 else {
4229 unicode = (PyUnicodeObject *)PyUnicode_New(unicode_size, maxchar);
4230 if (!unicode)
4231 return NULL;
4232 /* When the string is ASCII only, just use memcpy and return.
4233 unicode_size may be != size if there is an incomplete UTF-8
4234 sequence at the end of the ASCII block. */
4235 if (maxchar < 128 && size == unicode_size) {
4236 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4237 return (PyObject *)unicode;
4238 }
4239 kind = PyUnicode_KIND(unicode);
4240 data = PyUnicode_DATA(unicode);
4241 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004242 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004243 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004244 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004245 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004246
4247 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004248 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004249
4250 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004251 /* Fast path for runs of ASCII characters. Given that common UTF-8
4252 input will consist of an overwhelming majority of ASCII
4253 characters, we try to optimize for this case by checking
4254 as many characters as a C 'long' can contain.
4255 First, check if we can do an aligned read, as most CPUs have
4256 a penalty for unaligned reads.
4257 */
4258 if (!((size_t) s & LONG_PTR_MASK)) {
4259 /* Help register allocation */
4260 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004261 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004262 while (_s < aligned_end) {
4263 /* Read a whole long at a time (either 4 or 8 bytes),
4264 and do a fast unrolled copy if it only contains ASCII
4265 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004266 unsigned long value = *(unsigned long *) _s;
4267 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004268 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004269 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+0, _s[0]);
4270 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+1, _s[1]);
4271 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+2, _s[2]);
4272 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004273#if (SIZEOF_LONG == 8)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004274 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+4, _s[4]);
4275 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+5, _s[5]);
4276 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+6, _s[6]);
4277 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004278#endif
4279 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004280 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004281 }
4282 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004283 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004284 if (s == e)
4285 break;
4286 ch = (unsigned char)*s;
4287 }
4288 }
4289
4290 if (ch < 0x80) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004291 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004292 s++;
4293 continue;
4294 }
4295
4296 n = utf8_code_length[ch];
4297
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004298 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004299 if (consumed)
4300 break;
4301 else {
4302 errmsg = "unexpected end of data";
4303 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004304 endinpos = startinpos+1;
4305 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4306 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004307 goto utf8Error;
4308 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004309 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004310
4311 switch (n) {
4312
4313 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004314 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004315 startinpos = s-starts;
4316 endinpos = startinpos+1;
4317 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004318
4319 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004320 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004321 startinpos = s-starts;
4322 endinpos = startinpos+1;
4323 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004324
4325 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004326 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004327 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004328 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004329 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004330 goto utf8Error;
4331 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004332 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004333 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004334 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004335 break;
4336
4337 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004338 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4339 will result in surrogates in range d800-dfff. Surrogates are
4340 not valid UTF-8 so they are rejected.
4341 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4342 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004343 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004344 (s[2] & 0xc0) != 0x80 ||
4345 ((unsigned char)s[0] == 0xE0 &&
4346 (unsigned char)s[1] < 0xA0) ||
4347 ((unsigned char)s[0] == 0xED &&
4348 (unsigned char)s[1] > 0x9F)) {
4349 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004350 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004351 endinpos = startinpos + 1;
4352
4353 /* if s[1] first two bits are 1 and 0, then the invalid
4354 continuation byte is s[2], so increment endinpos by 1,
4355 if not, s[1] is invalid and endinpos doesn't need to
4356 be incremented. */
4357 if ((s[1] & 0xC0) == 0x80)
4358 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004359 goto utf8Error;
4360 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004361 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004362 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004363 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004364 break;
4365
4366 case 4:
4367 if ((s[1] & 0xc0) != 0x80 ||
4368 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004369 (s[3] & 0xc0) != 0x80 ||
4370 ((unsigned char)s[0] == 0xF0 &&
4371 (unsigned char)s[1] < 0x90) ||
4372 ((unsigned char)s[0] == 0xF4 &&
4373 (unsigned char)s[1] > 0x8F)) {
4374 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004375 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004376 endinpos = startinpos + 1;
4377 if ((s[1] & 0xC0) == 0x80) {
4378 endinpos++;
4379 if ((s[2] & 0xC0) == 0x80)
4380 endinpos++;
4381 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004382 goto utf8Error;
4383 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004384 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004385 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4386 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4387
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004388 /* If the string is flexible or we have native UCS-4, write
4389 directly.. */
4390 if (sizeof(Py_UNICODE) > 2 || kind != PyUnicode_WCHAR_KIND)
4391 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Tim Petersced69f82003-09-16 20:30:58 +00004392
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004393 else {
4394 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00004395
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004396 /* translate from 10000..10FFFF to 0..FFFF */
4397 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00004398
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004399 /* high surrogate = top 10 bits added to D800 */
4400 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4401 (Py_UNICODE)(0xD800 + (ch >> 10)));
4402
4403 /* low surrogate = bottom 10 bits added to DC00 */
4404 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4405 (Py_UNICODE)(0xDC00 + (ch & 0x03FF)));
4406 }
4407#if SIZEOF_WCHAR_T == 2
4408 wchar_offset++;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004409#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004410 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004411 }
4412 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004413 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004414
Benjamin Peterson29060642009-01-31 22:14:21 +00004415 utf8Error:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004416 /* If this is not yet a resizable string, make it one.. */
4417 if (kind != PyUnicode_WCHAR_KIND) {
4418 const Py_UNICODE *u;
4419 PyUnicodeObject *new_unicode = _PyUnicode_New(size);
4420 if (!new_unicode)
4421 goto onError;
4422 u = PyUnicode_AsUnicode((PyObject *)unicode);
4423 if (!u)
4424 goto onError;
4425#if SIZEOF_WCHAR_T == 2
4426 i += wchar_offset;
4427#endif
4428 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(new_unicode), u, i);
4429 Py_DECREF(unicode);
4430 unicode = new_unicode;
4431 kind = 0;
4432 data = PyUnicode_AS_UNICODE(new_unicode);
4433 assert(data != NULL);
4434 }
4435 error_outptr = PyUnicode_AS_UNICODE(unicode) + i;
Benjamin Peterson29060642009-01-31 22:14:21 +00004436 if (unicode_decode_call_errorhandler(
4437 errors, &errorHandler,
4438 "utf8", errmsg,
4439 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004440 &unicode, &i, &error_outptr))
Benjamin Peterson29060642009-01-31 22:14:21 +00004441 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004442 /* Update data because unicode_decode_call_errorhandler might have
4443 re-created or resized the unicode object. */
4444 data = PyUnicode_AS_UNICODE(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004445 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004446 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004447 /* Ensure the unicode_size calculation above was correct: */
4448 assert(kind == PyUnicode_WCHAR_KIND || i == unicode_size);
4449
Walter Dörwald69652032004-09-07 20:24:22 +00004450 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004451 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004452
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004453 /* Adjust length and ready string when it contained errors and
4454 is of the old resizable kind. */
4455 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004456 if (PyUnicode_Resize((PyObject**)&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004457 goto onError;
4458 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004459
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004460 Py_XDECREF(errorHandler);
4461 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004462#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004463 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004464 Py_DECREF(unicode);
4465 return NULL;
4466 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004467#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004468 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00004469 return (PyObject *)unicode;
4470
Benjamin Peterson29060642009-01-31 22:14:21 +00004471 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004472 Py_XDECREF(errorHandler);
4473 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004474 Py_DECREF(unicode);
4475 return NULL;
4476}
4477
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004478#undef WRITE_FLEXIBLE_OR_WSTR
Antoine Pitrouab868312009-01-10 15:40:25 +00004479
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004480#ifdef __APPLE__
4481
4482/* Simplified UTF-8 decoder using surrogateescape error handler,
4483 used to decode the command line arguments on Mac OS X. */
4484
4485wchar_t*
4486_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4487{
4488 int n;
4489 const char *e;
4490 wchar_t *unicode, *p;
4491
4492 /* Note: size will always be longer than the resulting Unicode
4493 character count */
4494 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4495 PyErr_NoMemory();
4496 return NULL;
4497 }
4498 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4499 if (!unicode)
4500 return NULL;
4501
4502 /* Unpack UTF-8 encoded data */
4503 p = unicode;
4504 e = s + size;
4505 while (s < e) {
4506 Py_UCS4 ch = (unsigned char)*s;
4507
4508 if (ch < 0x80) {
4509 *p++ = (wchar_t)ch;
4510 s++;
4511 continue;
4512 }
4513
4514 n = utf8_code_length[ch];
4515 if (s + n > e) {
4516 goto surrogateescape;
4517 }
4518
4519 switch (n) {
4520 case 0:
4521 case 1:
4522 goto surrogateescape;
4523
4524 case 2:
4525 if ((s[1] & 0xc0) != 0x80)
4526 goto surrogateescape;
4527 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4528 assert ((ch > 0x007F) && (ch <= 0x07FF));
4529 *p++ = (wchar_t)ch;
4530 break;
4531
4532 case 3:
4533 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4534 will result in surrogates in range d800-dfff. Surrogates are
4535 not valid UTF-8 so they are rejected.
4536 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4537 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4538 if ((s[1] & 0xc0) != 0x80 ||
4539 (s[2] & 0xc0) != 0x80 ||
4540 ((unsigned char)s[0] == 0xE0 &&
4541 (unsigned char)s[1] < 0xA0) ||
4542 ((unsigned char)s[0] == 0xED &&
4543 (unsigned char)s[1] > 0x9F)) {
4544
4545 goto surrogateescape;
4546 }
4547 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4548 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004549 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004550 break;
4551
4552 case 4:
4553 if ((s[1] & 0xc0) != 0x80 ||
4554 (s[2] & 0xc0) != 0x80 ||
4555 (s[3] & 0xc0) != 0x80 ||
4556 ((unsigned char)s[0] == 0xF0 &&
4557 (unsigned char)s[1] < 0x90) ||
4558 ((unsigned char)s[0] == 0xF4 &&
4559 (unsigned char)s[1] > 0x8F)) {
4560 goto surrogateescape;
4561 }
4562 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4563 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4564 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4565
4566#if SIZEOF_WCHAR_T == 4
4567 *p++ = (wchar_t)ch;
4568#else
4569 /* compute and append the two surrogates: */
4570
4571 /* translate from 10000..10FFFF to 0..FFFF */
4572 ch -= 0x10000;
4573
4574 /* high surrogate = top 10 bits added to D800 */
4575 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4576
4577 /* low surrogate = bottom 10 bits added to DC00 */
4578 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4579#endif
4580 break;
4581 }
4582 s += n;
4583 continue;
4584
4585 surrogateescape:
4586 *p++ = 0xDC00 + ch;
4587 s++;
4588 }
4589 *p = L'\0';
4590 return unicode;
4591}
4592
4593#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004594
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004595/* Primary internal function which creates utf8 encoded bytes objects.
4596
4597 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004598 and allocate exactly as much space needed at the end. Else allocate the
4599 maximum possible needed (4 result bytes per Unicode character), and return
4600 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004601*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004602PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004603_PyUnicode_AsUTF8String(PyObject *obj, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004604{
Tim Peters602f7402002-04-27 18:03:26 +00004605#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004606
Guido van Rossum98297ee2007-11-06 21:34:58 +00004607 Py_ssize_t i; /* index into s of next input byte */
4608 PyObject *result; /* result string object */
4609 char *p; /* next free byte in output buffer */
4610 Py_ssize_t nallocated; /* number of result bytes allocated */
4611 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004612 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004613 PyObject *errorHandler = NULL;
4614 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004615 int kind;
4616 void *data;
4617 Py_ssize_t size;
4618 PyUnicodeObject *unicode = (PyUnicodeObject *)obj;
4619#if SIZEOF_WCHAR_T == 2
4620 Py_ssize_t wchar_offset = 0;
4621#endif
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004622
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004623 if (!PyUnicode_Check(unicode)) {
4624 PyErr_BadArgument();
4625 return NULL;
4626 }
4627
4628 if (PyUnicode_READY(unicode) == -1)
4629 return NULL;
4630
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004631 if (PyUnicode_UTF8(unicode))
4632 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4633 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004634
4635 kind = PyUnicode_KIND(unicode);
4636 data = PyUnicode_DATA(unicode);
4637 size = PyUnicode_GET_LENGTH(unicode);
4638
Tim Peters602f7402002-04-27 18:03:26 +00004639 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004640
Tim Peters602f7402002-04-27 18:03:26 +00004641 if (size <= MAX_SHORT_UNICHARS) {
4642 /* Write into the stack buffer; nallocated can't overflow.
4643 * At the end, we'll allocate exactly as much heap space as it
4644 * turns out we need.
4645 */
4646 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004647 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004648 p = stackbuf;
4649 }
4650 else {
4651 /* Overallocate on the heap, and give the excess back at the end. */
4652 nallocated = size * 4;
4653 if (nallocated / 4 != size) /* overflow! */
4654 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004655 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004656 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004657 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004658 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004659 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004660
Tim Peters602f7402002-04-27 18:03:26 +00004661 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004662 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004663
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004664 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004665 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004666 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004667
Guido van Rossumd57fd912000-03-10 22:53:23 +00004668 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004669 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004670 *p++ = (char)(0xc0 | (ch >> 6));
4671 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004672 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004673 Py_ssize_t newpos;
4674 PyObject *rep;
4675 Py_ssize_t repsize, k, startpos;
4676 startpos = i-1;
4677#if SIZEOF_WCHAR_T == 2
4678 startpos += wchar_offset;
Victor Stinner445a6232010-04-22 20:01:57 +00004679#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004680 rep = unicode_encode_call_errorhandler(
4681 errors, &errorHandler, "utf-8", "surrogates not allowed",
4682 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
4683 &exc, startpos, startpos+1, &newpos);
4684 if (!rep)
4685 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004686
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004687 if (PyBytes_Check(rep))
4688 repsize = PyBytes_GET_SIZE(rep);
4689 else
4690 repsize = PyUnicode_GET_SIZE(rep);
4691
4692 if (repsize > 4) {
4693 Py_ssize_t offset;
4694
4695 if (result == NULL)
4696 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004697 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004698 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004699
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004700 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4701 /* integer overflow */
4702 PyErr_NoMemory();
4703 goto error;
4704 }
4705 nallocated += repsize - 4;
4706 if (result != NULL) {
4707 if (_PyBytes_Resize(&result, nallocated) < 0)
4708 goto error;
4709 } else {
4710 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004711 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004712 goto error;
4713 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4714 }
4715 p = PyBytes_AS_STRING(result) + offset;
4716 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004717
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004718 if (PyBytes_Check(rep)) {
4719 char *prep = PyBytes_AS_STRING(rep);
4720 for(k = repsize; k > 0; k--)
4721 *p++ = *prep++;
4722 } else /* rep is unicode */ {
4723 const Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
4724 Py_UNICODE c;
4725
4726 for(k=0; k<repsize; k++) {
4727 c = prep[k];
4728 if (0x80 <= c) {
4729 raise_encode_exception(&exc, "utf-8",
4730 PyUnicode_AS_UNICODE(unicode),
4731 size, i-1, i,
4732 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004733 goto error;
4734 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004735 *p++ = (char)prep[k];
Victor Stinner31be90b2010-04-22 19:38:16 +00004736 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004737 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004738 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004739 } else if (ch < 0x10000) {
4740 *p++ = (char)(0xe0 | (ch >> 12));
4741 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4742 *p++ = (char)(0x80 | (ch & 0x3f));
4743 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004744 /* Encode UCS4 Unicode ordinals */
4745 *p++ = (char)(0xf0 | (ch >> 18));
4746 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4747 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4748 *p++ = (char)(0x80 | (ch & 0x3f));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004749#if SIZEOF_WCHAR_T == 2
4750 wchar_offset++;
4751#endif
Tim Peters602f7402002-04-27 18:03:26 +00004752 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004753 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004754
Guido van Rossum98297ee2007-11-06 21:34:58 +00004755 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004756 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004757 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004758 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004759 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004760 }
4761 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004762 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004763 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004764 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004765 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004766 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004767
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004768 Py_XDECREF(errorHandler);
4769 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004770 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004771 error:
4772 Py_XDECREF(errorHandler);
4773 Py_XDECREF(exc);
4774 Py_XDECREF(result);
4775 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004776
Tim Peters602f7402002-04-27 18:03:26 +00004777#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004778}
4779
Alexander Belopolsky40018472011-02-26 01:02:56 +00004780PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004781PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4782 Py_ssize_t size,
4783 const char *errors)
4784{
4785 PyObject *v, *unicode;
4786
4787 unicode = PyUnicode_FromUnicode(s, size);
4788 if (unicode == NULL)
4789 return NULL;
4790 v = _PyUnicode_AsUTF8String(unicode, errors);
4791 Py_DECREF(unicode);
4792 return v;
4793}
4794
4795PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004796PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004797{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004798 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004799}
4800
Walter Dörwald41980ca2007-08-16 21:55:45 +00004801/* --- UTF-32 Codec ------------------------------------------------------- */
4802
4803PyObject *
4804PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004805 Py_ssize_t size,
4806 const char *errors,
4807 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004808{
4809 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4810}
4811
4812PyObject *
4813PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004814 Py_ssize_t size,
4815 const char *errors,
4816 int *byteorder,
4817 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004818{
4819 const char *starts = s;
4820 Py_ssize_t startinpos;
4821 Py_ssize_t endinpos;
4822 Py_ssize_t outpos;
4823 PyUnicodeObject *unicode;
4824 Py_UNICODE *p;
4825#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004826 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004827 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004828#else
4829 const int pairs = 0;
4830#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00004831 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004832 int bo = 0; /* assume native ordering by default */
4833 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004834 /* Offsets from q for retrieving bytes in the right order. */
4835#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4836 int iorder[] = {0, 1, 2, 3};
4837#else
4838 int iorder[] = {3, 2, 1, 0};
4839#endif
4840 PyObject *errorHandler = NULL;
4841 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004842
Walter Dörwald41980ca2007-08-16 21:55:45 +00004843 q = (unsigned char *)s;
4844 e = q + size;
4845
4846 if (byteorder)
4847 bo = *byteorder;
4848
4849 /* Check for BOM marks (U+FEFF) in the input and adjust current
4850 byte order setting accordingly. In native mode, the leading BOM
4851 mark is skipped, in all other modes, it is copied to the output
4852 stream as-is (giving a ZWNBSP character). */
4853 if (bo == 0) {
4854 if (size >= 4) {
4855 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004856 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004857#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004858 if (bom == 0x0000FEFF) {
4859 q += 4;
4860 bo = -1;
4861 }
4862 else if (bom == 0xFFFE0000) {
4863 q += 4;
4864 bo = 1;
4865 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004866#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004867 if (bom == 0x0000FEFF) {
4868 q += 4;
4869 bo = 1;
4870 }
4871 else if (bom == 0xFFFE0000) {
4872 q += 4;
4873 bo = -1;
4874 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004875#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004876 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004877 }
4878
4879 if (bo == -1) {
4880 /* force LE */
4881 iorder[0] = 0;
4882 iorder[1] = 1;
4883 iorder[2] = 2;
4884 iorder[3] = 3;
4885 }
4886 else if (bo == 1) {
4887 /* force BE */
4888 iorder[0] = 3;
4889 iorder[1] = 2;
4890 iorder[2] = 1;
4891 iorder[3] = 0;
4892 }
4893
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004894 /* On narrow builds we split characters outside the BMP into two
4895 codepoints => count how much extra space we need. */
4896#ifndef Py_UNICODE_WIDE
4897 for (qq = q; qq < e; qq += 4)
4898 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
4899 pairs++;
4900#endif
4901
4902 /* This might be one to much, because of a BOM */
4903 unicode = _PyUnicode_New((size+3)/4+pairs);
4904 if (!unicode)
4905 return NULL;
4906 if (size == 0)
4907 return (PyObject *)unicode;
4908
4909 /* Unpack UTF-32 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004910 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004911
Walter Dörwald41980ca2007-08-16 21:55:45 +00004912 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004913 Py_UCS4 ch;
4914 /* remaining bytes at the end? (size should be divisible by 4) */
4915 if (e-q<4) {
4916 if (consumed)
4917 break;
4918 errmsg = "truncated data";
4919 startinpos = ((const char *)q)-starts;
4920 endinpos = ((const char *)e)-starts;
4921 goto utf32Error;
4922 /* The remaining input chars are ignored if the callback
4923 chooses to skip the input */
4924 }
4925 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
4926 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004927
Benjamin Peterson29060642009-01-31 22:14:21 +00004928 if (ch >= 0x110000)
4929 {
4930 errmsg = "codepoint not in range(0x110000)";
4931 startinpos = ((const char *)q)-starts;
4932 endinpos = startinpos+4;
4933 goto utf32Error;
4934 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004935#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004936 if (ch >= 0x10000)
4937 {
4938 *p++ = 0xD800 | ((ch-0x10000) >> 10);
4939 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
4940 }
4941 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00004942#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004943 *p++ = ch;
4944 q += 4;
4945 continue;
4946 utf32Error:
4947 outpos = p-PyUnicode_AS_UNICODE(unicode);
4948 if (unicode_decode_call_errorhandler(
4949 errors, &errorHandler,
4950 "utf32", errmsg,
4951 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
4952 &unicode, &outpos, &p))
4953 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004954 }
4955
4956 if (byteorder)
4957 *byteorder = bo;
4958
4959 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004960 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004961
4962 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02004963 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004964 goto onError;
4965
4966 Py_XDECREF(errorHandler);
4967 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004968#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004969 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004970 Py_DECREF(unicode);
4971 return NULL;
4972 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004973#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004974 assert(_PyUnicode_CheckConsistency(unicode, 1));
Walter Dörwald41980ca2007-08-16 21:55:45 +00004975 return (PyObject *)unicode;
4976
Benjamin Peterson29060642009-01-31 22:14:21 +00004977 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00004978 Py_DECREF(unicode);
4979 Py_XDECREF(errorHandler);
4980 Py_XDECREF(exc);
4981 return NULL;
4982}
4983
4984PyObject *
4985PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004986 Py_ssize_t size,
4987 const char *errors,
4988 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004989{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004990 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004991 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004992 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004993#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004994 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004995#else
4996 const int pairs = 0;
4997#endif
4998 /* Offsets from p for storing byte pairs in the right order. */
4999#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5000 int iorder[] = {0, 1, 2, 3};
5001#else
5002 int iorder[] = {3, 2, 1, 0};
5003#endif
5004
Benjamin Peterson29060642009-01-31 22:14:21 +00005005#define STORECHAR(CH) \
5006 do { \
5007 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5008 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5009 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5010 p[iorder[0]] = (CH) & 0xff; \
5011 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005012 } while(0)
5013
5014 /* In narrow builds we can output surrogate pairs as one codepoint,
5015 so we need less space. */
5016#ifndef Py_UNICODE_WIDE
5017 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005018 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
5019 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
5020 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005021#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005022 nsize = (size - pairs + (byteorder == 0));
5023 bytesize = nsize * 4;
5024 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005025 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005026 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005027 if (v == NULL)
5028 return NULL;
5029
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005030 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005031 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005032 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005033 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005034 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005035
5036 if (byteorder == -1) {
5037 /* force LE */
5038 iorder[0] = 0;
5039 iorder[1] = 1;
5040 iorder[2] = 2;
5041 iorder[3] = 3;
5042 }
5043 else if (byteorder == 1) {
5044 /* force BE */
5045 iorder[0] = 3;
5046 iorder[1] = 2;
5047 iorder[2] = 1;
5048 iorder[3] = 0;
5049 }
5050
5051 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005052 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005053#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005054 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
5055 Py_UCS4 ch2 = *s;
5056 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
5057 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
5058 s++;
5059 size--;
5060 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005061 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005062#endif
5063 STORECHAR(ch);
5064 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005065
5066 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005067 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005068#undef STORECHAR
5069}
5070
Alexander Belopolsky40018472011-02-26 01:02:56 +00005071PyObject *
5072PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005073{
5074 if (!PyUnicode_Check(unicode)) {
5075 PyErr_BadArgument();
5076 return NULL;
5077 }
5078 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005079 PyUnicode_GET_SIZE(unicode),
5080 NULL,
5081 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005082}
5083
Guido van Rossumd57fd912000-03-10 22:53:23 +00005084/* --- UTF-16 Codec ------------------------------------------------------- */
5085
Tim Peters772747b2001-08-09 22:21:55 +00005086PyObject *
5087PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005088 Py_ssize_t size,
5089 const char *errors,
5090 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005091{
Walter Dörwald69652032004-09-07 20:24:22 +00005092 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5093}
5094
Antoine Pitrouab868312009-01-10 15:40:25 +00005095/* Two masks for fast checking of whether a C 'long' may contain
5096 UTF16-encoded surrogate characters. This is an efficient heuristic,
5097 assuming that non-surrogate characters with a code point >= 0x8000 are
5098 rare in most input.
5099 FAST_CHAR_MASK is used when the input is in native byte ordering,
5100 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005101*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005102#if (SIZEOF_LONG == 8)
5103# define FAST_CHAR_MASK 0x8000800080008000L
5104# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5105#elif (SIZEOF_LONG == 4)
5106# define FAST_CHAR_MASK 0x80008000L
5107# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5108#else
5109# error C 'long' size should be either 4 or 8!
5110#endif
5111
Walter Dörwald69652032004-09-07 20:24:22 +00005112PyObject *
5113PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005114 Py_ssize_t size,
5115 const char *errors,
5116 int *byteorder,
5117 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005118{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005119 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005120 Py_ssize_t startinpos;
5121 Py_ssize_t endinpos;
5122 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005123 PyUnicodeObject *unicode;
5124 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00005125 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005126 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005127 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005128 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005129 /* Offsets from q for retrieving byte pairs in the right order. */
5130#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5131 int ihi = 1, ilo = 0;
5132#else
5133 int ihi = 0, ilo = 1;
5134#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005135 PyObject *errorHandler = NULL;
5136 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005137
5138 /* Note: size will always be longer than the resulting Unicode
5139 character count */
5140 unicode = _PyUnicode_New(size);
5141 if (!unicode)
5142 return NULL;
5143 if (size == 0)
5144 return (PyObject *)unicode;
5145
5146 /* Unpack UTF-16 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005147 p = PyUnicode_AS_UNICODE(unicode);
Tim Peters772747b2001-08-09 22:21:55 +00005148 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005149 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005150
5151 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005152 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005153
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005154 /* Check for BOM marks (U+FEFF) in the input and adjust current
5155 byte order setting accordingly. In native mode, the leading BOM
5156 mark is skipped, in all other modes, it is copied to the output
5157 stream as-is (giving a ZWNBSP character). */
5158 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005159 if (size >= 2) {
5160 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005161#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005162 if (bom == 0xFEFF) {
5163 q += 2;
5164 bo = -1;
5165 }
5166 else if (bom == 0xFFFE) {
5167 q += 2;
5168 bo = 1;
5169 }
Tim Petersced69f82003-09-16 20:30:58 +00005170#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005171 if (bom == 0xFEFF) {
5172 q += 2;
5173 bo = 1;
5174 }
5175 else if (bom == 0xFFFE) {
5176 q += 2;
5177 bo = -1;
5178 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005179#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005180 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005181 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005182
Tim Peters772747b2001-08-09 22:21:55 +00005183 if (bo == -1) {
5184 /* force LE */
5185 ihi = 1;
5186 ilo = 0;
5187 }
5188 else if (bo == 1) {
5189 /* force BE */
5190 ihi = 0;
5191 ilo = 1;
5192 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005193#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5194 native_ordering = ilo < ihi;
5195#else
5196 native_ordering = ilo > ihi;
5197#endif
Tim Peters772747b2001-08-09 22:21:55 +00005198
Antoine Pitrouab868312009-01-10 15:40:25 +00005199 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005200 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005201 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005202 /* First check for possible aligned read of a C 'long'. Unaligned
5203 reads are more expensive, better to defer to another iteration. */
5204 if (!((size_t) q & LONG_PTR_MASK)) {
5205 /* Fast path for runs of non-surrogate chars. */
5206 register const unsigned char *_q = q;
5207 Py_UNICODE *_p = p;
5208 if (native_ordering) {
5209 /* Native ordering is simple: as long as the input cannot
5210 possibly contain a surrogate char, do an unrolled copy
5211 of several 16-bit code points to the target object.
5212 The non-surrogate check is done on several input bytes
5213 at a time (as many as a C 'long' can contain). */
5214 while (_q < aligned_end) {
5215 unsigned long data = * (unsigned long *) _q;
5216 if (data & FAST_CHAR_MASK)
5217 break;
5218 _p[0] = ((unsigned short *) _q)[0];
5219 _p[1] = ((unsigned short *) _q)[1];
5220#if (SIZEOF_LONG == 8)
5221 _p[2] = ((unsigned short *) _q)[2];
5222 _p[3] = ((unsigned short *) _q)[3];
5223#endif
5224 _q += SIZEOF_LONG;
5225 _p += SIZEOF_LONG / 2;
5226 }
5227 }
5228 else {
5229 /* Byteswapped ordering is similar, but we must decompose
5230 the copy bytewise, and take care of zero'ing out the
5231 upper bytes if the target object is in 32-bit units
5232 (that is, in UCS-4 builds). */
5233 while (_q < aligned_end) {
5234 unsigned long data = * (unsigned long *) _q;
5235 if (data & SWAPPED_FAST_CHAR_MASK)
5236 break;
5237 /* Zero upper bytes in UCS-4 builds */
5238#if (Py_UNICODE_SIZE > 2)
5239 _p[0] = 0;
5240 _p[1] = 0;
5241#if (SIZEOF_LONG == 8)
5242 _p[2] = 0;
5243 _p[3] = 0;
5244#endif
5245#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005246 /* Issue #4916; UCS-4 builds on big endian machines must
5247 fill the two last bytes of each 4-byte unit. */
5248#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
5249# define OFF 2
5250#else
5251# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00005252#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005253 ((unsigned char *) _p)[OFF + 1] = _q[0];
5254 ((unsigned char *) _p)[OFF + 0] = _q[1];
5255 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
5256 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
5257#if (SIZEOF_LONG == 8)
5258 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
5259 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
5260 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
5261 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
5262#endif
5263#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00005264 _q += SIZEOF_LONG;
5265 _p += SIZEOF_LONG / 2;
5266 }
5267 }
5268 p = _p;
5269 q = _q;
5270 if (q >= e)
5271 break;
5272 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005273 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005274
Benjamin Peterson14339b62009-01-31 16:36:08 +00005275 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005276
5277 if (ch < 0xD800 || ch > 0xDFFF) {
5278 *p++ = ch;
5279 continue;
5280 }
5281
5282 /* UTF-16 code pair: */
5283 if (q > e) {
5284 errmsg = "unexpected end of data";
5285 startinpos = (((const char *)q) - 2) - starts;
5286 endinpos = ((const char *)e) + 1 - starts;
5287 goto utf16Error;
5288 }
5289 if (0xD800 <= ch && ch <= 0xDBFF) {
5290 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
5291 q += 2;
5292 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00005293#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005294 *p++ = ch;
5295 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005296#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005297 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005298#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005299 continue;
5300 }
5301 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005302 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005303 startinpos = (((const char *)q)-4)-starts;
5304 endinpos = startinpos+2;
5305 goto utf16Error;
5306 }
5307
Benjamin Peterson14339b62009-01-31 16:36:08 +00005308 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005309 errmsg = "illegal encoding";
5310 startinpos = (((const char *)q)-2)-starts;
5311 endinpos = startinpos+2;
5312 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005313
Benjamin Peterson29060642009-01-31 22:14:21 +00005314 utf16Error:
5315 outpos = p - PyUnicode_AS_UNICODE(unicode);
5316 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005317 errors,
5318 &errorHandler,
5319 "utf16", errmsg,
5320 &starts,
5321 (const char **)&e,
5322 &startinpos,
5323 &endinpos,
5324 &exc,
5325 (const char **)&q,
5326 &unicode,
5327 &outpos,
5328 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00005329 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005330 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005331 /* remaining byte at the end? (size should be even) */
5332 if (e == q) {
5333 if (!consumed) {
5334 errmsg = "truncated data";
5335 startinpos = ((const char *)q) - starts;
5336 endinpos = ((const char *)e) + 1 - starts;
5337 outpos = p - PyUnicode_AS_UNICODE(unicode);
5338 if (unicode_decode_call_errorhandler(
5339 errors,
5340 &errorHandler,
5341 "utf16", errmsg,
5342 &starts,
5343 (const char **)&e,
5344 &startinpos,
5345 &endinpos,
5346 &exc,
5347 (const char **)&q,
5348 &unicode,
5349 &outpos,
5350 &p))
5351 goto onError;
5352 /* The remaining input chars are ignored if the callback
5353 chooses to skip the input */
5354 }
5355 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005356
5357 if (byteorder)
5358 *byteorder = bo;
5359
Walter Dörwald69652032004-09-07 20:24:22 +00005360 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005361 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005362
Guido van Rossumd57fd912000-03-10 22:53:23 +00005363 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02005364 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005365 goto onError;
5366
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005367 Py_XDECREF(errorHandler);
5368 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005369#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005370 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005371 Py_DECREF(unicode);
5372 return NULL;
5373 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005374#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005375 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00005376 return (PyObject *)unicode;
5377
Benjamin Peterson29060642009-01-31 22:14:21 +00005378 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005379 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005380 Py_XDECREF(errorHandler);
5381 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005382 return NULL;
5383}
5384
Antoine Pitrouab868312009-01-10 15:40:25 +00005385#undef FAST_CHAR_MASK
5386#undef SWAPPED_FAST_CHAR_MASK
5387
Tim Peters772747b2001-08-09 22:21:55 +00005388PyObject *
5389PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005390 Py_ssize_t size,
5391 const char *errors,
5392 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005393{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005394 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005395 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005396 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005397#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005398 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005399#else
5400 const int pairs = 0;
5401#endif
Tim Peters772747b2001-08-09 22:21:55 +00005402 /* Offsets from p for storing byte pairs in the right order. */
5403#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5404 int ihi = 1, ilo = 0;
5405#else
5406 int ihi = 0, ilo = 1;
5407#endif
5408
Benjamin Peterson29060642009-01-31 22:14:21 +00005409#define STORECHAR(CH) \
5410 do { \
5411 p[ihi] = ((CH) >> 8) & 0xff; \
5412 p[ilo] = (CH) & 0xff; \
5413 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005414 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005415
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005416#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005417 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005418 if (s[i] >= 0x10000)
5419 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005420#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005421 /* 2 * (size + pairs + (byteorder == 0)) */
5422 if (size > PY_SSIZE_T_MAX ||
5423 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005424 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005425 nsize = size + pairs + (byteorder == 0);
5426 bytesize = nsize * 2;
5427 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005428 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005429 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005430 if (v == NULL)
5431 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005432
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005433 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005434 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005435 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005436 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005437 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005438
5439 if (byteorder == -1) {
5440 /* force LE */
5441 ihi = 1;
5442 ilo = 0;
5443 }
5444 else if (byteorder == 1) {
5445 /* force BE */
5446 ihi = 0;
5447 ilo = 1;
5448 }
5449
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005450 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005451 Py_UNICODE ch = *s++;
5452 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005453#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005454 if (ch >= 0x10000) {
5455 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5456 ch = 0xD800 | ((ch-0x10000) >> 10);
5457 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005458#endif
Tim Peters772747b2001-08-09 22:21:55 +00005459 STORECHAR(ch);
5460 if (ch2)
5461 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005462 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005463
5464 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005465 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005466#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005467}
5468
Alexander Belopolsky40018472011-02-26 01:02:56 +00005469PyObject *
5470PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005471{
5472 if (!PyUnicode_Check(unicode)) {
5473 PyErr_BadArgument();
5474 return NULL;
5475 }
5476 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005477 PyUnicode_GET_SIZE(unicode),
5478 NULL,
5479 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005480}
5481
5482/* --- Unicode Escape Codec ----------------------------------------------- */
5483
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005484/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5485 if all the escapes in the string make it still a valid ASCII string.
5486 Returns -1 if any escapes were found which cause the string to
5487 pop out of ASCII range. Otherwise returns the length of the
5488 required buffer to hold the string.
5489 */
5490Py_ssize_t
5491length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5492{
5493 const unsigned char *p = (const unsigned char *)s;
5494 const unsigned char *end = p + size;
5495 Py_ssize_t length = 0;
5496
5497 if (size < 0)
5498 return -1;
5499
5500 for (; p < end; ++p) {
5501 if (*p > 127) {
5502 /* Non-ASCII */
5503 return -1;
5504 }
5505 else if (*p != '\\') {
5506 /* Normal character */
5507 ++length;
5508 }
5509 else {
5510 /* Backslash-escape, check next char */
5511 ++p;
5512 /* Escape sequence reaches till end of string or
5513 non-ASCII follow-up. */
5514 if (p >= end || *p > 127)
5515 return -1;
5516 switch (*p) {
5517 case '\n':
5518 /* backslash + \n result in zero characters */
5519 break;
5520 case '\\': case '\'': case '\"':
5521 case 'b': case 'f': case 't':
5522 case 'n': case 'r': case 'v': case 'a':
5523 ++length;
5524 break;
5525 case '0': case '1': case '2': case '3':
5526 case '4': case '5': case '6': case '7':
5527 case 'x': case 'u': case 'U': case 'N':
5528 /* these do not guarantee ASCII characters */
5529 return -1;
5530 default:
5531 /* count the backslash + the other character */
5532 length += 2;
5533 }
5534 }
5535 }
5536 return length;
5537}
5538
5539/* Similar to PyUnicode_WRITE but either write into wstr field
5540 or treat string as ASCII. */
5541#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5542 do { \
5543 if ((kind) != PyUnicode_WCHAR_KIND) \
5544 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5545 else \
5546 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5547 } while (0)
5548
5549#define WRITE_WSTR(buf, index, value) \
5550 assert(kind == PyUnicode_WCHAR_KIND), \
5551 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5552
5553
Fredrik Lundh06d12682001-01-24 07:59:11 +00005554static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005555
Alexander Belopolsky40018472011-02-26 01:02:56 +00005556PyObject *
5557PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005558 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005559 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005560{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005561 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005562 Py_ssize_t startinpos;
5563 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005564 int j;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005565 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005566 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005567 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005568 char* message;
5569 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005570 PyObject *errorHandler = NULL;
5571 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005572 Py_ssize_t ascii_length;
5573 Py_ssize_t i;
5574 int kind;
5575 void *data;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005576
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005577 ascii_length = length_of_escaped_ascii_string(s, size);
5578
5579 /* After length_of_escaped_ascii_string() there are two alternatives,
5580 either the string is pure ASCII with named escapes like \n, etc.
5581 and we determined it's exact size (common case)
5582 or it contains \x, \u, ... escape sequences. then we create a
5583 legacy wchar string and resize it at the end of this function. */
5584 if (ascii_length >= 0) {
5585 v = (PyUnicodeObject *)PyUnicode_New(ascii_length, 127);
5586 if (!v)
5587 goto onError;
5588 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
5589 kind = PyUnicode_1BYTE_KIND;
5590 data = PyUnicode_DATA(v);
5591 }
5592 else {
5593 /* Escaped strings will always be longer than the resulting
5594 Unicode string, so we start with size here and then reduce the
5595 length after conversion to the true value.
5596 (but if the error callback returns a long replacement string
5597 we'll have to allocate more space) */
5598 v = _PyUnicode_New(size);
5599 if (!v)
5600 goto onError;
5601 kind = PyUnicode_WCHAR_KIND;
5602 data = PyUnicode_AS_UNICODE(v);
5603 }
5604
Guido van Rossumd57fd912000-03-10 22:53:23 +00005605 if (size == 0)
5606 return (PyObject *)v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005607 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005608 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005609
Guido van Rossumd57fd912000-03-10 22:53:23 +00005610 while (s < end) {
5611 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005612 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005613 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005614
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005615 if (kind == PyUnicode_WCHAR_KIND) {
5616 assert(i < _PyUnicode_WSTR_LENGTH(v));
5617 }
5618 else {
5619 /* The only case in which i == ascii_length is a backslash
5620 followed by a newline. */
5621 assert(i <= ascii_length);
5622 }
5623
Guido van Rossumd57fd912000-03-10 22:53:23 +00005624 /* Non-escape characters are interpreted as Unicode ordinals */
5625 if (*s != '\\') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005626 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char) *s++);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005627 continue;
5628 }
5629
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005630 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005631 /* \ - Escapes */
5632 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005633 c = *s++;
5634 if (s > end)
5635 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005636
5637 if (kind == PyUnicode_WCHAR_KIND) {
5638 assert(i < _PyUnicode_WSTR_LENGTH(v));
5639 }
5640 else {
5641 /* The only case in which i == ascii_length is a backslash
5642 followed by a newline. */
5643 assert(i < ascii_length || (i == ascii_length && c == '\n'));
5644 }
5645
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005646 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005647
Benjamin Peterson29060642009-01-31 22:14:21 +00005648 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005649 case '\n': break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005650 case '\\': WRITE_ASCII_OR_WSTR(kind, data, i++, '\\'); break;
5651 case '\'': WRITE_ASCII_OR_WSTR(kind, data, i++, '\''); break;
5652 case '\"': WRITE_ASCII_OR_WSTR(kind, data, i++, '\"'); break;
5653 case 'b': WRITE_ASCII_OR_WSTR(kind, data, i++, '\b'); break;
5654 /* FF */
5655 case 'f': WRITE_ASCII_OR_WSTR(kind, data, i++, '\014'); break;
5656 case 't': WRITE_ASCII_OR_WSTR(kind, data, i++, '\t'); break;
5657 case 'n': WRITE_ASCII_OR_WSTR(kind, data, i++, '\n'); break;
5658 case 'r': WRITE_ASCII_OR_WSTR(kind, data, i++, '\r'); break;
5659 /* VT */
5660 case 'v': WRITE_ASCII_OR_WSTR(kind, data, i++, '\013'); break;
5661 /* BEL, not classic C */
5662 case 'a': WRITE_ASCII_OR_WSTR(kind, data, i++, '\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005663
Benjamin Peterson29060642009-01-31 22:14:21 +00005664 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005665 case '0': case '1': case '2': case '3':
5666 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005667 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005668 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005669 x = (x<<3) + *s++ - '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 Rossumd57fd912000-03-10 22:53:23 +00005672 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005673 WRITE_WSTR(data, i++, x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005674 break;
5675
Benjamin Peterson29060642009-01-31 22:14:21 +00005676 /* hex escapes */
5677 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005678 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005679 digits = 2;
5680 message = "truncated \\xXX escape";
5681 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005682
Benjamin Peterson29060642009-01-31 22:14:21 +00005683 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005684 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005685 digits = 4;
5686 message = "truncated \\uXXXX escape";
5687 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005688
Benjamin Peterson29060642009-01-31 22:14:21 +00005689 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005690 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005691 digits = 8;
5692 message = "truncated \\UXXXXXXXX escape";
5693 hexescape:
5694 chr = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005695 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005696 if (s+digits>end) {
5697 endinpos = size;
5698 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005699 errors, &errorHandler,
5700 "unicodeescape", "end of string in escape sequence",
5701 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005702 &v, &i, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005703 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005704 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005705 goto nextByte;
5706 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005707 for (j = 0; j < digits; ++j) {
5708 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005709 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005710 endinpos = (s+j+1)-starts;
5711 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005712 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005713 errors, &errorHandler,
5714 "unicodeescape", message,
5715 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005716 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005717 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005718 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005719 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005720 }
5721 chr = (chr<<4) & ~0xF;
5722 if (c >= '0' && c <= '9')
5723 chr += c - '0';
5724 else if (c >= 'a' && c <= 'f')
5725 chr += 10 + c - 'a';
5726 else
5727 chr += 10 + c - 'A';
5728 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005729 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005730 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005731 /* _decoding_error will have already written into the
5732 target buffer. */
5733 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005734 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005735 /* when we get here, chr is a 32-bit unicode character */
5736 if (chr <= 0xffff)
5737 /* UCS-2 character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005738 WRITE_WSTR(data, i++, chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005739 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005740 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00005741 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00005742#ifdef Py_UNICODE_WIDE
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005743 WRITE_WSTR(data, i++, chr);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005744#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00005745 chr -= 0x10000L;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005746 WRITE_WSTR(data, i++, 0xD800 + (Py_UNICODE) (chr >> 10));
5747 WRITE_WSTR(data, i++, 0xDC00 + (Py_UNICODE) (chr & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005748#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00005749 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005750 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005751 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005752 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005753 errors, &errorHandler,
5754 "unicodeescape", "illegal Unicode character",
5755 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005756 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005757 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005758 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005759 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005760 break;
5761
Benjamin Peterson29060642009-01-31 22:14:21 +00005762 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005763 case 'N':
5764 message = "malformed \\N character escape";
5765 if (ucnhash_CAPI == NULL) {
5766 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005767 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5768 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005769 if (ucnhash_CAPI == NULL)
5770 goto ucnhashError;
5771 }
5772 if (*s == '{') {
5773 const char *start = s+1;
5774 /* look for the closing brace */
5775 while (*s != '}' && s < end)
5776 s++;
5777 if (s > start && s < end && *s == '}') {
5778 /* found a name. look it up in the unicode database */
5779 message = "unknown Unicode character name";
5780 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005781 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
5782 &chr))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005783 goto store;
5784 }
5785 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005786 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005787 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005788 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005789 errors, &errorHandler,
5790 "unicodeescape", message,
5791 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005792 &v, &i, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005793 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005794 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005795 break;
5796
5797 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005798 if (s > end) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005799 assert(kind == PyUnicode_WCHAR_KIND);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005800 message = "\\ at end of string";
5801 s--;
5802 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005803 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005804 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005805 errors, &errorHandler,
5806 "unicodeescape", message,
5807 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005808 &v, &i, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00005809 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005810 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005811 }
5812 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005813 WRITE_ASCII_OR_WSTR(kind, data, i++, '\\');
5814 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005815 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005816 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005817 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005818 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005819 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005820 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005821 /* Ensure the length prediction worked in case of ASCII strings */
5822 assert(kind == PyUnicode_WCHAR_KIND || i == ascii_length);
5823
Victor Stinnerfe226c02011-10-03 03:52:20 +02005824 if (kind == PyUnicode_WCHAR_KIND)
5825 {
5826 if (PyUnicode_Resize((PyObject**)&v, i) < 0)
5827 goto onError;
Victor Stinnerfe226c02011-10-03 03:52:20 +02005828 }
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005829 Py_XDECREF(errorHandler);
5830 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005831#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005832 if (_PyUnicode_READY_REPLACE(&v)) {
5833 Py_DECREF(v);
5834 return NULL;
5835 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005836#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005837 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00005838 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005839
Benjamin Peterson29060642009-01-31 22:14:21 +00005840 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005841 PyErr_SetString(
5842 PyExc_UnicodeError,
5843 "\\N escapes not supported (can't load unicodedata module)"
5844 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005845 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005846 Py_XDECREF(errorHandler);
5847 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005848 return NULL;
5849
Benjamin Peterson29060642009-01-31 22:14:21 +00005850 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005851 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005852 Py_XDECREF(errorHandler);
5853 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005854 return NULL;
5855}
5856
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005857#undef WRITE_ASCII_OR_WSTR
5858#undef WRITE_WSTR
5859
Guido van Rossumd57fd912000-03-10 22:53:23 +00005860/* Return a Unicode-Escape string version of the Unicode object.
5861
5862 If quotes is true, the string is enclosed in u"" or u'' quotes as
5863 appropriate.
5864
5865*/
5866
Walter Dörwald79e913e2007-05-12 11:08:06 +00005867static const char *hexdigits = "0123456789abcdef";
5868
Alexander Belopolsky40018472011-02-26 01:02:56 +00005869PyObject *
5870PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005871 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005872{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005873 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005874 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005875
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005876#ifdef Py_UNICODE_WIDE
5877 const Py_ssize_t expandsize = 10;
5878#else
5879 const Py_ssize_t expandsize = 6;
5880#endif
5881
Thomas Wouters89f507f2006-12-13 04:49:30 +00005882 /* XXX(nnorwitz): rather than over-allocating, it would be
5883 better to choose a different scheme. Perhaps scan the
5884 first N-chars of the string and allocate based on that size.
5885 */
5886 /* Initial allocation is based on the longest-possible unichr
5887 escape.
5888
5889 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5890 unichr, so in this case it's the longest unichr escape. In
5891 narrow (UTF-16) builds this is five chars per source unichr
5892 since there are two unichrs in the surrogate pair, so in narrow
5893 (UTF-16) builds it's not the longest unichr escape.
5894
5895 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5896 so in the narrow (UTF-16) build case it's the longest unichr
5897 escape.
5898 */
5899
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005900 if (size == 0)
5901 return PyBytes_FromStringAndSize(NULL, 0);
5902
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005903 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005904 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005905
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005906 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005907 2
5908 + expandsize*size
5909 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005910 if (repr == NULL)
5911 return NULL;
5912
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005913 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005914
Guido van Rossumd57fd912000-03-10 22:53:23 +00005915 while (size-- > 0) {
5916 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005917
Walter Dörwald79e913e2007-05-12 11:08:06 +00005918 /* Escape backslashes */
5919 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005920 *p++ = '\\';
5921 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005922 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005923 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005924
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00005925#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005926 /* Map 21-bit characters to '\U00xxxxxx' */
5927 else if (ch >= 0x10000) {
5928 *p++ = '\\';
5929 *p++ = 'U';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005930 *p++ = hexdigits[(ch >> 28) & 0x0000000F];
5931 *p++ = hexdigits[(ch >> 24) & 0x0000000F];
5932 *p++ = hexdigits[(ch >> 20) & 0x0000000F];
5933 *p++ = hexdigits[(ch >> 16) & 0x0000000F];
5934 *p++ = hexdigits[(ch >> 12) & 0x0000000F];
5935 *p++ = hexdigits[(ch >> 8) & 0x0000000F];
5936 *p++ = hexdigits[(ch >> 4) & 0x0000000F];
5937 *p++ = hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005938 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005939 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005940#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005941 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
5942 else if (ch >= 0xD800 && ch < 0xDC00) {
5943 Py_UNICODE ch2;
5944 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00005945
Benjamin Peterson29060642009-01-31 22:14:21 +00005946 ch2 = *s++;
5947 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00005948 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005949 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
5950 *p++ = '\\';
5951 *p++ = 'U';
5952 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
5953 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
5954 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
5955 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
5956 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
5957 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
5958 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
5959 *p++ = hexdigits[ucs & 0x0000000F];
5960 continue;
5961 }
5962 /* Fall through: isolated surrogates are copied as-is */
5963 s--;
5964 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005965 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005966#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005967
Guido van Rossumd57fd912000-03-10 22:53:23 +00005968 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005969 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005970 *p++ = '\\';
5971 *p++ = 'u';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005972 *p++ = hexdigits[(ch >> 12) & 0x000F];
5973 *p++ = hexdigits[(ch >> 8) & 0x000F];
5974 *p++ = hexdigits[(ch >> 4) & 0x000F];
5975 *p++ = hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005976 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005977
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005978 /* Map special whitespace to '\t', \n', '\r' */
5979 else if (ch == '\t') {
5980 *p++ = '\\';
5981 *p++ = 't';
5982 }
5983 else if (ch == '\n') {
5984 *p++ = '\\';
5985 *p++ = 'n';
5986 }
5987 else if (ch == '\r') {
5988 *p++ = '\\';
5989 *p++ = 'r';
5990 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005991
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005992 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005993 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005994 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005995 *p++ = 'x';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005996 *p++ = hexdigits[(ch >> 4) & 0x000F];
5997 *p++ = hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005998 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005999
Guido van Rossumd57fd912000-03-10 22:53:23 +00006000 /* Copy everything else as-is */
6001 else
6002 *p++ = (char) ch;
6003 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006004
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006005 assert(p - PyBytes_AS_STRING(repr) > 0);
6006 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6007 return NULL;
6008 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006009}
6010
Alexander Belopolsky40018472011-02-26 01:02:56 +00006011PyObject *
6012PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006013{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006014 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006015 if (!PyUnicode_Check(unicode)) {
6016 PyErr_BadArgument();
6017 return NULL;
6018 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00006019 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6020 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006021 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006022}
6023
6024/* --- Raw Unicode Escape Codec ------------------------------------------- */
6025
Alexander Belopolsky40018472011-02-26 01:02:56 +00006026PyObject *
6027PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006028 Py_ssize_t size,
6029 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006030{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006031 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006032 Py_ssize_t startinpos;
6033 Py_ssize_t endinpos;
6034 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006035 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006036 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006037 const char *end;
6038 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006039 PyObject *errorHandler = NULL;
6040 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006041
Guido van Rossumd57fd912000-03-10 22:53:23 +00006042 /* Escaped strings will always be longer than the resulting
6043 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006044 length after conversion to the true value. (But decoding error
6045 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006046 v = _PyUnicode_New(size);
6047 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006048 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006049 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006050 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006051 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006052 end = s + size;
6053 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006054 unsigned char c;
6055 Py_UCS4 x;
6056 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006057 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006058
Benjamin Peterson29060642009-01-31 22:14:21 +00006059 /* Non-escape characters are interpreted as Unicode ordinals */
6060 if (*s != '\\') {
6061 *p++ = (unsigned char)*s++;
6062 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006063 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006064 startinpos = s-starts;
6065
6066 /* \u-escapes are only interpreted iff the number of leading
6067 backslashes if odd */
6068 bs = s;
6069 for (;s < end;) {
6070 if (*s != '\\')
6071 break;
6072 *p++ = (unsigned char)*s++;
6073 }
6074 if (((s - bs) & 1) == 0 ||
6075 s >= end ||
6076 (*s != 'u' && *s != 'U')) {
6077 continue;
6078 }
6079 p--;
6080 count = *s=='u' ? 4 : 8;
6081 s++;
6082
6083 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
6084 outpos = p-PyUnicode_AS_UNICODE(v);
6085 for (x = 0, i = 0; i < count; ++i, ++s) {
6086 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006087 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006088 endinpos = s-starts;
6089 if (unicode_decode_call_errorhandler(
6090 errors, &errorHandler,
6091 "rawunicodeescape", "truncated \\uXXXX",
6092 &starts, &end, &startinpos, &endinpos, &exc, &s,
6093 &v, &outpos, &p))
6094 goto onError;
6095 goto nextByte;
6096 }
6097 x = (x<<4) & ~0xF;
6098 if (c >= '0' && c <= '9')
6099 x += c - '0';
6100 else if (c >= 'a' && c <= 'f')
6101 x += 10 + c - 'a';
6102 else
6103 x += 10 + c - 'A';
6104 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00006105 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00006106 /* UCS-2 character */
6107 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006108 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006109 /* UCS-4 character. Either store directly, or as
6110 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00006111#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006112 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006113#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006114 x -= 0x10000L;
6115 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
6116 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00006117#endif
6118 } else {
6119 endinpos = s-starts;
6120 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006121 if (unicode_decode_call_errorhandler(
6122 errors, &errorHandler,
6123 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006124 &starts, &end, &startinpos, &endinpos, &exc, &s,
6125 &v, &outpos, &p))
6126 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006127 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006128 nextByte:
6129 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006130 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02006131 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006132 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006133 Py_XDECREF(errorHandler);
6134 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006135#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006136 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006137 Py_DECREF(v);
6138 return NULL;
6139 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006140#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006141 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006142 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006143
Benjamin Peterson29060642009-01-31 22:14:21 +00006144 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006145 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006146 Py_XDECREF(errorHandler);
6147 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006148 return NULL;
6149}
6150
Alexander Belopolsky40018472011-02-26 01:02:56 +00006151PyObject *
6152PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006153 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006154{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006155 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006156 char *p;
6157 char *q;
6158
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006159#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006160 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006161#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006162 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006163#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00006164
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006165 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006166 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006167
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006168 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006169 if (repr == NULL)
6170 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00006171 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006172 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006173
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006174 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006175 while (size-- > 0) {
6176 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006177#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006178 /* Map 32-bit characters to '\Uxxxxxxxx' */
6179 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006180 *p++ = '\\';
6181 *p++ = 'U';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00006182 *p++ = hexdigits[(ch >> 28) & 0xf];
6183 *p++ = hexdigits[(ch >> 24) & 0xf];
6184 *p++ = hexdigits[(ch >> 20) & 0xf];
6185 *p++ = hexdigits[(ch >> 16) & 0xf];
6186 *p++ = hexdigits[(ch >> 12) & 0xf];
6187 *p++ = hexdigits[(ch >> 8) & 0xf];
6188 *p++ = hexdigits[(ch >> 4) & 0xf];
6189 *p++ = hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006190 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006191 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00006192#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006193 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
6194 if (ch >= 0xD800 && ch < 0xDC00) {
6195 Py_UNICODE ch2;
6196 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006197
Benjamin Peterson29060642009-01-31 22:14:21 +00006198 ch2 = *s++;
6199 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00006200 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006201 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
6202 *p++ = '\\';
6203 *p++ = 'U';
6204 *p++ = hexdigits[(ucs >> 28) & 0xf];
6205 *p++ = hexdigits[(ucs >> 24) & 0xf];
6206 *p++ = hexdigits[(ucs >> 20) & 0xf];
6207 *p++ = hexdigits[(ucs >> 16) & 0xf];
6208 *p++ = hexdigits[(ucs >> 12) & 0xf];
6209 *p++ = hexdigits[(ucs >> 8) & 0xf];
6210 *p++ = hexdigits[(ucs >> 4) & 0xf];
6211 *p++ = hexdigits[ucs & 0xf];
6212 continue;
6213 }
6214 /* Fall through: isolated surrogates are copied as-is */
6215 s--;
6216 size++;
6217 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006218#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006219 /* Map 16-bit characters to '\uxxxx' */
6220 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006221 *p++ = '\\';
6222 *p++ = 'u';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00006223 *p++ = hexdigits[(ch >> 12) & 0xf];
6224 *p++ = hexdigits[(ch >> 8) & 0xf];
6225 *p++ = hexdigits[(ch >> 4) & 0xf];
6226 *p++ = hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006227 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006228 /* Copy everything else as-is */
6229 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006230 *p++ = (char) ch;
6231 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006232 size = p - q;
6233
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006234 assert(size > 0);
6235 if (_PyBytes_Resize(&repr, size) < 0)
6236 return NULL;
6237 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006238}
6239
Alexander Belopolsky40018472011-02-26 01:02:56 +00006240PyObject *
6241PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006242{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006243 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006244 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00006245 PyErr_BadArgument();
6246 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006247 }
Walter Dörwald711005d2007-05-12 12:03:26 +00006248 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6249 PyUnicode_GET_SIZE(unicode));
6250
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006251 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006252}
6253
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006254/* --- Unicode Internal Codec ------------------------------------------- */
6255
Alexander Belopolsky40018472011-02-26 01:02:56 +00006256PyObject *
6257_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006258 Py_ssize_t size,
6259 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006260{
6261 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006262 Py_ssize_t startinpos;
6263 Py_ssize_t endinpos;
6264 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006265 PyUnicodeObject *v;
6266 Py_UNICODE *p;
6267 const char *end;
6268 const char *reason;
6269 PyObject *errorHandler = NULL;
6270 PyObject *exc = NULL;
6271
Neal Norwitzd43069c2006-01-08 01:12:10 +00006272#ifdef Py_UNICODE_WIDE
6273 Py_UNICODE unimax = PyUnicode_GetMax();
6274#endif
6275
Thomas Wouters89f507f2006-12-13 04:49:30 +00006276 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006277 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
6278 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006279 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006280 /* Intentionally PyUnicode_GET_SIZE instead of PyUnicode_GET_LENGTH
6281 as string was created with the old API. */
6282 if (PyUnicode_GET_SIZE(v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006283 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006284 p = PyUnicode_AS_UNICODE(v);
6285 end = s + size;
6286
6287 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006288 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006289 /* We have to sanity check the raw data, otherwise doom looms for
6290 some malformed UCS-4 data. */
6291 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006292#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006293 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006294#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006295 end-s < Py_UNICODE_SIZE
6296 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006297 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006298 startinpos = s - starts;
6299 if (end-s < Py_UNICODE_SIZE) {
6300 endinpos = end-starts;
6301 reason = "truncated input";
6302 }
6303 else {
6304 endinpos = s - starts + Py_UNICODE_SIZE;
6305 reason = "illegal code point (> 0x10FFFF)";
6306 }
6307 outpos = p - PyUnicode_AS_UNICODE(v);
6308 if (unicode_decode_call_errorhandler(
6309 errors, &errorHandler,
6310 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006311 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00006312 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006313 goto onError;
6314 }
6315 }
6316 else {
6317 p++;
6318 s += Py_UNICODE_SIZE;
6319 }
6320 }
6321
Victor Stinnerfe226c02011-10-03 03:52:20 +02006322 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006323 goto onError;
6324 Py_XDECREF(errorHandler);
6325 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006326#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006327 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006328 Py_DECREF(v);
6329 return NULL;
6330 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006331#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006332 assert(_PyUnicode_CheckConsistency(v, 1));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006333 return (PyObject *)v;
6334
Benjamin Peterson29060642009-01-31 22:14:21 +00006335 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006336 Py_XDECREF(v);
6337 Py_XDECREF(errorHandler);
6338 Py_XDECREF(exc);
6339 return NULL;
6340}
6341
Guido van Rossumd57fd912000-03-10 22:53:23 +00006342/* --- Latin-1 Codec ------------------------------------------------------ */
6343
Alexander Belopolsky40018472011-02-26 01:02:56 +00006344PyObject *
6345PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006346 Py_ssize_t size,
6347 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006348{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006349 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006350 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006351}
6352
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006353/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006354static void
6355make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006356 const char *encoding,
6357 const Py_UNICODE *unicode, Py_ssize_t size,
6358 Py_ssize_t startpos, Py_ssize_t endpos,
6359 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006360{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006361 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006362 *exceptionObject = PyUnicodeEncodeError_Create(
6363 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006364 }
6365 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006366 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6367 goto onError;
6368 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6369 goto onError;
6370 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6371 goto onError;
6372 return;
6373 onError:
6374 Py_DECREF(*exceptionObject);
6375 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006376 }
6377}
6378
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006379/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006380static void
6381raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006382 const char *encoding,
6383 const Py_UNICODE *unicode, Py_ssize_t size,
6384 Py_ssize_t startpos, Py_ssize_t endpos,
6385 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006386{
6387 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006388 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006389 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006390 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006391}
6392
6393/* error handling callback helper:
6394 build arguments, call the callback and check the arguments,
6395 put the result into newpos and return the replacement string, which
6396 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006397static PyObject *
6398unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006399 PyObject **errorHandler,
6400 const char *encoding, const char *reason,
6401 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
6402 Py_ssize_t startpos, Py_ssize_t endpos,
6403 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006404{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006405 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006406
6407 PyObject *restuple;
6408 PyObject *resunicode;
6409
6410 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006411 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006412 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006413 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006414 }
6415
6416 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006417 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006418 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006419 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006420
6421 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006422 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006423 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006424 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006425 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006426 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006427 Py_DECREF(restuple);
6428 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006429 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006430 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006431 &resunicode, newpos)) {
6432 Py_DECREF(restuple);
6433 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006434 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006435 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6436 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6437 Py_DECREF(restuple);
6438 return NULL;
6439 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006440 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006441 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006442 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006443 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6444 Py_DECREF(restuple);
6445 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006446 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006447 Py_INCREF(resunicode);
6448 Py_DECREF(restuple);
6449 return resunicode;
6450}
6451
Alexander Belopolsky40018472011-02-26 01:02:56 +00006452static PyObject *
6453unicode_encode_ucs1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006454 Py_ssize_t size,
6455 const char *errors,
6456 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006457{
6458 /* output object */
6459 PyObject *res;
6460 /* pointers to the beginning and end+1 of input */
6461 const Py_UNICODE *startp = p;
6462 const Py_UNICODE *endp = p + size;
6463 /* pointer to the beginning of the unencodable characters */
6464 /* const Py_UNICODE *badp = NULL; */
6465 /* pointer into the output */
6466 char *str;
6467 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006468 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006469 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6470 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006471 PyObject *errorHandler = NULL;
6472 PyObject *exc = NULL;
6473 /* the following variable is used for caching string comparisons
6474 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6475 int known_errorHandler = -1;
6476
6477 /* allocate enough for a simple encoding without
6478 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006479 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006480 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006481 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006482 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006483 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006484 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006485 ressize = size;
6486
6487 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006488 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006489
Benjamin Peterson29060642009-01-31 22:14:21 +00006490 /* can we encode this? */
6491 if (c<limit) {
6492 /* no overflow check, because we know that the space is enough */
6493 *str++ = (char)c;
6494 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006495 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006496 else {
6497 Py_ssize_t unicodepos = p-startp;
6498 Py_ssize_t requiredsize;
6499 PyObject *repunicode;
6500 Py_ssize_t repsize;
6501 Py_ssize_t newpos;
6502 Py_ssize_t respos;
6503 Py_UNICODE *uni2;
6504 /* startpos for collecting unencodable chars */
6505 const Py_UNICODE *collstart = p;
6506 const Py_UNICODE *collend = p;
6507 /* find all unecodable characters */
6508 while ((collend < endp) && ((*collend)>=limit))
6509 ++collend;
6510 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6511 if (known_errorHandler==-1) {
6512 if ((errors==NULL) || (!strcmp(errors, "strict")))
6513 known_errorHandler = 1;
6514 else if (!strcmp(errors, "replace"))
6515 known_errorHandler = 2;
6516 else if (!strcmp(errors, "ignore"))
6517 known_errorHandler = 3;
6518 else if (!strcmp(errors, "xmlcharrefreplace"))
6519 known_errorHandler = 4;
6520 else
6521 known_errorHandler = 0;
6522 }
6523 switch (known_errorHandler) {
6524 case 1: /* strict */
6525 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
6526 goto onError;
6527 case 2: /* replace */
6528 while (collstart++<collend)
6529 *str++ = '?'; /* fall through */
6530 case 3: /* ignore */
6531 p = collend;
6532 break;
6533 case 4: /* xmlcharrefreplace */
6534 respos = str - PyBytes_AS_STRING(res);
6535 /* determine replacement size (temporarily (mis)uses p) */
6536 for (p = collstart, repsize = 0; p < collend; ++p) {
6537 if (*p<10)
6538 repsize += 2+1+1;
6539 else if (*p<100)
6540 repsize += 2+2+1;
6541 else if (*p<1000)
6542 repsize += 2+3+1;
6543 else if (*p<10000)
6544 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006545#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006546 else
6547 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006548#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006549 else if (*p<100000)
6550 repsize += 2+5+1;
6551 else if (*p<1000000)
6552 repsize += 2+6+1;
6553 else
6554 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006555#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006556 }
6557 requiredsize = respos+repsize+(endp-collend);
6558 if (requiredsize > ressize) {
6559 if (requiredsize<2*ressize)
6560 requiredsize = 2*ressize;
6561 if (_PyBytes_Resize(&res, requiredsize))
6562 goto onError;
6563 str = PyBytes_AS_STRING(res) + respos;
6564 ressize = requiredsize;
6565 }
6566 /* generate replacement (temporarily (mis)uses p) */
6567 for (p = collstart; p < collend; ++p) {
6568 str += sprintf(str, "&#%d;", (int)*p);
6569 }
6570 p = collend;
6571 break;
6572 default:
6573 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
6574 encoding, reason, startp, size, &exc,
6575 collstart-startp, collend-startp, &newpos);
6576 if (repunicode == NULL)
6577 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006578 if (PyBytes_Check(repunicode)) {
6579 /* Directly copy bytes result to output. */
6580 repsize = PyBytes_Size(repunicode);
6581 if (repsize > 1) {
6582 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006583 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006584 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6585 Py_DECREF(repunicode);
6586 goto onError;
6587 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006588 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006589 ressize += repsize-1;
6590 }
6591 memcpy(str, PyBytes_AsString(repunicode), repsize);
6592 str += repsize;
6593 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006594 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006595 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006596 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006597 /* need more space? (at least enough for what we
6598 have+the replacement+the rest of the string, so
6599 we won't have to check space for encodable characters) */
6600 respos = str - PyBytes_AS_STRING(res);
6601 repsize = PyUnicode_GET_SIZE(repunicode);
6602 requiredsize = respos+repsize+(endp-collend);
6603 if (requiredsize > ressize) {
6604 if (requiredsize<2*ressize)
6605 requiredsize = 2*ressize;
6606 if (_PyBytes_Resize(&res, requiredsize)) {
6607 Py_DECREF(repunicode);
6608 goto onError;
6609 }
6610 str = PyBytes_AS_STRING(res) + respos;
6611 ressize = requiredsize;
6612 }
6613 /* check if there is anything unencodable in the replacement
6614 and copy it to the output */
6615 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
6616 c = *uni2;
6617 if (c >= limit) {
6618 raise_encode_exception(&exc, encoding, startp, size,
6619 unicodepos, unicodepos+1, reason);
6620 Py_DECREF(repunicode);
6621 goto onError;
6622 }
6623 *str = (char)c;
6624 }
6625 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006626 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006627 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006628 }
6629 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006630 /* Resize if we allocated to much */
6631 size = str - PyBytes_AS_STRING(res);
6632 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006633 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006634 if (_PyBytes_Resize(&res, size) < 0)
6635 goto onError;
6636 }
6637
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006638 Py_XDECREF(errorHandler);
6639 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006640 return res;
6641
6642 onError:
6643 Py_XDECREF(res);
6644 Py_XDECREF(errorHandler);
6645 Py_XDECREF(exc);
6646 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006647}
6648
Alexander Belopolsky40018472011-02-26 01:02:56 +00006649PyObject *
6650PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006651 Py_ssize_t size,
6652 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006653{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006654 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006655}
6656
Alexander Belopolsky40018472011-02-26 01:02:56 +00006657PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006658_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006659{
6660 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006661 PyErr_BadArgument();
6662 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006663 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006664 if (PyUnicode_READY(unicode) == -1)
6665 return NULL;
6666 /* Fast path: if it is a one-byte string, construct
6667 bytes object directly. */
6668 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6669 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6670 PyUnicode_GET_LENGTH(unicode));
6671 /* Non-Latin-1 characters present. Defer to above function to
6672 raise the exception. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006673 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006674 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006675 errors);
6676}
6677
6678PyObject*
6679PyUnicode_AsLatin1String(PyObject *unicode)
6680{
6681 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006682}
6683
6684/* --- 7-bit ASCII Codec -------------------------------------------------- */
6685
Alexander Belopolsky40018472011-02-26 01:02:56 +00006686PyObject *
6687PyUnicode_DecodeASCII(const char *s,
6688 Py_ssize_t size,
6689 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006690{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006691 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006692 PyUnicodeObject *v;
Victor Stinner702c7342011-10-05 13:50:52 +02006693 Py_UNICODE *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006694 Py_ssize_t startinpos;
6695 Py_ssize_t endinpos;
6696 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006697 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006698 int has_error;
6699 const unsigned char *p = (const unsigned char *)s;
6700 const unsigned char *end = p + size;
6701 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006702 PyObject *errorHandler = NULL;
6703 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006704
Guido van Rossumd57fd912000-03-10 22:53:23 +00006705 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006706 if (size == 1 && (unsigned char)s[0] < 128)
6707 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006708
Victor Stinner702c7342011-10-05 13:50:52 +02006709 has_error = 0;
6710 while (p < end && !has_error) {
6711 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6712 an explanation. */
6713 if (!((size_t) p & LONG_PTR_MASK)) {
6714 /* Help register allocation */
6715 register const unsigned char *_p = p;
6716 while (_p < aligned_end) {
6717 unsigned long value = *(unsigned long *) _p;
6718 if (value & ASCII_CHAR_MASK) {
6719 has_error = 1;
6720 break;
6721 }
6722 _p += SIZEOF_LONG;
6723 }
6724 if (_p == end)
6725 break;
6726 if (has_error)
6727 break;
6728 p = _p;
6729 }
6730 if (*p & 0x80) {
6731 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006732 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006733 }
6734 else {
6735 ++p;
6736 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006737 }
Victor Stinner702c7342011-10-05 13:50:52 +02006738 if (!has_error)
6739 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006740
Guido van Rossumd57fd912000-03-10 22:53:23 +00006741 v = _PyUnicode_New(size);
6742 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006743 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006744 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006745 return (PyObject *)v;
Victor Stinner702c7342011-10-05 13:50:52 +02006746 u = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006747 e = s + size;
6748 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006749 register unsigned char c = (unsigned char)*s;
6750 if (c < 128) {
Victor Stinner702c7342011-10-05 13:50:52 +02006751 *u++ = c;
Benjamin Peterson29060642009-01-31 22:14:21 +00006752 ++s;
6753 }
6754 else {
6755 startinpos = s-starts;
6756 endinpos = startinpos + 1;
Victor Stinner702c7342011-10-05 13:50:52 +02006757 outpos = u - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006758 if (unicode_decode_call_errorhandler(
6759 errors, &errorHandler,
6760 "ascii", "ordinal not in range(128)",
6761 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinner702c7342011-10-05 13:50:52 +02006762 &v, &outpos, &u))
Benjamin Peterson29060642009-01-31 22:14:21 +00006763 goto onError;
6764 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006765 }
Victor Stinner702c7342011-10-05 13:50:52 +02006766 if (u - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
6767 if (PyUnicode_Resize((PyObject**)&v, u - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006768 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006769 Py_XDECREF(errorHandler);
6770 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006771#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006772 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006773 Py_DECREF(v);
6774 return NULL;
6775 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006776#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006777 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006778 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006779
Benjamin Peterson29060642009-01-31 22:14:21 +00006780 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006781 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006782 Py_XDECREF(errorHandler);
6783 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006784 return NULL;
6785}
6786
Alexander Belopolsky40018472011-02-26 01:02:56 +00006787PyObject *
6788PyUnicode_EncodeASCII(const Py_UNICODE *p,
6789 Py_ssize_t size,
6790 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006791{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006792 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006793}
6794
Alexander Belopolsky40018472011-02-26 01:02:56 +00006795PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006796_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006797{
6798 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006799 PyErr_BadArgument();
6800 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006801 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006802 if (PyUnicode_READY(unicode) == -1)
6803 return NULL;
6804 /* Fast path: if it is an ASCII-only string, construct bytes object
6805 directly. Else defer to above function to raise the exception. */
6806 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6807 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6808 PyUnicode_GET_LENGTH(unicode));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006809 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006810 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006811 errors);
6812}
6813
6814PyObject *
6815PyUnicode_AsASCIIString(PyObject *unicode)
6816{
6817 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006818}
6819
Victor Stinner99b95382011-07-04 14:23:54 +02006820#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006821
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006822/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006823
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006824#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006825#define NEED_RETRY
6826#endif
6827
6828/* XXX This code is limited to "true" double-byte encodings, as
6829 a) it assumes an incomplete character consists of a single byte, and
6830 b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
Benjamin Peterson29060642009-01-31 22:14:21 +00006831 encodings, see IsDBCSLeadByteEx documentation. */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006832
Alexander Belopolsky40018472011-02-26 01:02:56 +00006833static int
6834is_dbcs_lead_byte(const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006835{
6836 const char *curr = s + offset;
6837
6838 if (IsDBCSLeadByte(*curr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006839 const char *prev = CharPrev(s, curr);
6840 return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006841 }
6842 return 0;
6843}
6844
6845/*
6846 * Decode MBCS string into unicode object. If 'final' is set, converts
6847 * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
6848 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006849static int
6850decode_mbcs(PyUnicodeObject **v,
6851 const char *s, /* MBCS string */
6852 int size, /* sizeof MBCS string */
6853 int final,
6854 const char *errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006855{
6856 Py_UNICODE *p;
Victor Stinner554f3f02010-06-16 23:33:54 +00006857 Py_ssize_t n;
6858 DWORD usize;
6859 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006860
6861 assert(size >= 0);
6862
Victor Stinner554f3f02010-06-16 23:33:54 +00006863 /* check and handle 'errors' arg */
6864 if (errors==NULL || strcmp(errors, "strict")==0)
6865 flags = MB_ERR_INVALID_CHARS;
6866 else if (strcmp(errors, "ignore")==0)
6867 flags = 0;
6868 else {
6869 PyErr_Format(PyExc_ValueError,
6870 "mbcs encoding does not support errors='%s'",
6871 errors);
6872 return -1;
6873 }
6874
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006875 /* Skip trailing lead-byte unless 'final' is set */
6876 if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006877 --size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006878
6879 /* First get the size of the result */
6880 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00006881 usize = MultiByteToWideChar(CP_ACP, flags, s, size, NULL, 0);
6882 if (usize==0)
6883 goto mbcs_decode_error;
6884 } else
6885 usize = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006886
6887 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006888 /* Create unicode object */
6889 *v = _PyUnicode_New(usize);
6890 if (*v == NULL)
6891 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00006892 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006893 }
6894 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006895 /* Extend unicode object */
6896 n = PyUnicode_GET_SIZE(*v);
Victor Stinner2fd82272011-10-03 04:06:05 +02006897 if (PyUnicode_Resize((PyObject**)v, n + usize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006898 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006899 }
6900
6901 /* Do the conversion */
Victor Stinner554f3f02010-06-16 23:33:54 +00006902 if (usize > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006903 p = PyUnicode_AS_UNICODE(*v) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00006904 if (0 == MultiByteToWideChar(CP_ACP, flags, s, size, p, usize)) {
6905 goto mbcs_decode_error;
Benjamin Peterson29060642009-01-31 22:14:21 +00006906 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006907 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006908 return size;
Victor Stinner554f3f02010-06-16 23:33:54 +00006909
6910mbcs_decode_error:
6911 /* If the last error was ERROR_NO_UNICODE_TRANSLATION, then
6912 we raise a UnicodeDecodeError - else it is a 'generic'
6913 windows error
6914 */
6915 if (GetLastError()==ERROR_NO_UNICODE_TRANSLATION) {
6916 /* Ideally, we should get reason from FormatMessage - this
6917 is the Windows 2000 English version of the message
6918 */
6919 PyObject *exc = NULL;
6920 const char *reason = "No mapping for the Unicode character exists "
6921 "in the target multi-byte code page.";
6922 make_decode_exception(&exc, "mbcs", s, size, 0, 0, reason);
6923 if (exc != NULL) {
6924 PyCodec_StrictErrors(exc);
6925 Py_DECREF(exc);
6926 }
6927 } else {
6928 PyErr_SetFromWindowsErrWithFilename(0, NULL);
6929 }
6930 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006931}
6932
Alexander Belopolsky40018472011-02-26 01:02:56 +00006933PyObject *
6934PyUnicode_DecodeMBCSStateful(const char *s,
6935 Py_ssize_t size,
6936 const char *errors,
6937 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006938{
6939 PyUnicodeObject *v = NULL;
6940 int done;
6941
6942 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006943 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006944
6945#ifdef NEED_RETRY
6946 retry:
6947 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00006948 done = decode_mbcs(&v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006949 else
6950#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00006951 done = decode_mbcs(&v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006952
6953 if (done < 0) {
6954 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006955 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006956 }
6957
6958 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006959 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006960
6961#ifdef NEED_RETRY
6962 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006963 s += done;
6964 size -= done;
6965 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006966 }
6967#endif
Victor Stinner17efeed2011-10-04 20:05:46 +02006968#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006969 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006970 Py_DECREF(v);
6971 return NULL;
6972 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006973#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006974 assert(_PyUnicode_CheckConsistency(v, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006975 return (PyObject *)v;
6976}
6977
Alexander Belopolsky40018472011-02-26 01:02:56 +00006978PyObject *
6979PyUnicode_DecodeMBCS(const char *s,
6980 Py_ssize_t size,
6981 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006982{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006983 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
6984}
6985
6986/*
6987 * Convert unicode into string object (MBCS).
6988 * Returns 0 if succeed, -1 otherwise.
6989 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006990static int
6991encode_mbcs(PyObject **repr,
6992 const Py_UNICODE *p, /* unicode */
6993 int size, /* size of unicode */
6994 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006995{
Victor Stinner554f3f02010-06-16 23:33:54 +00006996 BOOL usedDefaultChar = FALSE;
6997 BOOL *pusedDefaultChar;
6998 int mbcssize;
6999 Py_ssize_t n;
7000 PyObject *exc = NULL;
7001 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007002
7003 assert(size >= 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007004
Victor Stinner554f3f02010-06-16 23:33:54 +00007005 /* check and handle 'errors' arg */
7006 if (errors==NULL || strcmp(errors, "strict")==0) {
7007 flags = WC_NO_BEST_FIT_CHARS;
7008 pusedDefaultChar = &usedDefaultChar;
7009 } else if (strcmp(errors, "replace")==0) {
7010 flags = 0;
7011 pusedDefaultChar = NULL;
7012 } else {
7013 PyErr_Format(PyExc_ValueError,
7014 "mbcs encoding does not support errors='%s'",
7015 errors);
7016 return -1;
7017 }
7018
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007019 /* First get the size of the result */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007020 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00007021 mbcssize = WideCharToMultiByte(CP_ACP, flags, p, size, NULL, 0,
7022 NULL, pusedDefaultChar);
Benjamin Peterson29060642009-01-31 22:14:21 +00007023 if (mbcssize == 0) {
7024 PyErr_SetFromWindowsErrWithFilename(0, NULL);
7025 return -1;
7026 }
Victor Stinner554f3f02010-06-16 23:33:54 +00007027 /* If we used a default char, then we failed! */
7028 if (pusedDefaultChar && *pusedDefaultChar)
7029 goto mbcs_encode_error;
7030 } else {
7031 mbcssize = 0;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007032 }
7033
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007034 if (*repr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007035 /* Create string object */
7036 *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
7037 if (*repr == NULL)
7038 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00007039 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007040 }
7041 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007042 /* Extend string object */
7043 n = PyBytes_Size(*repr);
7044 if (_PyBytes_Resize(repr, n + mbcssize) < 0)
7045 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007046 }
7047
7048 /* Do the conversion */
7049 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007050 char *s = PyBytes_AS_STRING(*repr) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00007051 if (0 == WideCharToMultiByte(CP_ACP, flags, p, size, s, mbcssize,
7052 NULL, pusedDefaultChar)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007053 PyErr_SetFromWindowsErrWithFilename(0, NULL);
7054 return -1;
7055 }
Victor Stinner554f3f02010-06-16 23:33:54 +00007056 if (pusedDefaultChar && *pusedDefaultChar)
7057 goto mbcs_encode_error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007058 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007059 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007060
7061mbcs_encode_error:
7062 raise_encode_exception(&exc, "mbcs", p, size, 0, 0, "invalid character");
7063 Py_XDECREF(exc);
7064 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007065}
7066
Alexander Belopolsky40018472011-02-26 01:02:56 +00007067PyObject *
7068PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7069 Py_ssize_t size,
7070 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007071{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007072 PyObject *repr = NULL;
7073 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00007074
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007075#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00007076 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007077 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00007078 ret = encode_mbcs(&repr, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007079 else
7080#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00007081 ret = encode_mbcs(&repr, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007082
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007083 if (ret < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007084 Py_XDECREF(repr);
7085 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007086 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007087
7088#ifdef NEED_RETRY
7089 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007090 p += INT_MAX;
7091 size -= INT_MAX;
7092 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007093 }
7094#endif
7095
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007096 return repr;
7097}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007098
Alexander Belopolsky40018472011-02-26 01:02:56 +00007099PyObject *
7100PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007101{
7102 if (!PyUnicode_Check(unicode)) {
7103 PyErr_BadArgument();
7104 return NULL;
7105 }
7106 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00007107 PyUnicode_GET_SIZE(unicode),
7108 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007109}
7110
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007111#undef NEED_RETRY
7112
Victor Stinner99b95382011-07-04 14:23:54 +02007113#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007114
Guido van Rossumd57fd912000-03-10 22:53:23 +00007115/* --- Character Mapping Codec -------------------------------------------- */
7116
Alexander Belopolsky40018472011-02-26 01:02:56 +00007117PyObject *
7118PyUnicode_DecodeCharmap(const char *s,
7119 Py_ssize_t size,
7120 PyObject *mapping,
7121 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007122{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007123 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007124 Py_ssize_t startinpos;
7125 Py_ssize_t endinpos;
7126 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007127 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007128 PyUnicodeObject *v;
7129 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007130 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007131 PyObject *errorHandler = NULL;
7132 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007133 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007134 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00007135
Guido van Rossumd57fd912000-03-10 22:53:23 +00007136 /* Default to Latin-1 */
7137 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007138 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007139
7140 v = _PyUnicode_New(size);
7141 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007142 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007143 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007144 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007145 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007146 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007147 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007148 mapstring = PyUnicode_AS_UNICODE(mapping);
7149 maplen = PyUnicode_GET_SIZE(mapping);
7150 while (s < e) {
7151 unsigned char ch = *s;
7152 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007153
Benjamin Peterson29060642009-01-31 22:14:21 +00007154 if (ch < maplen)
7155 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00007156
Benjamin Peterson29060642009-01-31 22:14:21 +00007157 if (x == 0xfffe) {
7158 /* undefined mapping */
7159 outpos = p-PyUnicode_AS_UNICODE(v);
7160 startinpos = s-starts;
7161 endinpos = startinpos+1;
7162 if (unicode_decode_call_errorhandler(
7163 errors, &errorHandler,
7164 "charmap", "character maps to <undefined>",
7165 &starts, &e, &startinpos, &endinpos, &exc, &s,
7166 &v, &outpos, &p)) {
7167 goto onError;
7168 }
7169 continue;
7170 }
7171 *p++ = x;
7172 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007173 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007174 }
7175 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007176 while (s < e) {
7177 unsigned char ch = *s;
7178 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007179
Benjamin Peterson29060642009-01-31 22:14:21 +00007180 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7181 w = PyLong_FromLong((long)ch);
7182 if (w == NULL)
7183 goto onError;
7184 x = PyObject_GetItem(mapping, w);
7185 Py_DECREF(w);
7186 if (x == NULL) {
7187 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7188 /* No mapping found means: mapping is undefined. */
7189 PyErr_Clear();
7190 x = Py_None;
7191 Py_INCREF(x);
7192 } else
7193 goto onError;
7194 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007195
Benjamin Peterson29060642009-01-31 22:14:21 +00007196 /* Apply mapping */
7197 if (PyLong_Check(x)) {
7198 long value = PyLong_AS_LONG(x);
7199 if (value < 0 || value > 65535) {
7200 PyErr_SetString(PyExc_TypeError,
7201 "character mapping must be in range(65536)");
7202 Py_DECREF(x);
7203 goto onError;
7204 }
7205 *p++ = (Py_UNICODE)value;
7206 }
7207 else if (x == Py_None) {
7208 /* undefined mapping */
7209 outpos = p-PyUnicode_AS_UNICODE(v);
7210 startinpos = s-starts;
7211 endinpos = startinpos+1;
7212 if (unicode_decode_call_errorhandler(
7213 errors, &errorHandler,
7214 "charmap", "character maps to <undefined>",
7215 &starts, &e, &startinpos, &endinpos, &exc, &s,
7216 &v, &outpos, &p)) {
7217 Py_DECREF(x);
7218 goto onError;
7219 }
7220 Py_DECREF(x);
7221 continue;
7222 }
7223 else if (PyUnicode_Check(x)) {
7224 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007225
Benjamin Peterson29060642009-01-31 22:14:21 +00007226 if (targetsize == 1)
7227 /* 1-1 mapping */
7228 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007229
Benjamin Peterson29060642009-01-31 22:14:21 +00007230 else if (targetsize > 1) {
7231 /* 1-n mapping */
7232 if (targetsize > extrachars) {
7233 /* resize first */
7234 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
7235 Py_ssize_t needed = (targetsize - extrachars) + \
7236 (targetsize << 2);
7237 extrachars += needed;
7238 /* XXX overflow detection missing */
Victor Stinnerfe226c02011-10-03 03:52:20 +02007239 if (PyUnicode_Resize((PyObject**)&v,
Benjamin Peterson29060642009-01-31 22:14:21 +00007240 PyUnicode_GET_SIZE(v) + needed) < 0) {
7241 Py_DECREF(x);
7242 goto onError;
7243 }
7244 p = PyUnicode_AS_UNICODE(v) + oldpos;
7245 }
7246 Py_UNICODE_COPY(p,
7247 PyUnicode_AS_UNICODE(x),
7248 targetsize);
7249 p += targetsize;
7250 extrachars -= targetsize;
7251 }
7252 /* 1-0 mapping: skip the character */
7253 }
7254 else {
7255 /* wrong return value */
7256 PyErr_SetString(PyExc_TypeError,
7257 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007258 Py_DECREF(x);
7259 goto onError;
7260 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007261 Py_DECREF(x);
7262 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007263 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007264 }
7265 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Victor Stinnerfe226c02011-10-03 03:52:20 +02007266 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007267 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007268 Py_XDECREF(errorHandler);
7269 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02007270#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007271 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007272 Py_DECREF(v);
7273 return NULL;
7274 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007275#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007276 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007277 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00007278
Benjamin Peterson29060642009-01-31 22:14:21 +00007279 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007280 Py_XDECREF(errorHandler);
7281 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007282 Py_XDECREF(v);
7283 return NULL;
7284}
7285
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007286/* Charmap encoding: the lookup table */
7287
Alexander Belopolsky40018472011-02-26 01:02:56 +00007288struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007289 PyObject_HEAD
7290 unsigned char level1[32];
7291 int count2, count3;
7292 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007293};
7294
7295static PyObject*
7296encoding_map_size(PyObject *obj, PyObject* args)
7297{
7298 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007299 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007300 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007301}
7302
7303static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007304 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007305 PyDoc_STR("Return the size (in bytes) of this object") },
7306 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007307};
7308
7309static void
7310encoding_map_dealloc(PyObject* o)
7311{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007312 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007313}
7314
7315static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007316 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007317 "EncodingMap", /*tp_name*/
7318 sizeof(struct encoding_map), /*tp_basicsize*/
7319 0, /*tp_itemsize*/
7320 /* methods */
7321 encoding_map_dealloc, /*tp_dealloc*/
7322 0, /*tp_print*/
7323 0, /*tp_getattr*/
7324 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007325 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007326 0, /*tp_repr*/
7327 0, /*tp_as_number*/
7328 0, /*tp_as_sequence*/
7329 0, /*tp_as_mapping*/
7330 0, /*tp_hash*/
7331 0, /*tp_call*/
7332 0, /*tp_str*/
7333 0, /*tp_getattro*/
7334 0, /*tp_setattro*/
7335 0, /*tp_as_buffer*/
7336 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7337 0, /*tp_doc*/
7338 0, /*tp_traverse*/
7339 0, /*tp_clear*/
7340 0, /*tp_richcompare*/
7341 0, /*tp_weaklistoffset*/
7342 0, /*tp_iter*/
7343 0, /*tp_iternext*/
7344 encoding_map_methods, /*tp_methods*/
7345 0, /*tp_members*/
7346 0, /*tp_getset*/
7347 0, /*tp_base*/
7348 0, /*tp_dict*/
7349 0, /*tp_descr_get*/
7350 0, /*tp_descr_set*/
7351 0, /*tp_dictoffset*/
7352 0, /*tp_init*/
7353 0, /*tp_alloc*/
7354 0, /*tp_new*/
7355 0, /*tp_free*/
7356 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007357};
7358
7359PyObject*
7360PyUnicode_BuildEncodingMap(PyObject* string)
7361{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007362 PyObject *result;
7363 struct encoding_map *mresult;
7364 int i;
7365 int need_dict = 0;
7366 unsigned char level1[32];
7367 unsigned char level2[512];
7368 unsigned char *mlevel1, *mlevel2, *mlevel3;
7369 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007370 int kind;
7371 void *data;
7372 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007373
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007374 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007375 PyErr_BadArgument();
7376 return NULL;
7377 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007378 kind = PyUnicode_KIND(string);
7379 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007380 memset(level1, 0xFF, sizeof level1);
7381 memset(level2, 0xFF, sizeof level2);
7382
7383 /* If there isn't a one-to-one mapping of NULL to \0,
7384 or if there are non-BMP characters, we need to use
7385 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007386 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007387 need_dict = 1;
7388 for (i = 1; i < 256; i++) {
7389 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007390 ch = PyUnicode_READ(kind, data, i);
7391 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007392 need_dict = 1;
7393 break;
7394 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007395 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007396 /* unmapped character */
7397 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007398 l1 = ch >> 11;
7399 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007400 if (level1[l1] == 0xFF)
7401 level1[l1] = count2++;
7402 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007403 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007404 }
7405
7406 if (count2 >= 0xFF || count3 >= 0xFF)
7407 need_dict = 1;
7408
7409 if (need_dict) {
7410 PyObject *result = PyDict_New();
7411 PyObject *key, *value;
7412 if (!result)
7413 return NULL;
7414 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007415 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007416 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007417 if (!key || !value)
7418 goto failed1;
7419 if (PyDict_SetItem(result, key, value) == -1)
7420 goto failed1;
7421 Py_DECREF(key);
7422 Py_DECREF(value);
7423 }
7424 return result;
7425 failed1:
7426 Py_XDECREF(key);
7427 Py_XDECREF(value);
7428 Py_DECREF(result);
7429 return NULL;
7430 }
7431
7432 /* Create a three-level trie */
7433 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7434 16*count2 + 128*count3 - 1);
7435 if (!result)
7436 return PyErr_NoMemory();
7437 PyObject_Init(result, &EncodingMapType);
7438 mresult = (struct encoding_map*)result;
7439 mresult->count2 = count2;
7440 mresult->count3 = count3;
7441 mlevel1 = mresult->level1;
7442 mlevel2 = mresult->level23;
7443 mlevel3 = mresult->level23 + 16*count2;
7444 memcpy(mlevel1, level1, 32);
7445 memset(mlevel2, 0xFF, 16*count2);
7446 memset(mlevel3, 0, 128*count3);
7447 count3 = 0;
7448 for (i = 1; i < 256; i++) {
7449 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007450 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007451 /* unmapped character */
7452 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007453 o1 = PyUnicode_READ(kind, data, i)>>11;
7454 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007455 i2 = 16*mlevel1[o1] + o2;
7456 if (mlevel2[i2] == 0xFF)
7457 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007458 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007459 i3 = 128*mlevel2[i2] + o3;
7460 mlevel3[i3] = i;
7461 }
7462 return result;
7463}
7464
7465static int
7466encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
7467{
7468 struct encoding_map *map = (struct encoding_map*)mapping;
7469 int l1 = c>>11;
7470 int l2 = (c>>7) & 0xF;
7471 int l3 = c & 0x7F;
7472 int i;
7473
7474#ifdef Py_UNICODE_WIDE
7475 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007476 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007477 }
7478#endif
7479 if (c == 0)
7480 return 0;
7481 /* level 1*/
7482 i = map->level1[l1];
7483 if (i == 0xFF) {
7484 return -1;
7485 }
7486 /* level 2*/
7487 i = map->level23[16*i+l2];
7488 if (i == 0xFF) {
7489 return -1;
7490 }
7491 /* level 3 */
7492 i = map->level23[16*map->count2 + 128*i + l3];
7493 if (i == 0) {
7494 return -1;
7495 }
7496 return i;
7497}
7498
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007499/* Lookup the character ch in the mapping. If the character
7500 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007501 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007502static PyObject *
7503charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007504{
Christian Heimes217cfd12007-12-02 14:31:20 +00007505 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007506 PyObject *x;
7507
7508 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007509 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007510 x = PyObject_GetItem(mapping, w);
7511 Py_DECREF(w);
7512 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007513 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7514 /* No mapping found means: mapping is undefined. */
7515 PyErr_Clear();
7516 x = Py_None;
7517 Py_INCREF(x);
7518 return x;
7519 } else
7520 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007521 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007522 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007523 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007524 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007525 long value = PyLong_AS_LONG(x);
7526 if (value < 0 || value > 255) {
7527 PyErr_SetString(PyExc_TypeError,
7528 "character mapping must be in range(256)");
7529 Py_DECREF(x);
7530 return NULL;
7531 }
7532 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007533 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007534 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007535 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007536 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007537 /* wrong return value */
7538 PyErr_Format(PyExc_TypeError,
7539 "character mapping must return integer, bytes or None, not %.400s",
7540 x->ob_type->tp_name);
7541 Py_DECREF(x);
7542 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007543 }
7544}
7545
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007546static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007547charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007548{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007549 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7550 /* exponentially overallocate to minimize reallocations */
7551 if (requiredsize < 2*outsize)
7552 requiredsize = 2*outsize;
7553 if (_PyBytes_Resize(outobj, requiredsize))
7554 return -1;
7555 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007556}
7557
Benjamin Peterson14339b62009-01-31 16:36:08 +00007558typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007559 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007560} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007561/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007562 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007563 space is available. Return a new reference to the object that
7564 was put in the output buffer, or Py_None, if the mapping was undefined
7565 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007566 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007567static charmapencode_result
7568charmapencode_output(Py_UNICODE c, PyObject *mapping,
7569 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007570{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007571 PyObject *rep;
7572 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007573 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007574
Christian Heimes90aa7642007-12-19 02:45:37 +00007575 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007576 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007577 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007578 if (res == -1)
7579 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007580 if (outsize<requiredsize)
7581 if (charmapencode_resize(outobj, outpos, requiredsize))
7582 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007583 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007584 outstart[(*outpos)++] = (char)res;
7585 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007586 }
7587
7588 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007589 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007590 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007591 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007592 Py_DECREF(rep);
7593 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007594 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007595 if (PyLong_Check(rep)) {
7596 Py_ssize_t requiredsize = *outpos+1;
7597 if (outsize<requiredsize)
7598 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7599 Py_DECREF(rep);
7600 return enc_EXCEPTION;
7601 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007602 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007603 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007604 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007605 else {
7606 const char *repchars = PyBytes_AS_STRING(rep);
7607 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7608 Py_ssize_t requiredsize = *outpos+repsize;
7609 if (outsize<requiredsize)
7610 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7611 Py_DECREF(rep);
7612 return enc_EXCEPTION;
7613 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007614 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007615 memcpy(outstart + *outpos, repchars, repsize);
7616 *outpos += repsize;
7617 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007618 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007619 Py_DECREF(rep);
7620 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007621}
7622
7623/* handle an error in PyUnicode_EncodeCharmap
7624 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007625static int
7626charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00007627 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007628 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007629 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007630 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007631{
7632 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007633 Py_ssize_t repsize;
7634 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007635 Py_UNICODE *uni2;
7636 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007637 Py_ssize_t collstartpos = *inpos;
7638 Py_ssize_t collendpos = *inpos+1;
7639 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007640 char *encoding = "charmap";
7641 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007642 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007643
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007644 /* find all unencodable characters */
7645 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007646 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007647 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007648 int res = encoding_map_lookup(p[collendpos], mapping);
7649 if (res != -1)
7650 break;
7651 ++collendpos;
7652 continue;
7653 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007654
Benjamin Peterson29060642009-01-31 22:14:21 +00007655 rep = charmapencode_lookup(p[collendpos], mapping);
7656 if (rep==NULL)
7657 return -1;
7658 else if (rep!=Py_None) {
7659 Py_DECREF(rep);
7660 break;
7661 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007662 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007663 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007664 }
7665 /* cache callback name lookup
7666 * (if not done yet, i.e. it's the first error) */
7667 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007668 if ((errors==NULL) || (!strcmp(errors, "strict")))
7669 *known_errorHandler = 1;
7670 else if (!strcmp(errors, "replace"))
7671 *known_errorHandler = 2;
7672 else if (!strcmp(errors, "ignore"))
7673 *known_errorHandler = 3;
7674 else if (!strcmp(errors, "xmlcharrefreplace"))
7675 *known_errorHandler = 4;
7676 else
7677 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007678 }
7679 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007680 case 1: /* strict */
7681 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7682 return -1;
7683 case 2: /* replace */
7684 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007685 x = charmapencode_output('?', mapping, res, respos);
7686 if (x==enc_EXCEPTION) {
7687 return -1;
7688 }
7689 else if (x==enc_FAILED) {
7690 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7691 return -1;
7692 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007693 }
7694 /* fall through */
7695 case 3: /* ignore */
7696 *inpos = collendpos;
7697 break;
7698 case 4: /* xmlcharrefreplace */
7699 /* generate replacement (temporarily (mis)uses p) */
7700 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007701 char buffer[2+29+1+1];
7702 char *cp;
7703 sprintf(buffer, "&#%d;", (int)p[collpos]);
7704 for (cp = buffer; *cp; ++cp) {
7705 x = charmapencode_output(*cp, mapping, res, respos);
7706 if (x==enc_EXCEPTION)
7707 return -1;
7708 else if (x==enc_FAILED) {
7709 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7710 return -1;
7711 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007712 }
7713 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007714 *inpos = collendpos;
7715 break;
7716 default:
7717 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00007718 encoding, reason, p, size, exceptionObject,
7719 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007720 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007721 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00007722 if (PyBytes_Check(repunicode)) {
7723 /* Directly copy bytes result to output. */
7724 Py_ssize_t outsize = PyBytes_Size(*res);
7725 Py_ssize_t requiredsize;
7726 repsize = PyBytes_Size(repunicode);
7727 requiredsize = *respos + repsize;
7728 if (requiredsize > outsize)
7729 /* Make room for all additional bytes. */
7730 if (charmapencode_resize(res, respos, requiredsize)) {
7731 Py_DECREF(repunicode);
7732 return -1;
7733 }
7734 memcpy(PyBytes_AsString(*res) + *respos,
7735 PyBytes_AsString(repunicode), repsize);
7736 *respos += repsize;
7737 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007738 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00007739 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007740 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007741 /* generate replacement */
7742 repsize = PyUnicode_GET_SIZE(repunicode);
7743 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007744 x = charmapencode_output(*uni2, mapping, res, respos);
7745 if (x==enc_EXCEPTION) {
7746 return -1;
7747 }
7748 else if (x==enc_FAILED) {
7749 Py_DECREF(repunicode);
7750 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7751 return -1;
7752 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007753 }
7754 *inpos = newpos;
7755 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007756 }
7757 return 0;
7758}
7759
Alexander Belopolsky40018472011-02-26 01:02:56 +00007760PyObject *
7761PyUnicode_EncodeCharmap(const Py_UNICODE *p,
7762 Py_ssize_t size,
7763 PyObject *mapping,
7764 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007765{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007766 /* output object */
7767 PyObject *res = NULL;
7768 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007769 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007770 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007771 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007772 PyObject *errorHandler = NULL;
7773 PyObject *exc = NULL;
7774 /* the following variable is used for caching string comparisons
7775 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
7776 * 3=ignore, 4=xmlcharrefreplace */
7777 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007778
7779 /* Default to Latin-1 */
7780 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007781 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007782
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007783 /* allocate enough for a simple encoding without
7784 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00007785 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007786 if (res == NULL)
7787 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00007788 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007789 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007790
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007791 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007792 /* try to encode it */
7793 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
7794 if (x==enc_EXCEPTION) /* error */
7795 goto onError;
7796 if (x==enc_FAILED) { /* unencodable character */
7797 if (charmap_encoding_error(p, size, &inpos, mapping,
7798 &exc,
7799 &known_errorHandler, &errorHandler, errors,
7800 &res, &respos)) {
7801 goto onError;
7802 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007803 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007804 else
7805 /* done with this character => adjust input position */
7806 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007807 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007808
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007809 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00007810 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00007811 if (_PyBytes_Resize(&res, respos) < 0)
7812 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00007813
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007814 Py_XDECREF(exc);
7815 Py_XDECREF(errorHandler);
7816 return res;
7817
Benjamin Peterson29060642009-01-31 22:14:21 +00007818 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007819 Py_XDECREF(res);
7820 Py_XDECREF(exc);
7821 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007822 return NULL;
7823}
7824
Alexander Belopolsky40018472011-02-26 01:02:56 +00007825PyObject *
7826PyUnicode_AsCharmapString(PyObject *unicode,
7827 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007828{
7829 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007830 PyErr_BadArgument();
7831 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007832 }
7833 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00007834 PyUnicode_GET_SIZE(unicode),
7835 mapping,
7836 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007837}
7838
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007839/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007840static void
7841make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007842 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007843 Py_ssize_t startpos, Py_ssize_t endpos,
7844 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007845{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007846 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007847 *exceptionObject = _PyUnicodeTranslateError_Create(
7848 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007849 }
7850 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007851 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
7852 goto onError;
7853 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
7854 goto onError;
7855 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
7856 goto onError;
7857 return;
7858 onError:
7859 Py_DECREF(*exceptionObject);
7860 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007861 }
7862}
7863
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007864/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007865static void
7866raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007867 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007868 Py_ssize_t startpos, Py_ssize_t endpos,
7869 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007870{
7871 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007872 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007873 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007874 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007875}
7876
7877/* error handling callback helper:
7878 build arguments, call the callback and check the arguments,
7879 put the result into newpos and return the replacement string, which
7880 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007881static PyObject *
7882unicode_translate_call_errorhandler(const char *errors,
7883 PyObject **errorHandler,
7884 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007885 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007886 Py_ssize_t startpos, Py_ssize_t endpos,
7887 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007888{
Benjamin Peterson142957c2008-07-04 19:55:29 +00007889 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007890
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007891 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007892 PyObject *restuple;
7893 PyObject *resunicode;
7894
7895 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007896 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007897 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007898 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007899 }
7900
7901 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007902 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007903 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007904 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007905
7906 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00007907 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007908 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007909 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007910 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00007911 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00007912 Py_DECREF(restuple);
7913 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007914 }
7915 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00007916 &resunicode, &i_newpos)) {
7917 Py_DECREF(restuple);
7918 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007919 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00007920 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007921 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007922 else
7923 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007924 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007925 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
7926 Py_DECREF(restuple);
7927 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00007928 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007929 Py_INCREF(resunicode);
7930 Py_DECREF(restuple);
7931 return resunicode;
7932}
7933
7934/* Lookup the character ch in the mapping and put the result in result,
7935 which must be decrefed by the caller.
7936 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007937static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007938charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007939{
Christian Heimes217cfd12007-12-02 14:31:20 +00007940 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007941 PyObject *x;
7942
7943 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007944 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007945 x = PyObject_GetItem(mapping, w);
7946 Py_DECREF(w);
7947 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007948 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7949 /* No mapping found means: use 1:1 mapping. */
7950 PyErr_Clear();
7951 *result = NULL;
7952 return 0;
7953 } else
7954 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007955 }
7956 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007957 *result = x;
7958 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007959 }
Christian Heimes217cfd12007-12-02 14:31:20 +00007960 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007961 long value = PyLong_AS_LONG(x);
7962 long max = PyUnicode_GetMax();
7963 if (value < 0 || value > max) {
7964 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00007965 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00007966 Py_DECREF(x);
7967 return -1;
7968 }
7969 *result = x;
7970 return 0;
7971 }
7972 else if (PyUnicode_Check(x)) {
7973 *result = x;
7974 return 0;
7975 }
7976 else {
7977 /* wrong return value */
7978 PyErr_SetString(PyExc_TypeError,
7979 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007980 Py_DECREF(x);
7981 return -1;
7982 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007983}
7984/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00007985 if not reallocate and adjust various state variables.
7986 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007987static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007988charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00007989 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007990{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007991 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00007992 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007993 /* exponentially overallocate to minimize reallocations */
7994 if (requiredsize < 2 * oldsize)
7995 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007996 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
7997 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007998 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007999 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008000 }
8001 return 0;
8002}
8003/* lookup the character, put the result in the output string and adjust
8004 various state variables. Return a new reference to the object that
8005 was put in the output buffer in *result, or Py_None, if the mapping was
8006 undefined (in which case no character was written).
8007 The called must decref result.
8008 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008009static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008010charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8011 PyObject *mapping, Py_UCS4 **output,
8012 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008013 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008014{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008015 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8016 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008017 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008018 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008019 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008020 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008021 }
8022 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008023 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008024 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008025 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008026 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008027 }
8028 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008029 Py_ssize_t repsize;
8030 if (PyUnicode_READY(*res) == -1)
8031 return -1;
8032 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008033 if (repsize==1) {
8034 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008035 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008036 }
8037 else if (repsize!=0) {
8038 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008039 Py_ssize_t requiredsize = *opos +
8040 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008041 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008042 Py_ssize_t i;
8043 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008044 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008045 for(i = 0; i < repsize; i++)
8046 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008047 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008048 }
8049 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008050 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008051 return 0;
8052}
8053
Alexander Belopolsky40018472011-02-26 01:02:56 +00008054PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008055_PyUnicode_TranslateCharmap(PyObject *input,
8056 PyObject *mapping,
8057 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008058{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008059 /* input object */
8060 char *idata;
8061 Py_ssize_t size, i;
8062 int kind;
8063 /* output buffer */
8064 Py_UCS4 *output = NULL;
8065 Py_ssize_t osize;
8066 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008067 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008068 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008069 char *reason = "character maps to <undefined>";
8070 PyObject *errorHandler = NULL;
8071 PyObject *exc = NULL;
8072 /* the following variable is used for caching string comparisons
8073 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8074 * 3=ignore, 4=xmlcharrefreplace */
8075 int known_errorHandler = -1;
8076
Guido van Rossumd57fd912000-03-10 22:53:23 +00008077 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008078 PyErr_BadArgument();
8079 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008080 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008081
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008082 if (PyUnicode_READY(input) == -1)
8083 return NULL;
8084 idata = (char*)PyUnicode_DATA(input);
8085 kind = PyUnicode_KIND(input);
8086 size = PyUnicode_GET_LENGTH(input);
8087 i = 0;
8088
8089 if (size == 0) {
8090 Py_INCREF(input);
8091 return input;
8092 }
8093
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008094 /* allocate enough for a simple 1:1 translation without
8095 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008096 osize = size;
8097 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8098 opos = 0;
8099 if (output == NULL) {
8100 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008101 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008102 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008103
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008104 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008105 /* try to encode it */
8106 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008107 if (charmaptranslate_output(input, i, mapping,
8108 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008109 Py_XDECREF(x);
8110 goto onError;
8111 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008112 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008113 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008114 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008115 else { /* untranslatable character */
8116 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8117 Py_ssize_t repsize;
8118 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008119 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008120 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008121 Py_ssize_t collstart = i;
8122 Py_ssize_t collend = i+1;
8123 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008124
Benjamin Peterson29060642009-01-31 22:14:21 +00008125 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008126 while (collend < size) {
8127 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008128 goto onError;
8129 Py_XDECREF(x);
8130 if (x!=Py_None)
8131 break;
8132 ++collend;
8133 }
8134 /* cache callback name lookup
8135 * (if not done yet, i.e. it's the first error) */
8136 if (known_errorHandler==-1) {
8137 if ((errors==NULL) || (!strcmp(errors, "strict")))
8138 known_errorHandler = 1;
8139 else if (!strcmp(errors, "replace"))
8140 known_errorHandler = 2;
8141 else if (!strcmp(errors, "ignore"))
8142 known_errorHandler = 3;
8143 else if (!strcmp(errors, "xmlcharrefreplace"))
8144 known_errorHandler = 4;
8145 else
8146 known_errorHandler = 0;
8147 }
8148 switch (known_errorHandler) {
8149 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008150 raise_translate_exception(&exc, input, collstart,
8151 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008152 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008153 case 2: /* replace */
8154 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008155 for (coll = collstart; coll<collend; coll++)
8156 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008157 /* fall through */
8158 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008159 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008160 break;
8161 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008162 /* generate replacement (temporarily (mis)uses i) */
8163 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008164 char buffer[2+29+1+1];
8165 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008166 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8167 if (charmaptranslate_makespace(&output, &osize,
8168 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008169 goto onError;
8170 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008171 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008172 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008173 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008174 break;
8175 default:
8176 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008177 reason, input, &exc,
8178 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008179 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008180 goto onError;
8181 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008182 repsize = PyUnicode_GET_LENGTH(repunicode);
8183 if (charmaptranslate_makespace(&output, &osize,
8184 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008185 Py_DECREF(repunicode);
8186 goto onError;
8187 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008188 for (uni2 = 0; repsize-->0; ++uni2)
8189 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8190 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008191 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008192 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008193 }
8194 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008195 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8196 if (!res)
8197 goto onError;
8198 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008199 Py_XDECREF(exc);
8200 Py_XDECREF(errorHandler);
8201 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008202
Benjamin Peterson29060642009-01-31 22:14:21 +00008203 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008204 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008205 Py_XDECREF(exc);
8206 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008207 return NULL;
8208}
8209
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008210/* Deprecated. Use PyUnicode_Translate instead. */
8211PyObject *
8212PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8213 Py_ssize_t size,
8214 PyObject *mapping,
8215 const char *errors)
8216{
8217 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8218 if (!unicode)
8219 return NULL;
8220 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8221}
8222
Alexander Belopolsky40018472011-02-26 01:02:56 +00008223PyObject *
8224PyUnicode_Translate(PyObject *str,
8225 PyObject *mapping,
8226 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008227{
8228 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008229
Guido van Rossumd57fd912000-03-10 22:53:23 +00008230 str = PyUnicode_FromObject(str);
8231 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008232 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008233 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008234 Py_DECREF(str);
8235 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008236
Benjamin Peterson29060642009-01-31 22:14:21 +00008237 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008238 Py_XDECREF(str);
8239 return NULL;
8240}
Tim Petersced69f82003-09-16 20:30:58 +00008241
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008242static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008243fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008244{
8245 /* No need to call PyUnicode_READY(self) because this function is only
8246 called as a callback from fixup() which does it already. */
8247 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8248 const int kind = PyUnicode_KIND(self);
8249 void *data = PyUnicode_DATA(self);
8250 Py_UCS4 maxchar = 0, ch, fixed;
8251 Py_ssize_t i;
8252
8253 for (i = 0; i < len; ++i) {
8254 ch = PyUnicode_READ(kind, data, i);
8255 fixed = 0;
8256 if (ch > 127) {
8257 if (Py_UNICODE_ISSPACE(ch))
8258 fixed = ' ';
8259 else {
8260 const int decimal = Py_UNICODE_TODECIMAL(ch);
8261 if (decimal >= 0)
8262 fixed = '0' + decimal;
8263 }
8264 if (fixed != 0) {
8265 if (fixed > maxchar)
8266 maxchar = fixed;
8267 PyUnicode_WRITE(kind, data, i, fixed);
8268 }
8269 else if (ch > maxchar)
8270 maxchar = ch;
8271 }
8272 else if (ch > maxchar)
8273 maxchar = ch;
8274 }
8275
8276 return maxchar;
8277}
8278
8279PyObject *
8280_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8281{
8282 if (!PyUnicode_Check(unicode)) {
8283 PyErr_BadInternalCall();
8284 return NULL;
8285 }
8286 if (PyUnicode_READY(unicode) == -1)
8287 return NULL;
8288 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8289 /* If the string is already ASCII, just return the same string */
8290 Py_INCREF(unicode);
8291 return unicode;
8292 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008293 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008294}
8295
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008296PyObject *
8297PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8298 Py_ssize_t length)
8299{
8300 PyObject *result;
8301 Py_UNICODE *p; /* write pointer into result */
8302 Py_ssize_t i;
8303 /* Copy to a new string */
8304 result = (PyObject *)_PyUnicode_New(length);
8305 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8306 if (result == NULL)
8307 return result;
8308 p = PyUnicode_AS_UNICODE(result);
8309 /* Iterate over code points */
8310 for (i = 0; i < length; i++) {
8311 Py_UNICODE ch =s[i];
8312 if (ch > 127) {
8313 int decimal = Py_UNICODE_TODECIMAL(ch);
8314 if (decimal >= 0)
8315 p[i] = '0' + decimal;
8316 }
8317 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008318#ifndef DONT_MAKE_RESULT_READY
8319 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008320 Py_DECREF(result);
8321 return NULL;
8322 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008323#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008324 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008325 return result;
8326}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008327/* --- Decimal Encoder ---------------------------------------------------- */
8328
Alexander Belopolsky40018472011-02-26 01:02:56 +00008329int
8330PyUnicode_EncodeDecimal(Py_UNICODE *s,
8331 Py_ssize_t length,
8332 char *output,
8333 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008334{
8335 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008336 PyObject *errorHandler = NULL;
8337 PyObject *exc = NULL;
8338 const char *encoding = "decimal";
8339 const char *reason = "invalid decimal Unicode string";
8340 /* the following variable is used for caching string comparisons
8341 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8342 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008343
8344 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008345 PyErr_BadArgument();
8346 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008347 }
8348
8349 p = s;
8350 end = s + length;
8351 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008352 register Py_UNICODE ch = *p;
8353 int decimal;
8354 PyObject *repunicode;
8355 Py_ssize_t repsize;
8356 Py_ssize_t newpos;
8357 Py_UNICODE *uni2;
8358 Py_UNICODE *collstart;
8359 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008360
Benjamin Peterson29060642009-01-31 22:14:21 +00008361 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008362 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008363 ++p;
8364 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008365 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008366 decimal = Py_UNICODE_TODECIMAL(ch);
8367 if (decimal >= 0) {
8368 *output++ = '0' + decimal;
8369 ++p;
8370 continue;
8371 }
8372 if (0 < ch && ch < 256) {
8373 *output++ = (char)ch;
8374 ++p;
8375 continue;
8376 }
8377 /* All other characters are considered unencodable */
8378 collstart = p;
8379 collend = p+1;
8380 while (collend < end) {
8381 if ((0 < *collend && *collend < 256) ||
8382 !Py_UNICODE_ISSPACE(*collend) ||
8383 Py_UNICODE_TODECIMAL(*collend))
8384 break;
8385 }
8386 /* cache callback name lookup
8387 * (if not done yet, i.e. it's the first error) */
8388 if (known_errorHandler==-1) {
8389 if ((errors==NULL) || (!strcmp(errors, "strict")))
8390 known_errorHandler = 1;
8391 else if (!strcmp(errors, "replace"))
8392 known_errorHandler = 2;
8393 else if (!strcmp(errors, "ignore"))
8394 known_errorHandler = 3;
8395 else if (!strcmp(errors, "xmlcharrefreplace"))
8396 known_errorHandler = 4;
8397 else
8398 known_errorHandler = 0;
8399 }
8400 switch (known_errorHandler) {
8401 case 1: /* strict */
8402 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
8403 goto onError;
8404 case 2: /* replace */
8405 for (p = collstart; p < collend; ++p)
8406 *output++ = '?';
8407 /* fall through */
8408 case 3: /* ignore */
8409 p = collend;
8410 break;
8411 case 4: /* xmlcharrefreplace */
8412 /* generate replacement (temporarily (mis)uses p) */
8413 for (p = collstart; p < collend; ++p)
8414 output += sprintf(output, "&#%d;", (int)*p);
8415 p = collend;
8416 break;
8417 default:
8418 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
8419 encoding, reason, s, length, &exc,
8420 collstart-s, collend-s, &newpos);
8421 if (repunicode == NULL)
8422 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008423 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008424 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008425 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8426 Py_DECREF(repunicode);
8427 goto onError;
8428 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008429 /* generate replacement */
8430 repsize = PyUnicode_GET_SIZE(repunicode);
8431 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
8432 Py_UNICODE ch = *uni2;
8433 if (Py_UNICODE_ISSPACE(ch))
8434 *output++ = ' ';
8435 else {
8436 decimal = Py_UNICODE_TODECIMAL(ch);
8437 if (decimal >= 0)
8438 *output++ = '0' + decimal;
8439 else if (0 < ch && ch < 256)
8440 *output++ = (char)ch;
8441 else {
8442 Py_DECREF(repunicode);
8443 raise_encode_exception(&exc, encoding,
8444 s, length, collstart-s, collend-s, reason);
8445 goto onError;
8446 }
8447 }
8448 }
8449 p = s + newpos;
8450 Py_DECREF(repunicode);
8451 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008452 }
8453 /* 0-terminate the output string */
8454 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008455 Py_XDECREF(exc);
8456 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008457 return 0;
8458
Benjamin Peterson29060642009-01-31 22:14:21 +00008459 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008460 Py_XDECREF(exc);
8461 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008462 return -1;
8463}
8464
Guido van Rossumd57fd912000-03-10 22:53:23 +00008465/* --- Helpers ------------------------------------------------------------ */
8466
Victor Stinnerc3cec782011-10-05 21:24:08 +02008467#include "stringlib/asciilib.h"
8468#include "stringlib/fastsearch.h"
8469#include "stringlib/partition.h"
8470#include "stringlib/split.h"
8471#include "stringlib/count.h"
8472#include "stringlib/find.h"
8473#include "stringlib/localeutil.h"
8474#include "stringlib/undef.h"
8475
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008476#include "stringlib/ucs1lib.h"
8477#include "stringlib/fastsearch.h"
8478#include "stringlib/partition.h"
8479#include "stringlib/split.h"
8480#include "stringlib/count.h"
8481#include "stringlib/find.h"
8482#include "stringlib/localeutil.h"
8483#include "stringlib/undef.h"
8484
8485#include "stringlib/ucs2lib.h"
8486#include "stringlib/fastsearch.h"
8487#include "stringlib/partition.h"
8488#include "stringlib/split.h"
8489#include "stringlib/count.h"
8490#include "stringlib/find.h"
8491#include "stringlib/localeutil.h"
8492#include "stringlib/undef.h"
8493
8494#include "stringlib/ucs4lib.h"
8495#include "stringlib/fastsearch.h"
8496#include "stringlib/partition.h"
8497#include "stringlib/split.h"
8498#include "stringlib/count.h"
8499#include "stringlib/find.h"
8500#include "stringlib/localeutil.h"
8501#include "stringlib/undef.h"
8502
8503static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02008504any_find_slice(Py_ssize_t Py_LOCAL_CALLBACK(ascii)(const Py_UCS1*, Py_ssize_t,
8505 const Py_UCS1*, Py_ssize_t,
8506 Py_ssize_t, Py_ssize_t),
8507 Py_ssize_t Py_LOCAL_CALLBACK(ucs1)(const Py_UCS1*, Py_ssize_t,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008508 const Py_UCS1*, Py_ssize_t,
8509 Py_ssize_t, Py_ssize_t),
8510 Py_ssize_t Py_LOCAL_CALLBACK(ucs2)(const Py_UCS2*, Py_ssize_t,
8511 const Py_UCS2*, Py_ssize_t,
8512 Py_ssize_t, Py_ssize_t),
8513 Py_ssize_t Py_LOCAL_CALLBACK(ucs4)(const Py_UCS4*, Py_ssize_t,
8514 const Py_UCS4*, Py_ssize_t,
8515 Py_ssize_t, Py_ssize_t),
8516 PyObject* s1, PyObject* s2,
8517 Py_ssize_t start,
8518 Py_ssize_t end)
8519{
8520 int kind1, kind2, kind;
8521 void *buf1, *buf2;
8522 Py_ssize_t len1, len2, result;
8523
8524 kind1 = PyUnicode_KIND(s1);
8525 kind2 = PyUnicode_KIND(s2);
8526 kind = kind1 > kind2 ? kind1 : kind2;
8527 buf1 = PyUnicode_DATA(s1);
8528 buf2 = PyUnicode_DATA(s2);
8529 if (kind1 != kind)
8530 buf1 = _PyUnicode_AsKind(s1, kind);
8531 if (!buf1)
8532 return -2;
8533 if (kind2 != kind)
8534 buf2 = _PyUnicode_AsKind(s2, kind);
8535 if (!buf2) {
8536 if (kind1 != kind) PyMem_Free(buf1);
8537 return -2;
8538 }
8539 len1 = PyUnicode_GET_LENGTH(s1);
8540 len2 = PyUnicode_GET_LENGTH(s2);
8541
8542 switch(kind) {
8543 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008544 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8545 result = ascii(buf1, len1, buf2, len2, start, end);
8546 else
8547 result = ucs1(buf1, len1, buf2, len2, start, end);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008548 break;
8549 case PyUnicode_2BYTE_KIND:
8550 result = ucs2(buf1, len1, buf2, len2, start, end);
8551 break;
8552 case PyUnicode_4BYTE_KIND:
8553 result = ucs4(buf1, len1, buf2, len2, start, end);
8554 break;
8555 default:
8556 assert(0); result = -2;
8557 }
8558
8559 if (kind1 != kind)
8560 PyMem_Free(buf1);
8561 if (kind2 != kind)
8562 PyMem_Free(buf2);
8563
8564 return result;
8565}
8566
8567Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02008568_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008569 Py_ssize_t n_buffer,
8570 void *digits, Py_ssize_t n_digits,
8571 Py_ssize_t min_width,
8572 const char *grouping,
8573 const char *thousands_sep)
8574{
8575 switch(kind) {
8576 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008577 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
8578 return _PyUnicode_ascii_InsertThousandsGrouping(
8579 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
8580 min_width, grouping, thousands_sep);
8581 else
8582 return _PyUnicode_ucs1_InsertThousandsGrouping(
8583 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
8584 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008585 case PyUnicode_2BYTE_KIND:
8586 return _PyUnicode_ucs2_InsertThousandsGrouping(
8587 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
8588 min_width, grouping, thousands_sep);
8589 case PyUnicode_4BYTE_KIND:
8590 return _PyUnicode_ucs4_InsertThousandsGrouping(
8591 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
8592 min_width, grouping, thousands_sep);
8593 }
8594 assert(0);
8595 return -1;
8596}
8597
8598
Eric Smith8c663262007-08-25 02:26:07 +00008599#include "stringlib/unicodedefs.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00008600#include "stringlib/fastsearch.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008601
Thomas Wouters477c8d52006-05-27 19:21:47 +00008602#include "stringlib/count.h"
8603#include "stringlib/find.h"
Eric Smith5807c412008-05-11 21:00:57 +00008604
Thomas Wouters477c8d52006-05-27 19:21:47 +00008605/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008606#define ADJUST_INDICES(start, end, len) \
8607 if (end > len) \
8608 end = len; \
8609 else if (end < 0) { \
8610 end += len; \
8611 if (end < 0) \
8612 end = 0; \
8613 } \
8614 if (start < 0) { \
8615 start += len; \
8616 if (start < 0) \
8617 start = 0; \
8618 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008619
Alexander Belopolsky40018472011-02-26 01:02:56 +00008620Py_ssize_t
8621PyUnicode_Count(PyObject *str,
8622 PyObject *substr,
8623 Py_ssize_t start,
8624 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008625{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008626 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008627 PyUnicodeObject* str_obj;
8628 PyUnicodeObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008629 int kind1, kind2, kind;
8630 void *buf1 = NULL, *buf2 = NULL;
8631 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008632
Thomas Wouters477c8d52006-05-27 19:21:47 +00008633 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008634 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008635 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008636 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02008637 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008638 Py_DECREF(str_obj);
8639 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008640 }
Tim Petersced69f82003-09-16 20:30:58 +00008641
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008642 kind1 = PyUnicode_KIND(str_obj);
8643 kind2 = PyUnicode_KIND(sub_obj);
8644 kind = kind1 > kind2 ? kind1 : kind2;
8645 buf1 = PyUnicode_DATA(str_obj);
8646 if (kind1 != kind)
8647 buf1 = _PyUnicode_AsKind((PyObject*)str_obj, kind);
8648 if (!buf1)
8649 goto onError;
8650 buf2 = PyUnicode_DATA(sub_obj);
8651 if (kind2 != kind)
8652 buf2 = _PyUnicode_AsKind((PyObject*)sub_obj, kind);
8653 if (!buf2)
8654 goto onError;
8655 len1 = PyUnicode_GET_LENGTH(str_obj);
8656 len2 = PyUnicode_GET_LENGTH(sub_obj);
8657
8658 ADJUST_INDICES(start, end, len1);
8659 switch(kind) {
8660 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008661 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
8662 result = asciilib_count(
8663 ((Py_UCS1*)buf1) + start, end - start,
8664 buf2, len2, PY_SSIZE_T_MAX
8665 );
8666 else
8667 result = ucs1lib_count(
8668 ((Py_UCS1*)buf1) + start, end - start,
8669 buf2, len2, PY_SSIZE_T_MAX
8670 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008671 break;
8672 case PyUnicode_2BYTE_KIND:
8673 result = ucs2lib_count(
8674 ((Py_UCS2*)buf1) + start, end - start,
8675 buf2, len2, PY_SSIZE_T_MAX
8676 );
8677 break;
8678 case PyUnicode_4BYTE_KIND:
8679 result = ucs4lib_count(
8680 ((Py_UCS4*)buf1) + start, end - start,
8681 buf2, len2, PY_SSIZE_T_MAX
8682 );
8683 break;
8684 default:
8685 assert(0); result = 0;
8686 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008687
8688 Py_DECREF(sub_obj);
8689 Py_DECREF(str_obj);
8690
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008691 if (kind1 != kind)
8692 PyMem_Free(buf1);
8693 if (kind2 != kind)
8694 PyMem_Free(buf2);
8695
Guido van Rossumd57fd912000-03-10 22:53:23 +00008696 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008697 onError:
8698 Py_DECREF(sub_obj);
8699 Py_DECREF(str_obj);
8700 if (kind1 != kind && buf1)
8701 PyMem_Free(buf1);
8702 if (kind2 != kind && buf2)
8703 PyMem_Free(buf2);
8704 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008705}
8706
Alexander Belopolsky40018472011-02-26 01:02:56 +00008707Py_ssize_t
8708PyUnicode_Find(PyObject *str,
8709 PyObject *sub,
8710 Py_ssize_t start,
8711 Py_ssize_t end,
8712 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008713{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008714 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008715
Guido van Rossumd57fd912000-03-10 22:53:23 +00008716 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008717 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008718 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008719 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008720 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008721 Py_DECREF(str);
8722 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008723 }
Tim Petersced69f82003-09-16 20:30:58 +00008724
Thomas Wouters477c8d52006-05-27 19:21:47 +00008725 if (direction > 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008726 result = any_find_slice(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008727 asciilib_find_slice, ucs1lib_find_slice,
8728 ucs2lib_find_slice, ucs4lib_find_slice,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008729 str, sub, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +00008730 );
8731 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008732 result = any_find_slice(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008733 asciilib_find_slice, ucs1lib_rfind_slice,
8734 ucs2lib_rfind_slice, ucs4lib_rfind_slice,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008735 str, sub, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +00008736 );
8737
Guido van Rossumd57fd912000-03-10 22:53:23 +00008738 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008739 Py_DECREF(sub);
8740
Guido van Rossumd57fd912000-03-10 22:53:23 +00008741 return result;
8742}
8743
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008744Py_ssize_t
8745PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
8746 Py_ssize_t start, Py_ssize_t end,
8747 int direction)
8748{
8749 char *result;
8750 int kind;
8751 if (PyUnicode_READY(str) == -1)
8752 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02008753 if (start < 0 || end < 0) {
8754 PyErr_SetString(PyExc_IndexError, "string index out of range");
8755 return -2;
8756 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008757 if (end > PyUnicode_GET_LENGTH(str))
8758 end = PyUnicode_GET_LENGTH(str);
8759 kind = PyUnicode_KIND(str);
8760 result = findchar(PyUnicode_1BYTE_DATA(str)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02008761 + kind*start,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008762 kind,
8763 end-start, ch, direction);
8764 if (!result)
8765 return -1;
8766 return (result-(char*)PyUnicode_DATA(str)) >> (kind-1);
8767}
8768
Alexander Belopolsky40018472011-02-26 01:02:56 +00008769static int
8770tailmatch(PyUnicodeObject *self,
8771 PyUnicodeObject *substring,
8772 Py_ssize_t start,
8773 Py_ssize_t end,
8774 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008775{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008776 int kind_self;
8777 int kind_sub;
8778 void *data_self;
8779 void *data_sub;
8780 Py_ssize_t offset;
8781 Py_ssize_t i;
8782 Py_ssize_t end_sub;
8783
8784 if (PyUnicode_READY(self) == -1 ||
8785 PyUnicode_READY(substring) == -1)
8786 return 0;
8787
8788 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008789 return 1;
8790
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008791 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
8792 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008793 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00008794 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008795
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008796 kind_self = PyUnicode_KIND(self);
8797 data_self = PyUnicode_DATA(self);
8798 kind_sub = PyUnicode_KIND(substring);
8799 data_sub = PyUnicode_DATA(substring);
8800 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
8801
8802 if (direction > 0)
8803 offset = end;
8804 else
8805 offset = start;
8806
8807 if (PyUnicode_READ(kind_self, data_self, offset) ==
8808 PyUnicode_READ(kind_sub, data_sub, 0) &&
8809 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
8810 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
8811 /* If both are of the same kind, memcmp is sufficient */
8812 if (kind_self == kind_sub) {
8813 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02008814 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008815 data_sub,
8816 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02008817 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008818 }
8819 /* otherwise we have to compare each character by first accesing it */
8820 else {
8821 /* We do not need to compare 0 and len(substring)-1 because
8822 the if statement above ensured already that they are equal
8823 when we end up here. */
8824 // TODO: honor direction and do a forward or backwards search
8825 for (i = 1; i < end_sub; ++i) {
8826 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
8827 PyUnicode_READ(kind_sub, data_sub, i))
8828 return 0;
8829 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008830 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008831 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008832 }
8833
8834 return 0;
8835}
8836
Alexander Belopolsky40018472011-02-26 01:02:56 +00008837Py_ssize_t
8838PyUnicode_Tailmatch(PyObject *str,
8839 PyObject *substr,
8840 Py_ssize_t start,
8841 Py_ssize_t end,
8842 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008843{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008844 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008845
Guido van Rossumd57fd912000-03-10 22:53:23 +00008846 str = PyUnicode_FromObject(str);
8847 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008848 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008849 substr = PyUnicode_FromObject(substr);
8850 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008851 Py_DECREF(str);
8852 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008853 }
Tim Petersced69f82003-09-16 20:30:58 +00008854
Guido van Rossumd57fd912000-03-10 22:53:23 +00008855 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00008856 (PyUnicodeObject *)substr,
8857 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008858 Py_DECREF(str);
8859 Py_DECREF(substr);
8860 return result;
8861}
8862
Guido van Rossumd57fd912000-03-10 22:53:23 +00008863/* Apply fixfct filter to the Unicode object self and return a
8864 reference to the modified object */
8865
Alexander Belopolsky40018472011-02-26 01:02:56 +00008866static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02008867fixup(PyObject *self,
8868 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008869{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008870 PyObject *u;
8871 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008872
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008873 if (PyUnicode_READY(self) == -1)
8874 return NULL;
8875 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
8876 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
8877 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008878 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008879 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00008880
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008881 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02008882 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00008883
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008884 /* fix functions return the new maximum character in a string,
8885 if the kind of the resulting unicode object does not change,
8886 everything is fine. Otherwise we need to change the string kind
8887 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02008888 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008889 if (maxchar_new == 0)
8890 /* do nothing, keep maxchar_new at 0 which means no changes. */;
8891 else if (maxchar_new <= 127)
8892 maxchar_new = 127;
8893 else if (maxchar_new <= 255)
8894 maxchar_new = 255;
8895 else if (maxchar_new <= 65535)
8896 maxchar_new = 65535;
8897 else
8898 maxchar_new = 1114111; /* 0x10ffff */
8899
8900 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008901 /* fixfct should return TRUE if it modified the buffer. If
8902 FALSE, return a reference to the original buffer instead
8903 (to save space, not time) */
8904 Py_INCREF(self);
8905 Py_DECREF(u);
8906 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008907 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008908 else if (maxchar_new == maxchar_old) {
8909 return u;
8910 }
8911 else {
8912 /* In case the maximum character changed, we need to
8913 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008914 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008915 if (v == NULL) {
8916 Py_DECREF(u);
8917 return NULL;
8918 }
8919 if (maxchar_new > maxchar_old) {
8920 /* If the maxchar increased so that the kind changed, not all
8921 characters are representable anymore and we need to fix the
8922 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02008923 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02008924 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008925 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
8926 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008927 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02008928 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008929 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008930
8931 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008932 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008933 return v;
8934 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008935}
8936
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008937static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008938fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008939{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008940 /* No need to call PyUnicode_READY(self) because this function is only
8941 called as a callback from fixup() which does it already. */
8942 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8943 const int kind = PyUnicode_KIND(self);
8944 void *data = PyUnicode_DATA(self);
8945 int touched = 0;
8946 Py_UCS4 maxchar = 0;
8947 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008948
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008949 for (i = 0; i < len; ++i) {
8950 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8951 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
8952 if (up != ch) {
8953 if (up > maxchar)
8954 maxchar = up;
8955 PyUnicode_WRITE(kind, data, i, up);
8956 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008957 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008958 else if (ch > maxchar)
8959 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008960 }
8961
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008962 if (touched)
8963 return maxchar;
8964 else
8965 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008966}
8967
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008968static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008969fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008970{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008971 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8972 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8973 const int kind = PyUnicode_KIND(self);
8974 void *data = PyUnicode_DATA(self);
8975 int touched = 0;
8976 Py_UCS4 maxchar = 0;
8977 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008978
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008979 for(i = 0; i < len; ++i) {
8980 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8981 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
8982 if (lo != ch) {
8983 if (lo > maxchar)
8984 maxchar = lo;
8985 PyUnicode_WRITE(kind, data, i, lo);
8986 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008987 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008988 else if (ch > maxchar)
8989 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008990 }
8991
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008992 if (touched)
8993 return maxchar;
8994 else
8995 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008996}
8997
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008998static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008999fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009000{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009001 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9002 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9003 const int kind = PyUnicode_KIND(self);
9004 void *data = PyUnicode_DATA(self);
9005 int touched = 0;
9006 Py_UCS4 maxchar = 0;
9007 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009008
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009009 for(i = 0; i < len; ++i) {
9010 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9011 Py_UCS4 nu = 0;
9012
9013 if (Py_UNICODE_ISUPPER(ch))
9014 nu = Py_UNICODE_TOLOWER(ch);
9015 else if (Py_UNICODE_ISLOWER(ch))
9016 nu = Py_UNICODE_TOUPPER(ch);
9017
9018 if (nu != 0) {
9019 if (nu > maxchar)
9020 maxchar = nu;
9021 PyUnicode_WRITE(kind, data, i, nu);
9022 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009023 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009024 else if (ch > maxchar)
9025 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009026 }
9027
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009028 if (touched)
9029 return maxchar;
9030 else
9031 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009032}
9033
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009034static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009035fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009036{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009037 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9038 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9039 const int kind = PyUnicode_KIND(self);
9040 void *data = PyUnicode_DATA(self);
9041 int touched = 0;
9042 Py_UCS4 maxchar = 0;
9043 Py_ssize_t i = 0;
9044 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009045
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009046 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009047 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009048
9049 ch = PyUnicode_READ(kind, data, i);
9050 if (!Py_UNICODE_ISUPPER(ch)) {
9051 maxchar = Py_UNICODE_TOUPPER(ch);
9052 PyUnicode_WRITE(kind, data, i, maxchar);
9053 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009054 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009055 ++i;
9056 for(; i < len; ++i) {
9057 ch = PyUnicode_READ(kind, data, i);
9058 if (!Py_UNICODE_ISLOWER(ch)) {
9059 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9060 if (lo > maxchar)
9061 maxchar = lo;
9062 PyUnicode_WRITE(kind, data, i, lo);
9063 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009064 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009065 else if (ch > maxchar)
9066 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009067 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009068
9069 if (touched)
9070 return maxchar;
9071 else
9072 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009073}
9074
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009075static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009076fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009077{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009078 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9079 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9080 const int kind = PyUnicode_KIND(self);
9081 void *data = PyUnicode_DATA(self);
9082 Py_UCS4 maxchar = 0;
9083 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009084 int previous_is_cased;
9085
9086 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009087 if (len == 1) {
9088 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9089 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9090 if (ti != ch) {
9091 PyUnicode_WRITE(kind, data, i, ti);
9092 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009093 }
9094 else
9095 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009096 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009097 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009098 for(; i < len; ++i) {
9099 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9100 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009101
Benjamin Peterson29060642009-01-31 22:14:21 +00009102 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009103 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009104 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009105 nu = Py_UNICODE_TOTITLE(ch);
9106
9107 if (nu > maxchar)
9108 maxchar = nu;
9109 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009110
Benjamin Peterson29060642009-01-31 22:14:21 +00009111 if (Py_UNICODE_ISLOWER(ch) ||
9112 Py_UNICODE_ISUPPER(ch) ||
9113 Py_UNICODE_ISTITLE(ch))
9114 previous_is_cased = 1;
9115 else
9116 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009117 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009118 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009119}
9120
Tim Peters8ce9f162004-08-27 01:49:32 +00009121PyObject *
9122PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009123{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009124 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009125 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009126 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009127 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009128 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9129 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009130 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009131 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009132 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009133 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009134 int use_memcpy;
9135 unsigned char *res_data = NULL, *sep_data = NULL;
9136 PyObject *last_obj;
9137 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009138
Tim Peters05eba1f2004-08-27 21:32:02 +00009139 fseq = PySequence_Fast(seq, "");
9140 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009141 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009142 }
9143
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009144 /* NOTE: the following code can't call back into Python code,
9145 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009146 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009147
Tim Peters05eba1f2004-08-27 21:32:02 +00009148 seqlen = PySequence_Fast_GET_SIZE(fseq);
9149 /* If empty sequence, return u"". */
9150 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009151 Py_DECREF(fseq);
9152 Py_INCREF(unicode_empty);
9153 res = unicode_empty;
9154 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009155 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009156
Tim Peters05eba1f2004-08-27 21:32:02 +00009157 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009158 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009159 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009160 if (seqlen == 1) {
9161 if (PyUnicode_CheckExact(items[0])) {
9162 res = items[0];
9163 Py_INCREF(res);
9164 Py_DECREF(fseq);
9165 return res;
9166 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009167 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009168 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009169 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009170 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009171 /* Set up sep and seplen */
9172 if (separator == NULL) {
9173 /* fall back to a blank space separator */
9174 sep = PyUnicode_FromOrdinal(' ');
9175 if (!sep)
9176 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009177 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009178 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009179 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009180 else {
9181 if (!PyUnicode_Check(separator)) {
9182 PyErr_Format(PyExc_TypeError,
9183 "separator: expected str instance,"
9184 " %.80s found",
9185 Py_TYPE(separator)->tp_name);
9186 goto onError;
9187 }
9188 if (PyUnicode_READY(separator))
9189 goto onError;
9190 sep = separator;
9191 seplen = PyUnicode_GET_LENGTH(separator);
9192 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9193 /* inc refcount to keep this code path symmetric with the
9194 above case of a blank separator */
9195 Py_INCREF(sep);
9196 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009197 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009198 }
9199
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009200 /* There are at least two things to join, or else we have a subclass
9201 * of str in the sequence.
9202 * Do a pre-pass to figure out the total amount of space we'll
9203 * need (sz), and see whether all argument are strings.
9204 */
9205 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009206#ifdef Py_DEBUG
9207 use_memcpy = 0;
9208#else
9209 use_memcpy = 1;
9210#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009211 for (i = 0; i < seqlen; i++) {
9212 const Py_ssize_t old_sz = sz;
9213 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009214 if (!PyUnicode_Check(item)) {
9215 PyErr_Format(PyExc_TypeError,
9216 "sequence item %zd: expected str instance,"
9217 " %.80s found",
9218 i, Py_TYPE(item)->tp_name);
9219 goto onError;
9220 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009221 if (PyUnicode_READY(item) == -1)
9222 goto onError;
9223 sz += PyUnicode_GET_LENGTH(item);
9224 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009225 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009226 if (i != 0)
9227 sz += seplen;
9228 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9229 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009230 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009231 goto onError;
9232 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009233 if (use_memcpy && last_obj != NULL) {
9234 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9235 use_memcpy = 0;
9236 }
9237 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009238 }
Tim Petersced69f82003-09-16 20:30:58 +00009239
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009240 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009241 if (res == NULL)
9242 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009243
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009244 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009245#ifdef Py_DEBUG
9246 use_memcpy = 0;
9247#else
9248 if (use_memcpy) {
9249 res_data = PyUnicode_1BYTE_DATA(res);
9250 kind = PyUnicode_KIND(res);
9251 if (seplen != 0)
9252 sep_data = PyUnicode_1BYTE_DATA(sep);
9253 }
9254#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009255 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009256 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009257 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009258 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009259 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009260 if (use_memcpy) {
9261 Py_MEMCPY(res_data,
9262 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009263 kind * seplen);
9264 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009265 }
9266 else {
9267 copy_characters(res, res_offset, sep, 0, seplen);
9268 res_offset += seplen;
9269 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009270 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009271 itemlen = PyUnicode_GET_LENGTH(item);
9272 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009273 if (use_memcpy) {
9274 Py_MEMCPY(res_data,
9275 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009276 kind * itemlen);
9277 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009278 }
9279 else {
9280 copy_characters(res, res_offset, item, 0, itemlen);
9281 res_offset += itemlen;
9282 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009283 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009284 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009285 if (use_memcpy)
9286 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009287 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009288 else
9289 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009290
Tim Peters05eba1f2004-08-27 21:32:02 +00009291 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009292 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009293 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009294 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009295
Benjamin Peterson29060642009-01-31 22:14:21 +00009296 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009297 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009298 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009299 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009300 return NULL;
9301}
9302
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009303#define FILL(kind, data, value, start, length) \
9304 do { \
9305 Py_ssize_t i_ = 0; \
9306 assert(kind != PyUnicode_WCHAR_KIND); \
9307 switch ((kind)) { \
9308 case PyUnicode_1BYTE_KIND: { \
9309 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9310 memset(to_, (unsigned char)value, length); \
9311 break; \
9312 } \
9313 case PyUnicode_2BYTE_KIND: { \
9314 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9315 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9316 break; \
9317 } \
9318 default: { \
9319 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9320 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9321 break; \
9322 } \
9323 } \
9324 } while (0)
9325
Victor Stinner9310abb2011-10-05 00:59:23 +02009326static PyObject *
9327pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009328 Py_ssize_t left,
9329 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009330 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009331{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009332 PyObject *u;
9333 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009334 int kind;
9335 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009336
9337 if (left < 0)
9338 left = 0;
9339 if (right < 0)
9340 right = 0;
9341
Tim Peters7a29bd52001-09-12 03:03:31 +00009342 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009343 Py_INCREF(self);
9344 return self;
9345 }
9346
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009347 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9348 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009349 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9350 return NULL;
9351 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009352 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9353 if (fill > maxchar)
9354 maxchar = fill;
9355 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009356 if (!u)
9357 return NULL;
9358
9359 kind = PyUnicode_KIND(u);
9360 data = PyUnicode_DATA(u);
9361 if (left)
9362 FILL(kind, data, fill, 0, left);
9363 if (right)
9364 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009365 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009366 assert(_PyUnicode_CheckConsistency(u, 1));
9367 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009368}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009369#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009370
Alexander Belopolsky40018472011-02-26 01:02:56 +00009371PyObject *
9372PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009373{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009374 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009375
9376 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009377 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009378 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009379
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009380 switch(PyUnicode_KIND(string)) {
9381 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009382 if (PyUnicode_IS_ASCII(string))
9383 list = asciilib_splitlines(
9384 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9385 PyUnicode_GET_LENGTH(string), keepends);
9386 else
9387 list = ucs1lib_splitlines(
9388 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9389 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009390 break;
9391 case PyUnicode_2BYTE_KIND:
9392 list = ucs2lib_splitlines(
9393 (PyObject*) string, PyUnicode_2BYTE_DATA(string),
9394 PyUnicode_GET_LENGTH(string), keepends);
9395 break;
9396 case PyUnicode_4BYTE_KIND:
9397 list = ucs4lib_splitlines(
9398 (PyObject*) string, PyUnicode_4BYTE_DATA(string),
9399 PyUnicode_GET_LENGTH(string), keepends);
9400 break;
9401 default:
9402 assert(0);
9403 list = 0;
9404 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009405 Py_DECREF(string);
9406 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009407}
9408
Alexander Belopolsky40018472011-02-26 01:02:56 +00009409static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009410split(PyObject *self,
9411 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009412 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009413{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009414 int kind1, kind2, kind;
9415 void *buf1, *buf2;
9416 Py_ssize_t len1, len2;
9417 PyObject* out;
9418
Guido van Rossumd57fd912000-03-10 22:53:23 +00009419 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009420 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009421
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009422 if (PyUnicode_READY(self) == -1)
9423 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009424
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009425 if (substring == NULL)
9426 switch(PyUnicode_KIND(self)) {
9427 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009428 if (PyUnicode_IS_ASCII(self))
9429 return asciilib_split_whitespace(
9430 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9431 PyUnicode_GET_LENGTH(self), maxcount
9432 );
9433 else
9434 return ucs1lib_split_whitespace(
9435 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9436 PyUnicode_GET_LENGTH(self), maxcount
9437 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009438 case PyUnicode_2BYTE_KIND:
9439 return ucs2lib_split_whitespace(
9440 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9441 PyUnicode_GET_LENGTH(self), maxcount
9442 );
9443 case PyUnicode_4BYTE_KIND:
9444 return ucs4lib_split_whitespace(
9445 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
9446 PyUnicode_GET_LENGTH(self), maxcount
9447 );
9448 default:
9449 assert(0);
9450 return NULL;
9451 }
9452
9453 if (PyUnicode_READY(substring) == -1)
9454 return NULL;
9455
9456 kind1 = PyUnicode_KIND(self);
9457 kind2 = PyUnicode_KIND(substring);
9458 kind = kind1 > kind2 ? kind1 : kind2;
9459 buf1 = PyUnicode_DATA(self);
9460 buf2 = PyUnicode_DATA(substring);
9461 if (kind1 != kind)
9462 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9463 if (!buf1)
9464 return NULL;
9465 if (kind2 != kind)
9466 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9467 if (!buf2) {
9468 if (kind1 != kind) PyMem_Free(buf1);
9469 return NULL;
9470 }
9471 len1 = PyUnicode_GET_LENGTH(self);
9472 len2 = PyUnicode_GET_LENGTH(substring);
9473
9474 switch(kind) {
9475 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009476 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9477 out = asciilib_split(
9478 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9479 else
9480 out = ucs1lib_split(
9481 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009482 break;
9483 case PyUnicode_2BYTE_KIND:
9484 out = ucs2lib_split(
9485 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9486 break;
9487 case PyUnicode_4BYTE_KIND:
9488 out = ucs4lib_split(
9489 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9490 break;
9491 default:
9492 out = NULL;
9493 }
9494 if (kind1 != kind)
9495 PyMem_Free(buf1);
9496 if (kind2 != kind)
9497 PyMem_Free(buf2);
9498 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009499}
9500
Alexander Belopolsky40018472011-02-26 01:02:56 +00009501static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009502rsplit(PyObject *self,
9503 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009504 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009505{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009506 int kind1, kind2, kind;
9507 void *buf1, *buf2;
9508 Py_ssize_t len1, len2;
9509 PyObject* out;
9510
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009511 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009512 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009513
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009514 if (PyUnicode_READY(self) == -1)
9515 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009516
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009517 if (substring == NULL)
9518 switch(PyUnicode_KIND(self)) {
9519 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009520 if (PyUnicode_IS_ASCII(self))
9521 return asciilib_rsplit_whitespace(
9522 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9523 PyUnicode_GET_LENGTH(self), maxcount
9524 );
9525 else
9526 return ucs1lib_rsplit_whitespace(
9527 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9528 PyUnicode_GET_LENGTH(self), maxcount
9529 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009530 case PyUnicode_2BYTE_KIND:
9531 return ucs2lib_rsplit_whitespace(
9532 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9533 PyUnicode_GET_LENGTH(self), maxcount
9534 );
9535 case PyUnicode_4BYTE_KIND:
9536 return ucs4lib_rsplit_whitespace(
9537 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
9538 PyUnicode_GET_LENGTH(self), maxcount
9539 );
9540 default:
9541 assert(0);
9542 return NULL;
9543 }
9544
9545 if (PyUnicode_READY(substring) == -1)
9546 return NULL;
9547
9548 kind1 = PyUnicode_KIND(self);
9549 kind2 = PyUnicode_KIND(substring);
9550 kind = kind1 > kind2 ? kind1 : kind2;
9551 buf1 = PyUnicode_DATA(self);
9552 buf2 = PyUnicode_DATA(substring);
9553 if (kind1 != kind)
9554 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9555 if (!buf1)
9556 return NULL;
9557 if (kind2 != kind)
9558 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9559 if (!buf2) {
9560 if (kind1 != kind) PyMem_Free(buf1);
9561 return NULL;
9562 }
9563 len1 = PyUnicode_GET_LENGTH(self);
9564 len2 = PyUnicode_GET_LENGTH(substring);
9565
9566 switch(kind) {
9567 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009568 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9569 out = asciilib_rsplit(
9570 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9571 else
9572 out = ucs1lib_rsplit(
9573 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009574 break;
9575 case PyUnicode_2BYTE_KIND:
9576 out = ucs2lib_rsplit(
9577 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9578 break;
9579 case PyUnicode_4BYTE_KIND:
9580 out = ucs4lib_rsplit(
9581 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9582 break;
9583 default:
9584 out = NULL;
9585 }
9586 if (kind1 != kind)
9587 PyMem_Free(buf1);
9588 if (kind2 != kind)
9589 PyMem_Free(buf2);
9590 return out;
9591}
9592
9593static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009594anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9595 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009596{
9597 switch(kind) {
9598 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009599 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
9600 return asciilib_find(buf1, len1, buf2, len2, offset);
9601 else
9602 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009603 case PyUnicode_2BYTE_KIND:
9604 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9605 case PyUnicode_4BYTE_KIND:
9606 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9607 }
9608 assert(0);
9609 return -1;
9610}
9611
9612static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009613anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
9614 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009615{
9616 switch(kind) {
9617 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009618 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
9619 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
9620 else
9621 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009622 case PyUnicode_2BYTE_KIND:
9623 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
9624 case PyUnicode_4BYTE_KIND:
9625 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
9626 }
9627 assert(0);
9628 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009629}
9630
Alexander Belopolsky40018472011-02-26 01:02:56 +00009631static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009632replace(PyObject *self, PyObject *str1,
9633 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009634{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009635 PyObject *u;
9636 char *sbuf = PyUnicode_DATA(self);
9637 char *buf1 = PyUnicode_DATA(str1);
9638 char *buf2 = PyUnicode_DATA(str2);
9639 int srelease = 0, release1 = 0, release2 = 0;
9640 int skind = PyUnicode_KIND(self);
9641 int kind1 = PyUnicode_KIND(str1);
9642 int kind2 = PyUnicode_KIND(str2);
9643 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
9644 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
9645 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009646
9647 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009648 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009649 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009650 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009651
Victor Stinner59de0ee2011-10-07 10:01:28 +02009652 if (str1 == str2)
9653 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009654 if (skind < kind1)
9655 /* substring too wide to be present */
9656 goto nothing;
9657
9658 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +00009659 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009660 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009661 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009662 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009663 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009664 /* replace characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009665 Py_UCS4 u1, u2, maxchar;
9666 int mayshrink, rkind;
9667 u1 = PyUnicode_READ_CHAR(str1, 0);
9668 if (!findchar(sbuf, PyUnicode_KIND(self),
9669 slen, u1, 1))
Thomas Wouters477c8d52006-05-27 19:21:47 +00009670 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009671 u2 = PyUnicode_READ_CHAR(str2, 0);
9672 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9673 /* Replacing u1 with u2 may cause a maxchar reduction in the
9674 result string. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009675 if (u2 > maxchar) {
9676 maxchar = u2;
9677 mayshrink = 0;
9678 }
Victor Stinnerb9275c12011-10-05 14:01:42 +02009679 else
9680 mayshrink = maxchar > 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009681 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009682 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009683 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009684 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009685 rkind = PyUnicode_KIND(u);
9686 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
9687 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009688 if (--maxcount < 0)
9689 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009690 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009691 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009692 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +02009693 unicode_adjust_maxchar(&u);
9694 if (u == NULL)
9695 goto error;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009696 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009697 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009698 int rkind = skind;
9699 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +02009700 PyObject *rstr;
9701 Py_UCS4 maxchar;
9702
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009703 if (kind1 < rkind) {
9704 /* widen substring */
9705 buf1 = _PyUnicode_AsKind(str1, rkind);
9706 if (!buf1) goto error;
9707 release1 = 1;
9708 }
Victor Stinnerc3cec782011-10-05 21:24:08 +02009709 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009710 if (i < 0)
9711 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009712 if (rkind > kind2) {
9713 /* widen replacement */
9714 buf2 = _PyUnicode_AsKind(str2, rkind);
9715 if (!buf2) goto error;
9716 release2 = 1;
9717 }
9718 else if (rkind < kind2) {
9719 /* widen self and buf1 */
9720 rkind = kind2;
9721 if (release1) PyMem_Free(buf1);
9722 sbuf = _PyUnicode_AsKind(self, rkind);
9723 if (!sbuf) goto error;
9724 srelease = 1;
9725 buf1 = _PyUnicode_AsKind(str1, rkind);
9726 if (!buf1) goto error;
9727 release1 = 1;
9728 }
Victor Stinner25a4b292011-10-06 12:31:55 +02009729 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9730 maxchar = Py_MAX(maxchar, PyUnicode_MAX_CHAR_VALUE(str2));
9731 rstr = PyUnicode_New(slen, maxchar);
9732 if (!rstr)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009733 goto error;
Victor Stinner25a4b292011-10-06 12:31:55 +02009734 res = PyUnicode_DATA(rstr);
9735
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009736 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009737 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009738 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009739 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009740 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009741 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009742
9743 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +02009744 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009745 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +02009746 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009747 if (i == -1)
9748 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009749 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009750 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009751 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009752 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009753 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009754
Victor Stinner25a4b292011-10-06 12:31:55 +02009755 u = rstr;
9756 unicode_adjust_maxchar(&u);
9757 if (!u)
9758 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009759 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009760 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009761
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009762 Py_ssize_t n, i, j, ires;
9763 Py_ssize_t product, new_size;
9764 int rkind = skind;
Victor Stinner25a4b292011-10-06 12:31:55 +02009765 PyObject *rstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009766 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +02009767 Py_UCS4 maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009768
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009769 if (kind1 < rkind) {
9770 buf1 = _PyUnicode_AsKind(str1, rkind);
9771 if (!buf1) goto error;
9772 release1 = 1;
9773 }
Victor Stinnerc3cec782011-10-05 21:24:08 +02009774 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009775 if (n == 0)
9776 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009777 if (kind2 < rkind) {
9778 buf2 = _PyUnicode_AsKind(str2, rkind);
9779 if (!buf2) goto error;
9780 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009781 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009782 else if (kind2 > rkind) {
9783 rkind = kind2;
9784 sbuf = _PyUnicode_AsKind(self, rkind);
9785 if (!sbuf) goto error;
9786 srelease = 1;
9787 if (release1) PyMem_Free(buf1);
9788 buf1 = _PyUnicode_AsKind(str1, rkind);
9789 if (!buf1) goto error;
9790 release1 = 1;
9791 }
9792 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
9793 PyUnicode_GET_LENGTH(str1))); */
9794 product = n * (len2-len1);
9795 if ((product / (len2-len1)) != n) {
9796 PyErr_SetString(PyExc_OverflowError,
9797 "replace string is too long");
9798 goto error;
9799 }
9800 new_size = slen + product;
9801 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
9802 PyErr_SetString(PyExc_OverflowError,
9803 "replace string is too long");
9804 goto error;
9805 }
Victor Stinner25a4b292011-10-06 12:31:55 +02009806 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9807 maxchar = Py_MAX(maxchar, PyUnicode_MAX_CHAR_VALUE(str2));
9808 rstr = PyUnicode_New(new_size, maxchar);
9809 if (!rstr)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009810 goto error;
Victor Stinner25a4b292011-10-06 12:31:55 +02009811 res = PyUnicode_DATA(rstr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009812 ires = i = 0;
9813 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009814 while (n-- > 0) {
9815 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +02009816 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009817 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +02009818 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009819 if (j == -1)
9820 break;
9821 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009822 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009823 memcpy(res + rkind * ires,
9824 sbuf + rkind * i,
9825 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009826 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009827 }
9828 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009829 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009830 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009831 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009832 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009833 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009834 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009835 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009836 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009837 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +00009838 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009839 memcpy(res + rkind * ires,
9840 sbuf + rkind * i,
9841 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00009842 } else {
9843 /* interleave */
9844 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009845 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009846 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009847 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009848 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009849 if (--n <= 0)
9850 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009851 memcpy(res + rkind * ires,
9852 sbuf + rkind * i,
9853 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009854 ires++;
9855 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009856 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009857 memcpy(res + rkind * ires,
9858 sbuf + rkind * i,
9859 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00009860 }
Victor Stinner25a4b292011-10-06 12:31:55 +02009861 u = rstr;
9862 unicode_adjust_maxchar(&u);
9863 if (u == NULL)
9864 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009865 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009866 if (srelease)
9867 PyMem_FREE(sbuf);
9868 if (release1)
9869 PyMem_FREE(buf1);
9870 if (release2)
9871 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009872 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009873 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009874
Benjamin Peterson29060642009-01-31 22:14:21 +00009875 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00009876 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009877 if (srelease)
9878 PyMem_FREE(sbuf);
9879 if (release1)
9880 PyMem_FREE(buf1);
9881 if (release2)
9882 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009883 if (PyUnicode_CheckExact(self)) {
9884 Py_INCREF(self);
9885 return (PyObject *) self;
9886 }
Victor Stinner034f6cf2011-09-30 02:26:44 +02009887 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009888 error:
9889 if (srelease && sbuf)
9890 PyMem_FREE(sbuf);
9891 if (release1 && buf1)
9892 PyMem_FREE(buf1);
9893 if (release2 && buf2)
9894 PyMem_FREE(buf2);
9895 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009896}
9897
9898/* --- Unicode Object Methods --------------------------------------------- */
9899
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009900PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009901 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009902\n\
9903Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009904characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009905
9906static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +02009907unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009908{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009909 return fixup(self, fixtitle);
9910}
9911
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009912PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009913 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009914\n\
9915Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +00009916have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009917
9918static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +02009919unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009920{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009921 return fixup(self, fixcapitalize);
9922}
9923
9924#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009925PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009926 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009927\n\
9928Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009929normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009930
9931static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009932unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009933{
9934 PyObject *list;
9935 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009936 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009937
Guido van Rossumd57fd912000-03-10 22:53:23 +00009938 /* Split into words */
9939 list = split(self, NULL, -1);
9940 if (!list)
9941 return NULL;
9942
9943 /* Capitalize each word */
9944 for (i = 0; i < PyList_GET_SIZE(list); i++) {
9945 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00009946 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009947 if (item == NULL)
9948 goto onError;
9949 Py_DECREF(PyList_GET_ITEM(list, i));
9950 PyList_SET_ITEM(list, i, item);
9951 }
9952
9953 /* Join the words to form a new string */
9954 item = PyUnicode_Join(NULL, list);
9955
Benjamin Peterson29060642009-01-31 22:14:21 +00009956 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009957 Py_DECREF(list);
9958 return (PyObject *)item;
9959}
9960#endif
9961
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009962/* Argument converter. Coerces to a single unicode character */
9963
9964static int
9965convert_uc(PyObject *obj, void *addr)
9966{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009967 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009968 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009969
Benjamin Peterson14339b62009-01-31 16:36:08 +00009970 uniobj = PyUnicode_FromObject(obj);
9971 if (uniobj == NULL) {
9972 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009973 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009974 return 0;
9975 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009976 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009977 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009978 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009979 Py_DECREF(uniobj);
9980 return 0;
9981 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009982 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009983 Py_DECREF(uniobj);
9984 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009985}
9986
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009987PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009988 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009989\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00009990Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009991done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009992
9993static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009994unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009995{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009996 Py_ssize_t marg, left;
9997 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009998 Py_UCS4 fillchar = ' ';
9999
Victor Stinnere9a29352011-10-01 02:14:59 +020010000 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010001 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010002
Victor Stinnere9a29352011-10-01 02:14:59 +020010003 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010004 return NULL;
10005
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010006 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010007 Py_INCREF(self);
10008 return (PyObject*) self;
10009 }
10010
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010011 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010012 left = marg / 2 + (marg & width & 1);
10013
Victor Stinner9310abb2011-10-05 00:59:23 +020010014 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010015}
10016
Marc-André Lemburge5034372000-08-08 08:04:29 +000010017#if 0
10018
10019/* This code should go into some future Unicode collation support
10020 module. The basic comparison should compare ordinals on a naive
Georg Brandlc6c31782009-06-08 13:41:29 +000010021 basis (this is what Java does and thus Jython too). */
Marc-André Lemburge5034372000-08-08 08:04:29 +000010022
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010023/* speedy UTF-16 code point order comparison */
10024/* gleaned from: */
10025/* http://www-4.ibm.com/software/developer/library/utf16.html?dwzone=unicode */
10026
Marc-André Lemburge12896e2000-07-07 17:51:08 +000010027static short utf16Fixup[32] =
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010028{
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010029 0, 0, 0, 0, 0, 0, 0, 0,
Tim Petersced69f82003-09-16 20:30:58 +000010030 0, 0, 0, 0, 0, 0, 0, 0,
10031 0, 0, 0, 0, 0, 0, 0, 0,
Marc-André Lemburge12896e2000-07-07 17:51:08 +000010032 0, 0, 0, 0x2000, -0x800, -0x800, -0x800, -0x800
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010033};
10034
Guido van Rossumd57fd912000-03-10 22:53:23 +000010035static int
10036unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
10037{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010038 Py_ssize_t len1, len2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010039
Guido van Rossumd57fd912000-03-10 22:53:23 +000010040 Py_UNICODE *s1 = str1->str;
10041 Py_UNICODE *s2 = str2->str;
10042
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010043 len1 = str1->_base._base.length;
10044 len2 = str2->_base._base.length;
Tim Petersced69f82003-09-16 20:30:58 +000010045
Guido van Rossumd57fd912000-03-10 22:53:23 +000010046 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +000010047 Py_UNICODE c1, c2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010048
10049 c1 = *s1++;
10050 c2 = *s2++;
Fredrik Lundh45714e92001-06-26 16:39:36 +000010051
Benjamin Peterson29060642009-01-31 22:14:21 +000010052 if (c1 > (1<<11) * 26)
10053 c1 += utf16Fixup[c1>>11];
10054 if (c2 > (1<<11) * 26)
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010055 c2 += utf16Fixup[c2>>11];
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010056 /* now c1 and c2 are in UTF-32-compatible order */
Fredrik Lundh45714e92001-06-26 16:39:36 +000010057
10058 if (c1 != c2)
10059 return (c1 < c2) ? -1 : 1;
Tim Petersced69f82003-09-16 20:30:58 +000010060
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +000010061 len1--; len2--;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010062 }
10063
10064 return (len1 < len2) ? -1 : (len1 != len2);
10065}
10066
Marc-André Lemburge5034372000-08-08 08:04:29 +000010067#else
10068
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010069/* This function assumes that str1 and str2 are readied by the caller. */
10070
Marc-André Lemburge5034372000-08-08 08:04:29 +000010071static int
10072unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
10073{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010074 int kind1, kind2;
10075 void *data1, *data2;
10076 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010077
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010078 kind1 = PyUnicode_KIND(str1);
10079 kind2 = PyUnicode_KIND(str2);
10080 data1 = PyUnicode_DATA(str1);
10081 data2 = PyUnicode_DATA(str2);
10082 len1 = PyUnicode_GET_LENGTH(str1);
10083 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010084
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010085 for (i = 0; i < len1 && i < len2; ++i) {
10086 Py_UCS4 c1, c2;
10087 c1 = PyUnicode_READ(kind1, data1, i);
10088 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010089
10090 if (c1 != c2)
10091 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010092 }
10093
10094 return (len1 < len2) ? -1 : (len1 != len2);
10095}
10096
10097#endif
10098
Alexander Belopolsky40018472011-02-26 01:02:56 +000010099int
10100PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010101{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010102 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10103 if (PyUnicode_READY(left) == -1 ||
10104 PyUnicode_READY(right) == -1)
10105 return -1;
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010106 return unicode_compare((PyUnicodeObject *)left,
10107 (PyUnicodeObject *)right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010108 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010109 PyErr_Format(PyExc_TypeError,
10110 "Can't compare %.100s and %.100s",
10111 left->ob_type->tp_name,
10112 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010113 return -1;
10114}
10115
Martin v. Löwis5b222132007-06-10 09:51:05 +000010116int
10117PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10118{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010119 Py_ssize_t i;
10120 int kind;
10121 void *data;
10122 Py_UCS4 chr;
10123
Victor Stinner910337b2011-10-03 03:20:16 +020010124 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010125 if (PyUnicode_READY(uni) == -1)
10126 return -1;
10127 kind = PyUnicode_KIND(uni);
10128 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010129 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010130 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10131 if (chr != str[i])
10132 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010133 /* This check keeps Python strings that end in '\0' from comparing equal
10134 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010135 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010136 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010137 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010138 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010139 return 0;
10140}
10141
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010142
Benjamin Peterson29060642009-01-31 22:14:21 +000010143#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010144 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010145
Alexander Belopolsky40018472011-02-26 01:02:56 +000010146PyObject *
10147PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010148{
10149 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010150
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010151 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10152 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010153 if (PyUnicode_READY(left) == -1 ||
10154 PyUnicode_READY(right) == -1)
10155 return NULL;
10156 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10157 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010158 if (op == Py_EQ) {
10159 Py_INCREF(Py_False);
10160 return Py_False;
10161 }
10162 if (op == Py_NE) {
10163 Py_INCREF(Py_True);
10164 return Py_True;
10165 }
10166 }
10167 if (left == right)
10168 result = 0;
10169 else
10170 result = unicode_compare((PyUnicodeObject *)left,
10171 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010172
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010173 /* Convert the return value to a Boolean */
10174 switch (op) {
10175 case Py_EQ:
10176 v = TEST_COND(result == 0);
10177 break;
10178 case Py_NE:
10179 v = TEST_COND(result != 0);
10180 break;
10181 case Py_LE:
10182 v = TEST_COND(result <= 0);
10183 break;
10184 case Py_GE:
10185 v = TEST_COND(result >= 0);
10186 break;
10187 case Py_LT:
10188 v = TEST_COND(result == -1);
10189 break;
10190 case Py_GT:
10191 v = TEST_COND(result == 1);
10192 break;
10193 default:
10194 PyErr_BadArgument();
10195 return NULL;
10196 }
10197 Py_INCREF(v);
10198 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010199 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010200
Brian Curtindfc80e32011-08-10 20:28:54 -050010201 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010202}
10203
Alexander Belopolsky40018472011-02-26 01:02:56 +000010204int
10205PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010206{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010207 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010208 int kind1, kind2, kind;
10209 void *buf1, *buf2;
10210 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010211 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010212
10213 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010214 sub = PyUnicode_FromObject(element);
10215 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010216 PyErr_Format(PyExc_TypeError,
10217 "'in <string>' requires string as left operand, not %s",
10218 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010219 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010220 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010221 if (PyUnicode_READY(sub) == -1)
10222 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010223
Thomas Wouters477c8d52006-05-27 19:21:47 +000010224 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010225 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010226 Py_DECREF(sub);
10227 return -1;
10228 }
10229
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010230 kind1 = PyUnicode_KIND(str);
10231 kind2 = PyUnicode_KIND(sub);
10232 kind = kind1 > kind2 ? kind1 : kind2;
10233 buf1 = PyUnicode_DATA(str);
10234 buf2 = PyUnicode_DATA(sub);
10235 if (kind1 != kind)
10236 buf1 = _PyUnicode_AsKind((PyObject*)str, kind);
10237 if (!buf1) {
10238 Py_DECREF(sub);
10239 return -1;
10240 }
10241 if (kind2 != kind)
10242 buf2 = _PyUnicode_AsKind((PyObject*)sub, kind);
10243 if (!buf2) {
10244 Py_DECREF(sub);
10245 if (kind1 != kind) PyMem_Free(buf1);
10246 return -1;
10247 }
10248 len1 = PyUnicode_GET_LENGTH(str);
10249 len2 = PyUnicode_GET_LENGTH(sub);
10250
10251 switch(kind) {
10252 case PyUnicode_1BYTE_KIND:
10253 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10254 break;
10255 case PyUnicode_2BYTE_KIND:
10256 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10257 break;
10258 case PyUnicode_4BYTE_KIND:
10259 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10260 break;
10261 default:
10262 result = -1;
10263 assert(0);
10264 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010265
10266 Py_DECREF(str);
10267 Py_DECREF(sub);
10268
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010269 if (kind1 != kind)
10270 PyMem_Free(buf1);
10271 if (kind2 != kind)
10272 PyMem_Free(buf2);
10273
Guido van Rossum403d68b2000-03-13 15:55:09 +000010274 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010275}
10276
Guido van Rossumd57fd912000-03-10 22:53:23 +000010277/* Concat to string or Unicode object giving a new Unicode object. */
10278
Alexander Belopolsky40018472011-02-26 01:02:56 +000010279PyObject *
10280PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010281{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010282 PyObject *u = NULL, *v = NULL, *w;
10283 Py_UCS4 maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010284
10285 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010286 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010287 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010288 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010289 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010290 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010291 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010292
10293 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010294 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010295 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010296 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010297 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010298 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010299 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010300 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010301 }
10302
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010303 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinnerff9e50f2011-09-28 22:17:19 +020010304 maxchar = Py_MAX(maxchar, PyUnicode_MAX_CHAR_VALUE(v));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305
Guido van Rossumd57fd912000-03-10 22:53:23 +000010306 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 w = PyUnicode_New(
10308 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10309 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010310 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010311 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010312 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10313 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010314 Py_DECREF(u);
10315 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010316 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010317 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010318
Benjamin Peterson29060642009-01-31 22:14:21 +000010319 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010320 Py_XDECREF(u);
10321 Py_XDECREF(v);
10322 return NULL;
10323}
10324
Victor Stinnerb0923652011-10-04 01:17:31 +020010325static void
10326unicode_append_inplace(PyObject **p_left, PyObject *right)
10327{
10328 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010329
10330 assert(PyUnicode_IS_READY(*p_left));
10331 assert(PyUnicode_IS_READY(right));
10332
10333 left_len = PyUnicode_GET_LENGTH(*p_left);
10334 right_len = PyUnicode_GET_LENGTH(right);
10335 if (left_len > PY_SSIZE_T_MAX - right_len) {
10336 PyErr_SetString(PyExc_OverflowError,
10337 "strings are too large to concat");
10338 goto error;
10339 }
10340 new_len = left_len + right_len;
10341
10342 /* Now we own the last reference to 'left', so we can resize it
10343 * in-place.
10344 */
10345 if (unicode_resize(p_left, new_len) != 0) {
10346 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10347 * deallocated so it cannot be put back into
10348 * 'variable'. The MemoryError is raised when there
10349 * is no value in 'variable', which might (very
10350 * remotely) be a cause of incompatibilities.
10351 */
10352 goto error;
10353 }
10354 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010355 copy_characters(*p_left, left_len, right, 0, right_len);
10356 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010357 return;
10358
10359error:
10360 Py_DECREF(*p_left);
10361 *p_left = NULL;
10362}
10363
Walter Dörwald1ab83302007-05-18 17:15:44 +000010364void
Victor Stinner23e56682011-10-03 03:54:37 +020010365PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010366{
Victor Stinner23e56682011-10-03 03:54:37 +020010367 PyObject *left, *res;
10368
10369 if (p_left == NULL) {
10370 if (!PyErr_Occurred())
10371 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010372 return;
10373 }
Victor Stinner23e56682011-10-03 03:54:37 +020010374 left = *p_left;
10375 if (right == NULL || !PyUnicode_Check(left)) {
10376 if (!PyErr_Occurred())
10377 PyErr_BadInternalCall();
10378 goto error;
10379 }
10380
Victor Stinnere1335c72011-10-04 20:53:03 +020010381 if (PyUnicode_READY(left))
10382 goto error;
10383 if (PyUnicode_READY(right))
10384 goto error;
10385
Victor Stinner23e56682011-10-03 03:54:37 +020010386 if (PyUnicode_CheckExact(left) && left != unicode_empty
10387 && PyUnicode_CheckExact(right) && right != unicode_empty
10388 && unicode_resizable(left)
10389 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10390 || _PyUnicode_WSTR(left) != NULL))
10391 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010392 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10393 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010394 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010395 not so different than duplicating the string. */
10396 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010397 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010398 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010399 if (p_left != NULL)
10400 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010401 return;
10402 }
10403 }
10404
10405 res = PyUnicode_Concat(left, right);
10406 if (res == NULL)
10407 goto error;
10408 Py_DECREF(left);
10409 *p_left = res;
10410 return;
10411
10412error:
10413 Py_DECREF(*p_left);
10414 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010415}
10416
10417void
10418PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10419{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010420 PyUnicode_Append(pleft, right);
10421 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010422}
10423
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010424PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010425 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010426\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010427Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010428string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010429interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010430
10431static PyObject *
10432unicode_count(PyUnicodeObject *self, PyObject *args)
10433{
10434 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010435 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010436 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010437 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010438 int kind1, kind2, kind;
10439 void *buf1, *buf2;
10440 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010441
Jesus Ceaac451502011-04-20 17:09:23 +020010442 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10443 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010444 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010445
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010446 kind1 = PyUnicode_KIND(self);
10447 kind2 = PyUnicode_KIND(substring);
10448 kind = kind1 > kind2 ? kind1 : kind2;
10449 buf1 = PyUnicode_DATA(self);
10450 buf2 = PyUnicode_DATA(substring);
10451 if (kind1 != kind)
10452 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10453 if (!buf1) {
10454 Py_DECREF(substring);
10455 return NULL;
10456 }
10457 if (kind2 != kind)
10458 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10459 if (!buf2) {
10460 Py_DECREF(substring);
10461 if (kind1 != kind) PyMem_Free(buf1);
10462 return NULL;
10463 }
10464 len1 = PyUnicode_GET_LENGTH(self);
10465 len2 = PyUnicode_GET_LENGTH(substring);
10466
10467 ADJUST_INDICES(start, end, len1);
10468 switch(kind) {
10469 case PyUnicode_1BYTE_KIND:
10470 iresult = ucs1lib_count(
10471 ((Py_UCS1*)buf1) + start, end - start,
10472 buf2, len2, PY_SSIZE_T_MAX
10473 );
10474 break;
10475 case PyUnicode_2BYTE_KIND:
10476 iresult = ucs2lib_count(
10477 ((Py_UCS2*)buf1) + start, end - start,
10478 buf2, len2, PY_SSIZE_T_MAX
10479 );
10480 break;
10481 case PyUnicode_4BYTE_KIND:
10482 iresult = ucs4lib_count(
10483 ((Py_UCS4*)buf1) + start, end - start,
10484 buf2, len2, PY_SSIZE_T_MAX
10485 );
10486 break;
10487 default:
10488 assert(0); iresult = 0;
10489 }
10490
10491 result = PyLong_FromSsize_t(iresult);
10492
10493 if (kind1 != kind)
10494 PyMem_Free(buf1);
10495 if (kind2 != kind)
10496 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010497
10498 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010499
Guido van Rossumd57fd912000-03-10 22:53:23 +000010500 return result;
10501}
10502
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010503PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010504 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010505\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010506Encode S using the codec registered for encoding. Default encoding\n\
10507is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010508handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010509a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10510'xmlcharrefreplace' as well as any other name registered with\n\
10511codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010512
10513static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +000010514unicode_encode(PyUnicodeObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010515{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010516 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010517 char *encoding = NULL;
10518 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010519
Benjamin Peterson308d6372009-09-18 21:42:35 +000010520 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10521 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010522 return NULL;
Georg Brandl3b9406b2010-12-03 07:54:09 +000010523 return PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010524}
10525
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010526PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010527 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010528\n\
10529Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010530If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010531
10532static PyObject*
10533unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
10534{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010535 Py_ssize_t i, j, line_pos, src_len, incr;
10536 Py_UCS4 ch;
10537 PyObject *u;
10538 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010539 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010540 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010541 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010542
10543 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010544 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010545
Antoine Pitrou22425222011-10-04 19:10:51 +020010546 if (PyUnicode_READY(self) == -1)
10547 return NULL;
10548
Thomas Wouters7e474022000-07-16 12:04:32 +000010549 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010550 src_len = PyUnicode_GET_LENGTH(self);
10551 i = j = line_pos = 0;
10552 kind = PyUnicode_KIND(self);
10553 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010554 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010555 for (; i < src_len; i++) {
10556 ch = PyUnicode_READ(kind, src_data, i);
10557 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010558 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010559 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010560 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010561 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010562 goto overflow;
10563 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010564 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010565 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010566 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010567 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010568 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010569 goto overflow;
10570 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010571 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010572 if (ch == '\n' || ch == '\r')
10573 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010574 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010575 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020010576 if (!found && PyUnicode_CheckExact(self)) {
10577 Py_INCREF((PyObject *) self);
10578 return (PyObject *) self;
10579 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010580
Guido van Rossumd57fd912000-03-10 22:53:23 +000010581 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010582 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010583 if (!u)
10584 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010585 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010586
Antoine Pitroue71d5742011-10-04 15:55:09 +020010587 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010588
Antoine Pitroue71d5742011-10-04 15:55:09 +020010589 for (; i < src_len; i++) {
10590 ch = PyUnicode_READ(kind, src_data, i);
10591 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010592 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010593 incr = tabsize - (line_pos % tabsize);
10594 line_pos += incr;
10595 while (incr--) {
10596 PyUnicode_WRITE(kind, dest_data, j, ' ');
10597 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010598 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010599 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010600 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010601 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010602 line_pos++;
10603 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010604 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010605 if (ch == '\n' || ch == '\r')
10606 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010607 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010608 }
10609 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020010610#ifndef DONT_MAKE_RESULT_READY
10611 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010612 Py_DECREF(u);
10613 return NULL;
10614 }
Victor Stinner17efeed2011-10-04 20:05:46 +020010615#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010616 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010617 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010618
Antoine Pitroue71d5742011-10-04 15:55:09 +020010619 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010620 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10621 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010622}
10623
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010624PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010625 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010626\n\
10627Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010628such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010629arguments start and end are interpreted as in slice notation.\n\
10630\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010631Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010632
10633static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010634unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010635{
Jesus Ceaac451502011-04-20 17:09:23 +020010636 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010637 Py_ssize_t start;
10638 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010639 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010640
Jesus Ceaac451502011-04-20 17:09:23 +020010641 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10642 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010643 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010644
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010645 if (PyUnicode_READY(self) == -1)
10646 return NULL;
10647 if (PyUnicode_READY(substring) == -1)
10648 return NULL;
10649
10650 result = any_find_slice(
Victor Stinnerc3cec782011-10-05 21:24:08 +020010651 asciilib_find_slice, ucs1lib_find_slice,
10652 ucs2lib_find_slice, ucs4lib_find_slice,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010653 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010654 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010655
10656 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010657
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010658 if (result == -2)
10659 return NULL;
10660
Christian Heimes217cfd12007-12-02 14:31:20 +000010661 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010662}
10663
10664static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010665unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010666{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010667 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
10668 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010669 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010670 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010671}
10672
Guido van Rossumc2504932007-09-18 19:42:40 +000010673/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010010674 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000010675static Py_hash_t
Neil Schemenauerf8c37d12007-09-07 20:49:04 +000010676unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010677{
Guido van Rossumc2504932007-09-18 19:42:40 +000010678 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010010679 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010680
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010681 if (_PyUnicode_HASH(self) != -1)
10682 return _PyUnicode_HASH(self);
10683 if (PyUnicode_READY(self) == -1)
10684 return -1;
10685 len = PyUnicode_GET_LENGTH(self);
10686
10687 /* The hash function as a macro, gets expanded three times below. */
10688#define HASH(P) \
10689 x = (Py_uhash_t)*P << 7; \
10690 while (--len >= 0) \
10691 x = (1000003*x) ^ (Py_uhash_t)*P++;
10692
10693 switch (PyUnicode_KIND(self)) {
10694 case PyUnicode_1BYTE_KIND: {
10695 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
10696 HASH(c);
10697 break;
10698 }
10699 case PyUnicode_2BYTE_KIND: {
10700 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
10701 HASH(s);
10702 break;
10703 }
10704 default: {
10705 Py_UCS4 *l;
10706 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
10707 "Impossible switch case in unicode_hash");
10708 l = PyUnicode_4BYTE_DATA(self);
10709 HASH(l);
10710 break;
10711 }
10712 }
10713 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
10714
Guido van Rossumc2504932007-09-18 19:42:40 +000010715 if (x == -1)
10716 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010717 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010718 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010719}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010720#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000010721
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010722PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010723 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010724\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010725Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010726
10727static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010728unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010729{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010730 Py_ssize_t result;
Jesus Ceaac451502011-04-20 17:09:23 +020010731 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010732 Py_ssize_t start;
10733 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010734
Jesus Ceaac451502011-04-20 17:09:23 +020010735 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
10736 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010737 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010738
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010739 if (PyUnicode_READY(self) == -1)
10740 return NULL;
10741 if (PyUnicode_READY(substring) == -1)
10742 return NULL;
10743
10744 result = any_find_slice(
Victor Stinnerc3cec782011-10-05 21:24:08 +020010745 asciilib_find_slice, ucs1lib_find_slice,
10746 ucs2lib_find_slice, ucs4lib_find_slice,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010747 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010748 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010749
10750 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010751
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010752 if (result == -2)
10753 return NULL;
10754
Guido van Rossumd57fd912000-03-10 22:53:23 +000010755 if (result < 0) {
10756 PyErr_SetString(PyExc_ValueError, "substring not found");
10757 return NULL;
10758 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010759
Christian Heimes217cfd12007-12-02 14:31:20 +000010760 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010761}
10762
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010763PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010764 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010765\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010766Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010767at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010768
10769static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010770unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010771{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010772 Py_ssize_t i, length;
10773 int kind;
10774 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010775 int cased;
10776
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010777 if (PyUnicode_READY(self) == -1)
10778 return NULL;
10779 length = PyUnicode_GET_LENGTH(self);
10780 kind = PyUnicode_KIND(self);
10781 data = PyUnicode_DATA(self);
10782
Guido van Rossumd57fd912000-03-10 22:53:23 +000010783 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010784 if (length == 1)
10785 return PyBool_FromLong(
10786 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010787
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010788 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010789 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010790 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010791
Guido van Rossumd57fd912000-03-10 22:53:23 +000010792 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010793 for (i = 0; i < length; i++) {
10794 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010795
Benjamin Peterson29060642009-01-31 22:14:21 +000010796 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
10797 return PyBool_FromLong(0);
10798 else if (!cased && Py_UNICODE_ISLOWER(ch))
10799 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010800 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010801 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010802}
10803
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010804PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010805 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010806\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010807Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010808at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010809
10810static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010811unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010812{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010813 Py_ssize_t i, length;
10814 int kind;
10815 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010816 int cased;
10817
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010818 if (PyUnicode_READY(self) == -1)
10819 return NULL;
10820 length = PyUnicode_GET_LENGTH(self);
10821 kind = PyUnicode_KIND(self);
10822 data = PyUnicode_DATA(self);
10823
Guido van Rossumd57fd912000-03-10 22:53:23 +000010824 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010825 if (length == 1)
10826 return PyBool_FromLong(
10827 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010828
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010829 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010830 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010831 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010832
Guido van Rossumd57fd912000-03-10 22:53:23 +000010833 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010834 for (i = 0; i < length; i++) {
10835 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010836
Benjamin Peterson29060642009-01-31 22:14:21 +000010837 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
10838 return PyBool_FromLong(0);
10839 else if (!cased && Py_UNICODE_ISUPPER(ch))
10840 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010841 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010842 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010843}
10844
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010845PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010846 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010847\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010848Return True if S is a titlecased string and there is at least one\n\
10849character in S, i.e. upper- and titlecase characters may only\n\
10850follow uncased characters and lowercase characters only cased ones.\n\
10851Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010852
10853static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010854unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010855{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010856 Py_ssize_t i, length;
10857 int kind;
10858 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010859 int cased, previous_is_cased;
10860
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010861 if (PyUnicode_READY(self) == -1)
10862 return NULL;
10863 length = PyUnicode_GET_LENGTH(self);
10864 kind = PyUnicode_KIND(self);
10865 data = PyUnicode_DATA(self);
10866
Guido van Rossumd57fd912000-03-10 22:53:23 +000010867 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010868 if (length == 1) {
10869 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10870 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
10871 (Py_UNICODE_ISUPPER(ch) != 0));
10872 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010873
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010874 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010875 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010876 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010877
Guido van Rossumd57fd912000-03-10 22:53:23 +000010878 cased = 0;
10879 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010880 for (i = 0; i < length; i++) {
10881 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010882
Benjamin Peterson29060642009-01-31 22:14:21 +000010883 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
10884 if (previous_is_cased)
10885 return PyBool_FromLong(0);
10886 previous_is_cased = 1;
10887 cased = 1;
10888 }
10889 else if (Py_UNICODE_ISLOWER(ch)) {
10890 if (!previous_is_cased)
10891 return PyBool_FromLong(0);
10892 previous_is_cased = 1;
10893 cased = 1;
10894 }
10895 else
10896 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010897 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010898 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010899}
10900
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010901PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010902 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010903\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010904Return True if all characters in S are whitespace\n\
10905and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010906
10907static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010908unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010909{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010910 Py_ssize_t i, length;
10911 int kind;
10912 void *data;
10913
10914 if (PyUnicode_READY(self) == -1)
10915 return NULL;
10916 length = PyUnicode_GET_LENGTH(self);
10917 kind = PyUnicode_KIND(self);
10918 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010919
Guido van Rossumd57fd912000-03-10 22:53:23 +000010920 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010921 if (length == 1)
10922 return PyBool_FromLong(
10923 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010924
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010925 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010926 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010927 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010928
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010929 for (i = 0; i < length; i++) {
10930 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010931 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000010932 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010933 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010934 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010935}
10936
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010937PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010938 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010939\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010940Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010941and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010942
10943static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010944unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010945{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010946 Py_ssize_t i, length;
10947 int kind;
10948 void *data;
10949
10950 if (PyUnicode_READY(self) == -1)
10951 return NULL;
10952 length = PyUnicode_GET_LENGTH(self);
10953 kind = PyUnicode_KIND(self);
10954 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010955
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010956 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010957 if (length == 1)
10958 return PyBool_FromLong(
10959 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010960
10961 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010962 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010963 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010964
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010965 for (i = 0; i < length; i++) {
10966 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010967 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010968 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010969 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010970}
10971
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010972PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010973 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010974\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010975Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010976and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010977
10978static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010979unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010980{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010981 int kind;
10982 void *data;
10983 Py_ssize_t len, i;
10984
10985 if (PyUnicode_READY(self) == -1)
10986 return NULL;
10987
10988 kind = PyUnicode_KIND(self);
10989 data = PyUnicode_DATA(self);
10990 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010991
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010992 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010993 if (len == 1) {
10994 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10995 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
10996 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010997
10998 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010999 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011000 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011001
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011002 for (i = 0; i < len; i++) {
11003 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011004 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011005 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011006 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011007 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011008}
11009
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011010PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011011 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011012\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011013Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011014False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011015
11016static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011017unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011018{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011019 Py_ssize_t i, length;
11020 int kind;
11021 void *data;
11022
11023 if (PyUnicode_READY(self) == -1)
11024 return NULL;
11025 length = PyUnicode_GET_LENGTH(self);
11026 kind = PyUnicode_KIND(self);
11027 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011028
Guido van Rossumd57fd912000-03-10 22:53:23 +000011029 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011030 if (length == 1)
11031 return PyBool_FromLong(
11032 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011033
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011034 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011035 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011036 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011037
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011038 for (i = 0; i < length; i++) {
11039 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011040 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011041 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011042 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011043}
11044
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011045PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011046 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011047\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011048Return True if all characters in S are digits\n\
11049and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011050
11051static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011052unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011053{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011054 Py_ssize_t i, length;
11055 int kind;
11056 void *data;
11057
11058 if (PyUnicode_READY(self) == -1)
11059 return NULL;
11060 length = PyUnicode_GET_LENGTH(self);
11061 kind = PyUnicode_KIND(self);
11062 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011063
Guido van Rossumd57fd912000-03-10 22:53:23 +000011064 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011065 if (length == 1) {
11066 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11067 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11068 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011069
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011070 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011071 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011072 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011073
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011074 for (i = 0; i < length; i++) {
11075 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011076 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011077 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011078 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011079}
11080
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011081PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011082 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011083\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011084Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011085False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011086
11087static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011088unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011089{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011090 Py_ssize_t i, length;
11091 int kind;
11092 void *data;
11093
11094 if (PyUnicode_READY(self) == -1)
11095 return NULL;
11096 length = PyUnicode_GET_LENGTH(self);
11097 kind = PyUnicode_KIND(self);
11098 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011099
Guido van Rossumd57fd912000-03-10 22:53:23 +000011100 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011101 if (length == 1)
11102 return PyBool_FromLong(
11103 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011104
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011105 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011106 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011107 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011108
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011109 for (i = 0; i < length; i++) {
11110 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011111 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011112 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011113 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011114}
11115
Martin v. Löwis47383402007-08-15 07:32:56 +000011116int
11117PyUnicode_IsIdentifier(PyObject *self)
11118{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011119 int kind;
11120 void *data;
11121 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011122 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011123
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011124 if (PyUnicode_READY(self) == -1) {
11125 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011126 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011127 }
11128
11129 /* Special case for empty strings */
11130 if (PyUnicode_GET_LENGTH(self) == 0)
11131 return 0;
11132 kind = PyUnicode_KIND(self);
11133 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011134
11135 /* PEP 3131 says that the first character must be in
11136 XID_Start and subsequent characters in XID_Continue,
11137 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011138 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011139 letters, digits, underscore). However, given the current
11140 definition of XID_Start and XID_Continue, it is sufficient
11141 to check just for these, except that _ must be allowed
11142 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011143 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011144 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011145 return 0;
11146
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011147 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011148 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011149 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011150 return 1;
11151}
11152
11153PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011154 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011155\n\
11156Return True if S is a valid identifier according\n\
11157to the language definition.");
11158
11159static PyObject*
11160unicode_isidentifier(PyObject *self)
11161{
11162 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11163}
11164
Georg Brandl559e5d72008-06-11 18:37:52 +000011165PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011166 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011167\n\
11168Return True if all characters in S are considered\n\
11169printable in repr() or S is empty, False otherwise.");
11170
11171static PyObject*
11172unicode_isprintable(PyObject *self)
11173{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011174 Py_ssize_t i, length;
11175 int kind;
11176 void *data;
11177
11178 if (PyUnicode_READY(self) == -1)
11179 return NULL;
11180 length = PyUnicode_GET_LENGTH(self);
11181 kind = PyUnicode_KIND(self);
11182 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011183
11184 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011185 if (length == 1)
11186 return PyBool_FromLong(
11187 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011188
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011189 for (i = 0; i < length; i++) {
11190 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011191 Py_RETURN_FALSE;
11192 }
11193 }
11194 Py_RETURN_TRUE;
11195}
11196
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011197PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011198 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011199\n\
11200Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011201iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011202
11203static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011204unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011205{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011206 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207}
11208
Martin v. Löwis18e16552006-02-15 17:27:45 +000011209static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210unicode_length(PyUnicodeObject *self)
11211{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011212 if (PyUnicode_READY(self) == -1)
11213 return -1;
11214 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011215}
11216
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011217PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011218 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011219\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011220Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011221done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011222
11223static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011224unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011226 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011227 Py_UCS4 fillchar = ' ';
11228
11229 if (PyUnicode_READY(self) == -1)
11230 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011231
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011232 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011233 return NULL;
11234
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011235 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011236 Py_INCREF(self);
11237 return (PyObject*) self;
11238 }
11239
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011240 return (PyObject*) pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011241}
11242
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011243PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011244 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011245\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011246Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011247
11248static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011249unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011250{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011251 return fixup(self, fixlower);
11252}
11253
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011254#define LEFTSTRIP 0
11255#define RIGHTSTRIP 1
11256#define BOTHSTRIP 2
11257
11258/* Arrays indexed by above */
11259static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11260
11261#define STRIPNAME(i) (stripformat[i]+3)
11262
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011263/* externally visible for str.strip(unicode) */
11264PyObject *
11265_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
11266{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011267 void *data;
11268 int kind;
11269 Py_ssize_t i, j, len;
11270 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011271
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011272 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11273 return NULL;
11274
11275 kind = PyUnicode_KIND(self);
11276 data = PyUnicode_DATA(self);
11277 len = PyUnicode_GET_LENGTH(self);
11278 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11279 PyUnicode_DATA(sepobj),
11280 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011281
Benjamin Peterson14339b62009-01-31 16:36:08 +000011282 i = 0;
11283 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011284 while (i < len &&
11285 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011286 i++;
11287 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011288 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011289
Benjamin Peterson14339b62009-01-31 16:36:08 +000011290 j = len;
11291 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011292 do {
11293 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011294 } while (j >= i &&
11295 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011296 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011297 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011298
Victor Stinner12bab6d2011-10-01 01:53:49 +020011299 return PyUnicode_Substring((PyObject*)self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011300}
11301
11302PyObject*
11303PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11304{
11305 unsigned char *data;
11306 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011307 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011308
Victor Stinnerde636f32011-10-01 03:55:54 +020011309 if (PyUnicode_READY(self) == -1)
11310 return NULL;
11311
11312 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11313
Victor Stinner12bab6d2011-10-01 01:53:49 +020011314 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011315 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011316 if (PyUnicode_CheckExact(self)) {
11317 Py_INCREF(self);
11318 return self;
11319 }
11320 else
11321 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011322 }
11323
Victor Stinner12bab6d2011-10-01 01:53:49 +020011324 length = end - start;
11325 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011326 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011327
Victor Stinnerde636f32011-10-01 03:55:54 +020011328 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011329 PyErr_SetString(PyExc_IndexError, "string index out of range");
11330 return NULL;
11331 }
11332
Victor Stinnerb9275c12011-10-05 14:01:42 +020011333 if (PyUnicode_IS_ASCII(self)) {
11334 kind = PyUnicode_KIND(self);
11335 data = PyUnicode_1BYTE_DATA(self);
11336 return unicode_fromascii(data + start, length);
11337 }
11338 else {
11339 kind = PyUnicode_KIND(self);
11340 data = PyUnicode_1BYTE_DATA(self);
11341 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011342 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011343 length);
11344 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011345}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011346
11347static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011348do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011349{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011350 int kind;
11351 void *data;
11352 Py_ssize_t len, i, j;
11353
11354 if (PyUnicode_READY(self) == -1)
11355 return NULL;
11356
11357 kind = PyUnicode_KIND(self);
11358 data = PyUnicode_DATA(self);
11359 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011360
Benjamin Peterson14339b62009-01-31 16:36:08 +000011361 i = 0;
11362 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011363 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011364 i++;
11365 }
11366 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011367
Benjamin Peterson14339b62009-01-31 16:36:08 +000011368 j = len;
11369 if (striptype != LEFTSTRIP) {
11370 do {
11371 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011372 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011373 j++;
11374 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011375
Victor Stinner12bab6d2011-10-01 01:53:49 +020011376 return PyUnicode_Substring((PyObject*)self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011377}
11378
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011379
11380static PyObject *
11381do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
11382{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011383 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011384
Benjamin Peterson14339b62009-01-31 16:36:08 +000011385 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11386 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011387
Benjamin Peterson14339b62009-01-31 16:36:08 +000011388 if (sep != NULL && sep != Py_None) {
11389 if (PyUnicode_Check(sep))
11390 return _PyUnicode_XStrip(self, striptype, sep);
11391 else {
11392 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011393 "%s arg must be None or str",
11394 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011395 return NULL;
11396 }
11397 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011398
Benjamin Peterson14339b62009-01-31 16:36:08 +000011399 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011400}
11401
11402
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011403PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011404 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011405\n\
11406Return a copy of the string S with leading and trailing\n\
11407whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011408If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011409
11410static PyObject *
11411unicode_strip(PyUnicodeObject *self, PyObject *args)
11412{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011413 if (PyTuple_GET_SIZE(args) == 0)
11414 return do_strip(self, BOTHSTRIP); /* Common case */
11415 else
11416 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011417}
11418
11419
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011420PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011421 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011422\n\
11423Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011424If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011425
11426static PyObject *
11427unicode_lstrip(PyUnicodeObject *self, PyObject *args)
11428{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011429 if (PyTuple_GET_SIZE(args) == 0)
11430 return do_strip(self, LEFTSTRIP); /* Common case */
11431 else
11432 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011433}
11434
11435
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011436PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011437 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011438\n\
11439Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011440If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011441
11442static PyObject *
11443unicode_rstrip(PyUnicodeObject *self, PyObject *args)
11444{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011445 if (PyTuple_GET_SIZE(args) == 0)
11446 return do_strip(self, RIGHTSTRIP); /* Common case */
11447 else
11448 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011449}
11450
11451
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +000011453unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011454{
11455 PyUnicodeObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011456 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011457
Georg Brandl222de0f2009-04-12 12:01:50 +000011458 if (len < 1) {
11459 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011460 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011461 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462
Tim Peters7a29bd52001-09-12 03:03:31 +000011463 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011464 /* no repeat, return original string */
11465 Py_INCREF(str);
11466 return (PyObject*) str;
11467 }
Tim Peters8f422462000-09-09 06:13:41 +000011468
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011469 if (PyUnicode_READY(str) == -1)
11470 return NULL;
11471
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011472 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011473 PyErr_SetString(PyExc_OverflowError,
11474 "repeated string is too long");
11475 return NULL;
11476 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011477 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011478
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011479 u = (PyUnicodeObject *)PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011480 if (!u)
11481 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011482 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011483
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011484 if (PyUnicode_GET_LENGTH(str) == 1) {
11485 const int kind = PyUnicode_KIND(str);
11486 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11487 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011488 if (kind == PyUnicode_1BYTE_KIND)
11489 memset(to, (unsigned char)fill_char, len);
11490 else {
11491 for (n = 0; n < len; ++n)
11492 PyUnicode_WRITE(kind, to, n, fill_char);
11493 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011494 }
11495 else {
11496 /* number of characters copied this far */
11497 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011498 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011499 char *to = (char *) PyUnicode_DATA(u);
11500 Py_MEMCPY(to, PyUnicode_DATA(str),
11501 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011502 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011503 n = (done <= nchars-done) ? done : nchars-done;
11504 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011505 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011506 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011507 }
11508
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011509 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510 return (PyObject*) u;
11511}
11512
Alexander Belopolsky40018472011-02-26 01:02:56 +000011513PyObject *
11514PyUnicode_Replace(PyObject *obj,
11515 PyObject *subobj,
11516 PyObject *replobj,
11517 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011518{
11519 PyObject *self;
11520 PyObject *str1;
11521 PyObject *str2;
11522 PyObject *result;
11523
11524 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011525 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011526 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011527 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011528 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011529 Py_DECREF(self);
11530 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011531 }
11532 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011533 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011534 Py_DECREF(self);
11535 Py_DECREF(str1);
11536 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011537 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011538 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011539 Py_DECREF(self);
11540 Py_DECREF(str1);
11541 Py_DECREF(str2);
11542 return result;
11543}
11544
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011545PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011546 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011547\n\
11548Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011549old replaced by new. If the optional argument count is\n\
11550given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011551
11552static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011553unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011554{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011555 PyObject *str1;
11556 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011557 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011558 PyObject *result;
11559
Martin v. Löwis18e16552006-02-15 17:27:45 +000011560 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011561 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011562 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011563 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011564 str1 = PyUnicode_FromObject(str1);
11565 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11566 return NULL;
11567 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011568 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011569 Py_DECREF(str1);
11570 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011571 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011572
11573 result = replace(self, str1, str2, maxcount);
11574
11575 Py_DECREF(str1);
11576 Py_DECREF(str2);
11577 return result;
11578}
11579
Alexander Belopolsky40018472011-02-26 01:02:56 +000011580static PyObject *
11581unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011582{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011583 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011584 Py_ssize_t isize;
11585 Py_ssize_t osize, squote, dquote, i, o;
11586 Py_UCS4 max, quote;
11587 int ikind, okind;
11588 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011589
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011590 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011591 return NULL;
11592
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011593 isize = PyUnicode_GET_LENGTH(unicode);
11594 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011595
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011596 /* Compute length of output, quote characters, and
11597 maximum character */
11598 osize = 2; /* quotes */
11599 max = 127;
11600 squote = dquote = 0;
11601 ikind = PyUnicode_KIND(unicode);
11602 for (i = 0; i < isize; i++) {
11603 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11604 switch (ch) {
11605 case '\'': squote++; osize++; break;
11606 case '"': dquote++; osize++; break;
11607 case '\\': case '\t': case '\r': case '\n':
11608 osize += 2; break;
11609 default:
11610 /* Fast-path ASCII */
11611 if (ch < ' ' || ch == 0x7f)
11612 osize += 4; /* \xHH */
11613 else if (ch < 0x7f)
11614 osize++;
11615 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11616 osize++;
11617 max = ch > max ? ch : max;
11618 }
11619 else if (ch < 0x100)
11620 osize += 4; /* \xHH */
11621 else if (ch < 0x10000)
11622 osize += 6; /* \uHHHH */
11623 else
11624 osize += 10; /* \uHHHHHHHH */
11625 }
11626 }
11627
11628 quote = '\'';
11629 if (squote) {
11630 if (dquote)
11631 /* Both squote and dquote present. Use squote,
11632 and escape them */
11633 osize += squote;
11634 else
11635 quote = '"';
11636 }
11637
11638 repr = PyUnicode_New(osize, max);
11639 if (repr == NULL)
11640 return NULL;
11641 okind = PyUnicode_KIND(repr);
11642 odata = PyUnicode_DATA(repr);
11643
11644 PyUnicode_WRITE(okind, odata, 0, quote);
11645 PyUnicode_WRITE(okind, odata, osize-1, quote);
11646
11647 for (i = 0, o = 1; i < isize; i++) {
11648 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011649
11650 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011651 if ((ch == quote) || (ch == '\\')) {
11652 PyUnicode_WRITE(okind, odata, o++, '\\');
11653 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011654 continue;
11655 }
11656
Benjamin Peterson29060642009-01-31 22:14:21 +000011657 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011658 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011659 PyUnicode_WRITE(okind, odata, o++, '\\');
11660 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011661 }
11662 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011663 PyUnicode_WRITE(okind, odata, o++, '\\');
11664 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011665 }
11666 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011667 PyUnicode_WRITE(okind, odata, o++, '\\');
11668 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011669 }
11670
11671 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011672 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011673 PyUnicode_WRITE(okind, odata, o++, '\\');
11674 PyUnicode_WRITE(okind, odata, o++, 'x');
11675 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
11676 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011677 }
11678
Georg Brandl559e5d72008-06-11 18:37:52 +000011679 /* Copy ASCII characters as-is */
11680 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011681 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011682 }
11683
Benjamin Peterson29060642009-01-31 22:14:21 +000011684 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000011685 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011686 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000011687 (categories Z* and C* except ASCII space)
11688 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011689 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011690 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011691 if (ch <= 0xff) {
11692 PyUnicode_WRITE(okind, odata, o++, '\\');
11693 PyUnicode_WRITE(okind, odata, o++, 'x');
11694 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
11695 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011696 }
11697 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011698 else if (ch >= 0x10000) {
11699 PyUnicode_WRITE(okind, odata, o++, '\\');
11700 PyUnicode_WRITE(okind, odata, o++, 'U');
11701 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 28) & 0xF]);
11702 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 24) & 0xF]);
11703 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 20) & 0xF]);
11704 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 16) & 0xF]);
11705 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
11706 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
11707 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
11708 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011709 }
11710 /* Map 16-bit characters to '\uxxxx' */
11711 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011712 PyUnicode_WRITE(okind, odata, o++, '\\');
11713 PyUnicode_WRITE(okind, odata, o++, 'u');
11714 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
11715 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
11716 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
11717 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011718 }
11719 }
11720 /* Copy characters as-is */
11721 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011722 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011723 }
11724 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000011725 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011726 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020011727 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000011728 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011729}
11730
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011731PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011732 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011733\n\
11734Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011735such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011736arguments start and end are interpreted as in slice notation.\n\
11737\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011738Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011739
11740static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011741unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011742{
Jesus Ceaac451502011-04-20 17:09:23 +020011743 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011744 Py_ssize_t start;
11745 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011746 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011747
Jesus Ceaac451502011-04-20 17:09:23 +020011748 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
11749 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000011750 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011751
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011752 if (PyUnicode_READY(self) == -1)
11753 return NULL;
11754 if (PyUnicode_READY(substring) == -1)
11755 return NULL;
11756
11757 result = any_find_slice(
Victor Stinnerc3cec782011-10-05 21:24:08 +020011758 asciilib_rfind_slice, ucs1lib_rfind_slice,
11759 ucs2lib_rfind_slice, ucs4lib_rfind_slice,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011760 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011761 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011762
11763 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011764
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011765 if (result == -2)
11766 return NULL;
11767
Christian Heimes217cfd12007-12-02 14:31:20 +000011768 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011769}
11770
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011771PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011772 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011773\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011774Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011775
11776static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011777unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011778{
Jesus Ceaac451502011-04-20 17:09:23 +020011779 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011780 Py_ssize_t start;
11781 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011782 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011783
Jesus Ceaac451502011-04-20 17:09:23 +020011784 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
11785 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000011786 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011787
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011788 if (PyUnicode_READY(self) == -1)
11789 return NULL;
11790 if (PyUnicode_READY(substring) == -1)
11791 return NULL;
11792
11793 result = any_find_slice(
Victor Stinnerc3cec782011-10-05 21:24:08 +020011794 asciilib_rfind_slice, ucs1lib_rfind_slice,
11795 ucs2lib_rfind_slice, ucs4lib_rfind_slice,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011796 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011797 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011798
11799 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011800
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011801 if (result == -2)
11802 return NULL;
11803
Guido van Rossumd57fd912000-03-10 22:53:23 +000011804 if (result < 0) {
11805 PyErr_SetString(PyExc_ValueError, "substring not found");
11806 return NULL;
11807 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011808
Christian Heimes217cfd12007-12-02 14:31:20 +000011809 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011810}
11811
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011812PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011813 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011814\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011815Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011816done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011817
11818static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011819unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011820{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011821 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011822 Py_UCS4 fillchar = ' ';
11823
Victor Stinnere9a29352011-10-01 02:14:59 +020011824 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011825 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011826
Victor Stinnere9a29352011-10-01 02:14:59 +020011827 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011828 return NULL;
11829
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011830 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011831 Py_INCREF(self);
11832 return (PyObject*) self;
11833 }
11834
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011835 return (PyObject*) pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011836}
11837
Alexander Belopolsky40018472011-02-26 01:02:56 +000011838PyObject *
11839PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011840{
11841 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000011842
Guido van Rossumd57fd912000-03-10 22:53:23 +000011843 s = PyUnicode_FromObject(s);
11844 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000011845 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000011846 if (sep != NULL) {
11847 sep = PyUnicode_FromObject(sep);
11848 if (sep == NULL) {
11849 Py_DECREF(s);
11850 return NULL;
11851 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011852 }
11853
Victor Stinner9310abb2011-10-05 00:59:23 +020011854 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011855
11856 Py_DECREF(s);
11857 Py_XDECREF(sep);
11858 return result;
11859}
11860
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011861PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011862 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011863\n\
11864Return a list of the words in S, using sep as the\n\
11865delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000011866splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000011867whitespace string is a separator and empty strings are\n\
11868removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011869
11870static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011871unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011872{
11873 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011874 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011875
Martin v. Löwis18e16552006-02-15 17:27:45 +000011876 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011877 return NULL;
11878
11879 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000011880 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011881 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020011882 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011883 else
Benjamin Peterson29060642009-01-31 22:14:21 +000011884 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011885}
11886
Thomas Wouters477c8d52006-05-27 19:21:47 +000011887PyObject *
11888PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
11889{
11890 PyObject* str_obj;
11891 PyObject* sep_obj;
11892 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011893 int kind1, kind2, kind;
11894 void *buf1 = NULL, *buf2 = NULL;
11895 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011896
11897 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020011898 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011899 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011900 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011901 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000011902 Py_DECREF(str_obj);
11903 return NULL;
11904 }
11905
Victor Stinner14f8f022011-10-05 20:58:25 +020011906 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011907 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020011908 kind = Py_MAX(kind1, kind2);
11909 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011910 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020011911 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011912 if (!buf1)
11913 goto onError;
11914 buf2 = PyUnicode_DATA(sep_obj);
11915 if (kind2 != kind)
11916 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11917 if (!buf2)
11918 goto onError;
11919 len1 = PyUnicode_GET_LENGTH(str_obj);
11920 len2 = PyUnicode_GET_LENGTH(sep_obj);
11921
Victor Stinner14f8f022011-10-05 20:58:25 +020011922 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011923 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020011924 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
11925 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11926 else
11927 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011928 break;
11929 case PyUnicode_2BYTE_KIND:
11930 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11931 break;
11932 case PyUnicode_4BYTE_KIND:
11933 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11934 break;
11935 default:
11936 assert(0);
11937 out = 0;
11938 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011939
11940 Py_DECREF(sep_obj);
11941 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011942 if (kind1 != kind)
11943 PyMem_Free(buf1);
11944 if (kind2 != kind)
11945 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011946
11947 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011948 onError:
11949 Py_DECREF(sep_obj);
11950 Py_DECREF(str_obj);
11951 if (kind1 != kind && buf1)
11952 PyMem_Free(buf1);
11953 if (kind2 != kind && buf2)
11954 PyMem_Free(buf2);
11955 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011956}
11957
11958
11959PyObject *
11960PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
11961{
11962 PyObject* str_obj;
11963 PyObject* sep_obj;
11964 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011965 int kind1, kind2, kind;
11966 void *buf1 = NULL, *buf2 = NULL;
11967 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011968
11969 str_obj = PyUnicode_FromObject(str_in);
11970 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000011971 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011972 sep_obj = PyUnicode_FromObject(sep_in);
11973 if (!sep_obj) {
11974 Py_DECREF(str_obj);
11975 return NULL;
11976 }
11977
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011978 kind1 = PyUnicode_KIND(str_in);
11979 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020011980 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011981 buf1 = PyUnicode_DATA(str_in);
11982 if (kind1 != kind)
11983 buf1 = _PyUnicode_AsKind(str_in, kind);
11984 if (!buf1)
11985 goto onError;
11986 buf2 = PyUnicode_DATA(sep_obj);
11987 if (kind2 != kind)
11988 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11989 if (!buf2)
11990 goto onError;
11991 len1 = PyUnicode_GET_LENGTH(str_obj);
11992 len2 = PyUnicode_GET_LENGTH(sep_obj);
11993
11994 switch(PyUnicode_KIND(str_in)) {
11995 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020011996 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
11997 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11998 else
11999 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012000 break;
12001 case PyUnicode_2BYTE_KIND:
12002 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12003 break;
12004 case PyUnicode_4BYTE_KIND:
12005 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12006 break;
12007 default:
12008 assert(0);
12009 out = 0;
12010 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012011
12012 Py_DECREF(sep_obj);
12013 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012014 if (kind1 != kind)
12015 PyMem_Free(buf1);
12016 if (kind2 != kind)
12017 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012018
12019 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012020 onError:
12021 Py_DECREF(sep_obj);
12022 Py_DECREF(str_obj);
12023 if (kind1 != kind && buf1)
12024 PyMem_Free(buf1);
12025 if (kind2 != kind && buf2)
12026 PyMem_Free(buf2);
12027 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012028}
12029
12030PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012031 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012032\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012033Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012034the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012035found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012036
12037static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012038unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012039{
Victor Stinner9310abb2011-10-05 00:59:23 +020012040 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012041}
12042
12043PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012044 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012045\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012046Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012047the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012048separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012049
12050static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012051unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012052{
Victor Stinner9310abb2011-10-05 00:59:23 +020012053 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012054}
12055
Alexander Belopolsky40018472011-02-26 01:02:56 +000012056PyObject *
12057PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012058{
12059 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012060
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012061 s = PyUnicode_FromObject(s);
12062 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012063 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012064 if (sep != NULL) {
12065 sep = PyUnicode_FromObject(sep);
12066 if (sep == NULL) {
12067 Py_DECREF(s);
12068 return NULL;
12069 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012070 }
12071
Victor Stinner9310abb2011-10-05 00:59:23 +020012072 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012073
12074 Py_DECREF(s);
12075 Py_XDECREF(sep);
12076 return result;
12077}
12078
12079PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012080 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012081\n\
12082Return a list of the words in S, using sep as the\n\
12083delimiter string, starting at the end of the string and\n\
12084working to the front. If maxsplit is given, at most maxsplit\n\
12085splits are done. If sep is not specified, any whitespace string\n\
12086is a separator.");
12087
12088static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012089unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012090{
12091 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012092 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012093
Martin v. Löwis18e16552006-02-15 17:27:45 +000012094 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012095 return NULL;
12096
12097 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012098 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012099 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012100 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012101 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012102 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012103}
12104
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012105PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012106 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012107\n\
12108Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012109Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012110is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012111
12112static PyObject*
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012113unicode_splitlines(PyUnicodeObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012114{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012115 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012116 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012117
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012118 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12119 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012120 return NULL;
12121
Guido van Rossum86662912000-04-11 15:38:46 +000012122 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012123}
12124
12125static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012126PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012127{
Walter Dörwald346737f2007-05-31 10:44:43 +000012128 if (PyUnicode_CheckExact(self)) {
12129 Py_INCREF(self);
12130 return self;
12131 } else
12132 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012133 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012134}
12135
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012136PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012137 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012138\n\
12139Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012140and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012141
12142static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012143unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012144{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012145 return fixup(self, fixswapcase);
12146}
12147
Georg Brandlceee0772007-11-27 23:48:05 +000012148PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012149 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012150\n\
12151Return a translation table usable for str.translate().\n\
12152If there is only one argument, it must be a dictionary mapping Unicode\n\
12153ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012154Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012155If there are two arguments, they must be strings of equal length, and\n\
12156in the resulting dictionary, each character in x will be mapped to the\n\
12157character at the same position in y. If there is a third argument, it\n\
12158must be a string, whose characters will be mapped to None in the result.");
12159
12160static PyObject*
12161unicode_maketrans(PyUnicodeObject *null, PyObject *args)
12162{
12163 PyObject *x, *y = NULL, *z = NULL;
12164 PyObject *new = NULL, *key, *value;
12165 Py_ssize_t i = 0;
12166 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012167
Georg Brandlceee0772007-11-27 23:48:05 +000012168 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12169 return NULL;
12170 new = PyDict_New();
12171 if (!new)
12172 return NULL;
12173 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012174 int x_kind, y_kind, z_kind;
12175 void *x_data, *y_data, *z_data;
12176
Georg Brandlceee0772007-11-27 23:48:05 +000012177 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012178 if (!PyUnicode_Check(x)) {
12179 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12180 "be a string if there is a second argument");
12181 goto err;
12182 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012183 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012184 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12185 "arguments must have equal length");
12186 goto err;
12187 }
12188 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012189 x_kind = PyUnicode_KIND(x);
12190 y_kind = PyUnicode_KIND(y);
12191 x_data = PyUnicode_DATA(x);
12192 y_data = PyUnicode_DATA(y);
12193 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12194 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12195 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012196 if (!key || !value)
12197 goto err;
12198 res = PyDict_SetItem(new, key, value);
12199 Py_DECREF(key);
12200 Py_DECREF(value);
12201 if (res < 0)
12202 goto err;
12203 }
12204 /* create entries for deleting chars in z */
12205 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012206 z_kind = PyUnicode_KIND(z);
12207 z_data = PyUnicode_DATA(z);
Georg Brandlceee0772007-11-27 23:48:05 +000012208 for (i = 0; i < PyUnicode_GET_SIZE(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012209 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012210 if (!key)
12211 goto err;
12212 res = PyDict_SetItem(new, key, Py_None);
12213 Py_DECREF(key);
12214 if (res < 0)
12215 goto err;
12216 }
12217 }
12218 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012219 int kind;
12220 void *data;
12221
Georg Brandlceee0772007-11-27 23:48:05 +000012222 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012223 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012224 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12225 "to maketrans it must be a dict");
12226 goto err;
12227 }
12228 /* copy entries into the new dict, converting string keys to int keys */
12229 while (PyDict_Next(x, &i, &key, &value)) {
12230 if (PyUnicode_Check(key)) {
12231 /* convert string keys to integer keys */
12232 PyObject *newkey;
12233 if (PyUnicode_GET_SIZE(key) != 1) {
12234 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12235 "table must be of length 1");
12236 goto err;
12237 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012238 kind = PyUnicode_KIND(key);
12239 data = PyUnicode_DATA(key);
12240 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012241 if (!newkey)
12242 goto err;
12243 res = PyDict_SetItem(new, newkey, value);
12244 Py_DECREF(newkey);
12245 if (res < 0)
12246 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012247 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012248 /* just keep integer keys */
12249 if (PyDict_SetItem(new, key, value) < 0)
12250 goto err;
12251 } else {
12252 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12253 "be strings or integers");
12254 goto err;
12255 }
12256 }
12257 }
12258 return new;
12259 err:
12260 Py_DECREF(new);
12261 return NULL;
12262}
12263
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012264PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012265 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012266\n\
12267Return a copy of the string S, where all characters have been mapped\n\
12268through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012269Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012270Unmapped characters are left untouched. Characters mapped to None\n\
12271are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012272
12273static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012274unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012275{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012276 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012277}
12278
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012279PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012280 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012281\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012282Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012283
12284static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012285unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012286{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012287 return fixup(self, fixupper);
12288}
12289
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012290PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012291 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012292\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012293Pad a numeric string S with zeros on the left, to fill a field\n\
12294of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012295
12296static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012297unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012298{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012299 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012300 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012301 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012302 int kind;
12303 void *data;
12304 Py_UCS4 chr;
12305
12306 if (PyUnicode_READY(self) == -1)
12307 return NULL;
12308
Martin v. Löwis18e16552006-02-15 17:27:45 +000012309 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012310 return NULL;
12311
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012312 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012313 if (PyUnicode_CheckExact(self)) {
12314 Py_INCREF(self);
12315 return (PyObject*) self;
12316 }
12317 else
Victor Stinner2219e0a2011-10-01 01:16:59 +020012318 return PyUnicode_Copy((PyObject*)self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012319 }
12320
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012321 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012322
12323 u = pad(self, fill, 0, '0');
12324
Walter Dörwald068325e2002-04-15 13:36:47 +000012325 if (u == NULL)
12326 return NULL;
12327
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012328 kind = PyUnicode_KIND(u);
12329 data = PyUnicode_DATA(u);
12330 chr = PyUnicode_READ(kind, data, fill);
12331
12332 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012333 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012334 PyUnicode_WRITE(kind, data, 0, chr);
12335 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012336 }
12337
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012338 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012339 return (PyObject*) u;
12340}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012341
12342#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012343static PyObject *
12344unicode__decimal2ascii(PyObject *self)
12345{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012346 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012347}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012348#endif
12349
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012350PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012351 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012352\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012353Return True if S starts with the specified prefix, False otherwise.\n\
12354With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012355With optional end, stop comparing S at that position.\n\
12356prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012357
12358static PyObject *
12359unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012360 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012361{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012362 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012363 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012364 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012365 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012366 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012367
Jesus Ceaac451502011-04-20 17:09:23 +020012368 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012369 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012370 if (PyTuple_Check(subobj)) {
12371 Py_ssize_t i;
12372 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
12373 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012374 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012375 if (substring == NULL)
12376 return NULL;
12377 result = tailmatch(self, substring, start, end, -1);
12378 Py_DECREF(substring);
12379 if (result) {
12380 Py_RETURN_TRUE;
12381 }
12382 }
12383 /* nothing matched */
12384 Py_RETURN_FALSE;
12385 }
12386 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012387 if (substring == NULL) {
12388 if (PyErr_ExceptionMatches(PyExc_TypeError))
12389 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12390 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012391 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012392 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012393 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012394 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012395 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012396}
12397
12398
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012399PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012400 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012401\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012402Return True if S ends with the specified suffix, False otherwise.\n\
12403With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012404With optional end, stop comparing S at that position.\n\
12405suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012406
12407static PyObject *
12408unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012409 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012410{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012411 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012412 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012413 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012414 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012415 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012416
Jesus Ceaac451502011-04-20 17:09:23 +020012417 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012418 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012419 if (PyTuple_Check(subobj)) {
12420 Py_ssize_t i;
12421 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
12422 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012423 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012424 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012425 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012426 result = tailmatch(self, substring, start, end, +1);
12427 Py_DECREF(substring);
12428 if (result) {
12429 Py_RETURN_TRUE;
12430 }
12431 }
12432 Py_RETURN_FALSE;
12433 }
12434 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012435 if (substring == NULL) {
12436 if (PyErr_ExceptionMatches(PyExc_TypeError))
12437 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12438 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012439 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012440 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012441 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012442 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012443 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012444}
12445
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012446#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012447
12448PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012449 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012450\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012451Return a formatted version of S, using substitutions from args and kwargs.\n\
12452The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012453
Eric Smith27bbca62010-11-04 17:06:58 +000012454PyDoc_STRVAR(format_map__doc__,
12455 "S.format_map(mapping) -> str\n\
12456\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012457Return a formatted version of S, using substitutions from mapping.\n\
12458The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012459
Eric Smith4a7d76d2008-05-30 18:10:19 +000012460static PyObject *
12461unicode__format__(PyObject* self, PyObject* args)
12462{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012463 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012464
12465 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12466 return NULL;
12467
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012468 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012469 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012470 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012471}
12472
Eric Smith8c663262007-08-25 02:26:07 +000012473PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012474 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012475\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012476Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012477
12478static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012479unicode__sizeof__(PyUnicodeObject *v)
12480{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012481 Py_ssize_t size;
12482
12483 /* If it's a compact object, account for base structure +
12484 character data. */
12485 if (PyUnicode_IS_COMPACT_ASCII(v))
12486 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12487 else if (PyUnicode_IS_COMPACT(v))
12488 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012489 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012490 else {
12491 /* If it is a two-block object, account for base object, and
12492 for character block if present. */
12493 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012494 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012495 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012496 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012497 }
12498 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012499 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012500 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012501 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012502 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012503 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012504
12505 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012506}
12507
12508PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012509 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012510
12511static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012512unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012513{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012514 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012515 if (!copy)
12516 return NULL;
12517 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012518}
12519
Guido van Rossumd57fd912000-03-10 22:53:23 +000012520static PyMethodDef unicode_methods[] = {
12521
12522 /* Order is according to common usage: often used methods should
12523 appear first, since lookup is done sequentially. */
12524
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012525 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012526 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12527 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012528 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012529 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12530 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12531 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12532 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12533 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12534 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12535 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012536 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012537 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12538 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12539 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012540 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012541 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12542 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12543 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012544 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012545 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012546 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012547 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012548 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12549 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12550 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12551 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12552 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12553 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12554 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12555 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12556 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12557 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12558 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12559 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12560 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12561 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012562 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012563 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012564 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012565 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012566 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012567 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012568 {"maketrans", (PyCFunction) unicode_maketrans,
12569 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012570 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012571#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012572 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012573#endif
12574
12575#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012576 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012577 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012578#endif
12579
Benjamin Peterson14339b62009-01-31 16:36:08 +000012580 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012581 {NULL, NULL}
12582};
12583
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012584static PyObject *
12585unicode_mod(PyObject *v, PyObject *w)
12586{
Brian Curtindfc80e32011-08-10 20:28:54 -050012587 if (!PyUnicode_Check(v))
12588 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012589 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012590}
12591
12592static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012593 0, /*nb_add*/
12594 0, /*nb_subtract*/
12595 0, /*nb_multiply*/
12596 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012597};
12598
Guido van Rossumd57fd912000-03-10 22:53:23 +000012599static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012600 (lenfunc) unicode_length, /* sq_length */
12601 PyUnicode_Concat, /* sq_concat */
12602 (ssizeargfunc) unicode_repeat, /* sq_repeat */
12603 (ssizeargfunc) unicode_getitem, /* sq_item */
12604 0, /* sq_slice */
12605 0, /* sq_ass_item */
12606 0, /* sq_ass_slice */
12607 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012608};
12609
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012610static PyObject*
12611unicode_subscript(PyUnicodeObject* self, PyObject* item)
12612{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012613 if (PyUnicode_READY(self) == -1)
12614 return NULL;
12615
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000012616 if (PyIndex_Check(item)) {
12617 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012618 if (i == -1 && PyErr_Occurred())
12619 return NULL;
12620 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012621 i += PyUnicode_GET_LENGTH(self);
Victor Stinner2fe5ced2011-10-02 00:25:40 +020012622 return unicode_getitem((PyObject*)self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012623 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000012624 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012625 PyObject *result;
12626 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012627 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012628 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012629
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012630 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000012631 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012632 return NULL;
12633 }
12634
12635 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012636 return PyUnicode_New(0, 0);
12637 } else if (start == 0 && step == 1 &&
12638 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000012639 PyUnicode_CheckExact(self)) {
12640 Py_INCREF(self);
12641 return (PyObject *)self;
12642 } else if (step == 1) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012643 return PyUnicode_Substring((PyObject*)self,
12644 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012645 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012646 /* General case */
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012647 max_char = 0;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012648 src_kind = PyUnicode_KIND(self);
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012649 kind_limit = kind_maxchar_limit(src_kind);
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012650 src_data = PyUnicode_DATA(self);
12651 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
12652 ch = PyUnicode_READ(src_kind, src_data, cur);
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012653 if (ch > max_char) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012654 max_char = ch;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012655 if (max_char >= kind_limit)
12656 break;
12657 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012658 }
12659 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012660 if (result == NULL)
12661 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012662 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012663 dest_data = PyUnicode_DATA(result);
12664
12665 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012666 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
12667 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012668 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012669 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012670 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012671 } else {
12672 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
12673 return NULL;
12674 }
12675}
12676
12677static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012678 (lenfunc)unicode_length, /* mp_length */
12679 (binaryfunc)unicode_subscript, /* mp_subscript */
12680 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012681};
12682
Guido van Rossumd57fd912000-03-10 22:53:23 +000012683
Guido van Rossumd57fd912000-03-10 22:53:23 +000012684/* Helpers for PyUnicode_Format() */
12685
12686static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000012687getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012688{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012689 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012690 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012691 (*p_argidx)++;
12692 if (arglen < 0)
12693 return args;
12694 else
12695 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012696 }
12697 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012698 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012699 return NULL;
12700}
12701
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012702/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012703
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012704static PyObject *
12705formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012706{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012707 char *p;
12708 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012709 double x;
Tim Petersced69f82003-09-16 20:30:58 +000012710
Guido van Rossumd57fd912000-03-10 22:53:23 +000012711 x = PyFloat_AsDouble(v);
12712 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012713 return NULL;
12714
Guido van Rossumd57fd912000-03-10 22:53:23 +000012715 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012716 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000012717
Eric Smith0923d1d2009-04-16 20:16:10 +000012718 p = PyOS_double_to_string(x, type, prec,
12719 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012720 if (p == NULL)
12721 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012722 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000012723 PyMem_Free(p);
12724 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012725}
12726
Tim Peters38fd5b62000-09-21 05:43:11 +000012727static PyObject*
12728formatlong(PyObject *val, int flags, int prec, int type)
12729{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012730 char *buf;
12731 int len;
12732 PyObject *str; /* temporary string object. */
12733 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000012734
Benjamin Peterson14339b62009-01-31 16:36:08 +000012735 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
12736 if (!str)
12737 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012738 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012739 Py_DECREF(str);
12740 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000012741}
12742
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012743static Py_UCS4
12744formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012745{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000012746 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012747 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012748 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012749 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000012750 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012751 goto onError;
12752 }
12753 else {
12754 /* Integer input truncated to a character */
12755 long x;
12756 x = PyLong_AsLong(v);
12757 if (x == -1 && PyErr_Occurred())
12758 goto onError;
12759
12760 if (x < 0 || x > 0x10ffff) {
12761 PyErr_SetString(PyExc_OverflowError,
12762 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012763 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000012764 }
12765
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012766 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012767 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000012768
Benjamin Peterson29060642009-01-31 22:14:21 +000012769 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012770 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012771 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012772 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012773}
12774
Antoine Pitrou978b9d22011-10-07 12:35:48 +020012775static int
12776repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
12777{
12778 int r;
12779 assert(count > 0);
12780 assert(PyUnicode_Check(obj));
12781 if (count > 5) {
12782 PyObject *repeated = unicode_repeat((PyUnicodeObject *) obj, count);
12783 if (repeated == NULL)
12784 return -1;
12785 r = _PyAccu_Accumulate(acc, repeated);
12786 Py_DECREF(repeated);
12787 return r;
12788 }
12789 else {
12790 do {
12791 if (_PyAccu_Accumulate(acc, obj))
12792 return -1;
12793 } while (--count);
12794 return 0;
12795 }
12796}
12797
Alexander Belopolsky40018472011-02-26 01:02:56 +000012798PyObject *
12799PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012800{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012801 void *fmt;
12802 int fmtkind;
12803 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012804 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012805 int r;
12806 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012807 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012808 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012809 PyObject *temp = NULL;
12810 PyObject *second = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012811 PyUnicodeObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012812 _PyAccu acc;
12813 static PyObject *plus, *minus, *blank, *zero, *percent;
12814
12815 if (!plus && !(plus = get_latin1_char('+')))
12816 return NULL;
12817 if (!minus && !(minus = get_latin1_char('-')))
12818 return NULL;
12819 if (!blank && !(blank = get_latin1_char(' ')))
12820 return NULL;
12821 if (!zero && !(zero = get_latin1_char('0')))
12822 return NULL;
12823 if (!percent && !(percent = get_latin1_char('%')))
12824 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000012825
Guido van Rossumd57fd912000-03-10 22:53:23 +000012826 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012827 PyErr_BadInternalCall();
12828 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012829 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012830 uformat = (PyUnicodeObject*)PyUnicode_FromObject(format);
12831 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012832 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012833 if (_PyAccu_Init(&acc))
12834 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012835 fmt = PyUnicode_DATA(uformat);
12836 fmtkind = PyUnicode_KIND(uformat);
12837 fmtcnt = PyUnicode_GET_LENGTH(uformat);
12838 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012839
Guido van Rossumd57fd912000-03-10 22:53:23 +000012840 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012841 arglen = PyTuple_Size(args);
12842 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012843 }
12844 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012845 arglen = -1;
12846 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012847 }
Christian Heimes90aa7642007-12-19 02:45:37 +000012848 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000012849 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000012850 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012851
12852 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012853 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012854 PyObject *nonfmt;
12855 Py_ssize_t nonfmtpos;
12856 nonfmtpos = fmtpos++;
12857 while (fmtcnt >= 0 &&
12858 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
12859 fmtpos++;
12860 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012861 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012862 nonfmt = PyUnicode_Substring((PyObject *) uformat, nonfmtpos, fmtpos);
12863 if (nonfmt == NULL)
12864 goto onError;
12865 r = _PyAccu_Accumulate(&acc, nonfmt);
12866 Py_DECREF(nonfmt);
12867 if (r)
12868 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012869 }
12870 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012871 /* Got a format specifier */
12872 int flags = 0;
12873 Py_ssize_t width = -1;
12874 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012875 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012876 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000012877 int isnumok;
12878 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012879 void *pbuf = NULL;
12880 Py_ssize_t pindex, len;
12881 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012882
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012883 fmtpos++;
12884 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
12885 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000012886 Py_ssize_t keylen;
12887 PyObject *key;
12888 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000012889
Benjamin Peterson29060642009-01-31 22:14:21 +000012890 if (dict == NULL) {
12891 PyErr_SetString(PyExc_TypeError,
12892 "format requires a mapping");
12893 goto onError;
12894 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012895 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000012896 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012897 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000012898 /* Skip over balanced parentheses */
12899 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012900 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000012901 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012902 else 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 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000012905 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012906 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000012907 if (fmtcnt < 0 || pcount > 0) {
12908 PyErr_SetString(PyExc_ValueError,
12909 "incomplete format key");
12910 goto onError;
12911 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020012912 key = PyUnicode_Substring((PyObject*)uformat,
12913 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000012914 if (key == NULL)
12915 goto onError;
12916 if (args_owned) {
12917 Py_DECREF(args);
12918 args_owned = 0;
12919 }
12920 args = PyObject_GetItem(dict, key);
12921 Py_DECREF(key);
12922 if (args == NULL) {
12923 goto onError;
12924 }
12925 args_owned = 1;
12926 arglen = -1;
12927 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012928 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012929 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012930 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012931 case '-': flags |= F_LJUST; continue;
12932 case '+': flags |= F_SIGN; continue;
12933 case ' ': flags |= F_BLANK; continue;
12934 case '#': flags |= F_ALT; continue;
12935 case '0': flags |= F_ZERO; continue;
12936 }
12937 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012938 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012939 if (c == '*') {
12940 v = getnextarg(args, arglen, &argidx);
12941 if (v == NULL)
12942 goto onError;
12943 if (!PyLong_Check(v)) {
12944 PyErr_SetString(PyExc_TypeError,
12945 "* wants int");
12946 goto onError;
12947 }
12948 width = PyLong_AsLong(v);
12949 if (width == -1 && PyErr_Occurred())
12950 goto onError;
12951 if (width < 0) {
12952 flags |= F_LJUST;
12953 width = -width;
12954 }
12955 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012956 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012957 }
12958 else if (c >= '0' && c <= '9') {
12959 width = c - '0';
12960 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012961 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012962 if (c < '0' || c > '9')
12963 break;
12964 if ((width*10) / 10 != width) {
12965 PyErr_SetString(PyExc_ValueError,
12966 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000012967 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000012968 }
12969 width = width*10 + (c - '0');
12970 }
12971 }
12972 if (c == '.') {
12973 prec = 0;
12974 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012975 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012976 if (c == '*') {
12977 v = getnextarg(args, arglen, &argidx);
12978 if (v == NULL)
12979 goto onError;
12980 if (!PyLong_Check(v)) {
12981 PyErr_SetString(PyExc_TypeError,
12982 "* wants int");
12983 goto onError;
12984 }
12985 prec = PyLong_AsLong(v);
12986 if (prec == -1 && PyErr_Occurred())
12987 goto onError;
12988 if (prec < 0)
12989 prec = 0;
12990 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012991 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012992 }
12993 else if (c >= '0' && c <= '9') {
12994 prec = c - '0';
12995 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012996 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012997 if (c < '0' || c > '9')
12998 break;
12999 if ((prec*10) / 10 != prec) {
13000 PyErr_SetString(PyExc_ValueError,
13001 "prec too big");
13002 goto onError;
13003 }
13004 prec = prec*10 + (c - '0');
13005 }
13006 }
13007 } /* prec */
13008 if (fmtcnt >= 0) {
13009 if (c == 'h' || c == 'l' || c == 'L') {
13010 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013011 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013012 }
13013 }
13014 if (fmtcnt < 0) {
13015 PyErr_SetString(PyExc_ValueError,
13016 "incomplete format");
13017 goto onError;
13018 }
13019 if (c != '%') {
13020 v = getnextarg(args, arglen, &argidx);
13021 if (v == NULL)
13022 goto onError;
13023 }
13024 sign = 0;
13025 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013026 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013027 switch (c) {
13028
13029 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013030 _PyAccu_Accumulate(&acc, percent);
13031 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013032
13033 case 's':
13034 case 'r':
13035 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013036 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013037 temp = v;
13038 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013039 }
13040 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013041 if (c == 's')
13042 temp = PyObject_Str(v);
13043 else if (c == 'r')
13044 temp = PyObject_Repr(v);
13045 else
13046 temp = PyObject_ASCII(v);
13047 if (temp == NULL)
13048 goto onError;
13049 if (PyUnicode_Check(temp))
13050 /* nothing to do */;
13051 else {
13052 Py_DECREF(temp);
13053 PyErr_SetString(PyExc_TypeError,
13054 "%s argument has non-string str()");
13055 goto onError;
13056 }
13057 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013058 if (PyUnicode_READY(temp) == -1) {
13059 Py_CLEAR(temp);
13060 goto onError;
13061 }
13062 pbuf = PyUnicode_DATA(temp);
13063 kind = PyUnicode_KIND(temp);
13064 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013065 if (prec >= 0 && len > prec)
13066 len = prec;
13067 break;
13068
13069 case 'i':
13070 case 'd':
13071 case 'u':
13072 case 'o':
13073 case 'x':
13074 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013075 isnumok = 0;
13076 if (PyNumber_Check(v)) {
13077 PyObject *iobj=NULL;
13078
13079 if (PyLong_Check(v)) {
13080 iobj = v;
13081 Py_INCREF(iobj);
13082 }
13083 else {
13084 iobj = PyNumber_Long(v);
13085 }
13086 if (iobj!=NULL) {
13087 if (PyLong_Check(iobj)) {
13088 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013089 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013090 Py_DECREF(iobj);
13091 if (!temp)
13092 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013093 if (PyUnicode_READY(temp) == -1) {
13094 Py_CLEAR(temp);
13095 goto onError;
13096 }
13097 pbuf = PyUnicode_DATA(temp);
13098 kind = PyUnicode_KIND(temp);
13099 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013100 sign = 1;
13101 }
13102 else {
13103 Py_DECREF(iobj);
13104 }
13105 }
13106 }
13107 if (!isnumok) {
13108 PyErr_Format(PyExc_TypeError,
13109 "%%%c format: a number is required, "
13110 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13111 goto onError;
13112 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013113 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013114 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013115 fillobj = zero;
13116 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013117 break;
13118
13119 case 'e':
13120 case 'E':
13121 case 'f':
13122 case 'F':
13123 case 'g':
13124 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013125 temp = formatfloat(v, flags, prec, c);
13126 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013127 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013128 if (PyUnicode_READY(temp) == -1) {
13129 Py_CLEAR(temp);
13130 goto onError;
13131 }
13132 pbuf = PyUnicode_DATA(temp);
13133 kind = PyUnicode_KIND(temp);
13134 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013135 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013136 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013137 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013138 fillobj = zero;
13139 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013140 break;
13141
13142 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013143 {
13144 Py_UCS4 ch = formatchar(v);
13145 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013146 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013147 temp = _PyUnicode_FromUCS4(&ch, 1);
13148 if (temp == NULL)
13149 goto onError;
13150 pbuf = PyUnicode_DATA(temp);
13151 kind = PyUnicode_KIND(temp);
13152 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013153 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013154 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013155
13156 default:
13157 PyErr_Format(PyExc_ValueError,
13158 "unsupported format character '%c' (0x%x) "
13159 "at index %zd",
13160 (31<=c && c<=126) ? (char)c : '?',
13161 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013162 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013163 goto onError;
13164 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013165 /* pbuf is initialized here. */
13166 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013167 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013168 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13169 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013170 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013171 pindex++;
13172 }
13173 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13174 signobj = plus;
13175 len--;
13176 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013177 }
13178 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013179 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013180 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013181 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013182 else
13183 sign = 0;
13184 }
13185 if (width < len)
13186 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013187 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013188 if (fill != ' ') {
13189 assert(signobj != NULL);
13190 if (_PyAccu_Accumulate(&acc, signobj))
13191 goto onError;
13192 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013193 if (width > len)
13194 width--;
13195 }
13196 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013197 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013198 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013199 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013200 second = get_latin1_char(
13201 PyUnicode_READ(kind, pbuf, pindex + 1));
13202 pindex += 2;
13203 if (second == NULL ||
13204 _PyAccu_Accumulate(&acc, zero) ||
13205 _PyAccu_Accumulate(&acc, second))
13206 goto onError;
13207 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013208 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013209 width -= 2;
13210 if (width < 0)
13211 width = 0;
13212 len -= 2;
13213 }
13214 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013215 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013216 if (repeat_accumulate(&acc, fillobj, width - len))
13217 goto onError;
13218 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013219 }
13220 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013221 if (sign) {
13222 assert(signobj != NULL);
13223 if (_PyAccu_Accumulate(&acc, signobj))
13224 goto onError;
13225 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013226 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013227 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13228 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013229 second = get_latin1_char(
13230 PyUnicode_READ(kind, pbuf, pindex + 1));
13231 pindex += 2;
13232 if (second == NULL ||
13233 _PyAccu_Accumulate(&acc, zero) ||
13234 _PyAccu_Accumulate(&acc, second))
13235 goto onError;
13236 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013237 }
13238 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013239 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013240 if (temp != NULL) {
13241 assert(pbuf == PyUnicode_DATA(temp));
13242 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013243 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013244 else {
13245 const char *p = (const char *) pbuf;
13246 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013247 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013248 v = PyUnicode_FromKindAndData(kind, p, len);
13249 }
13250 if (v == NULL)
13251 goto onError;
13252 r = _PyAccu_Accumulate(&acc, v);
13253 Py_DECREF(v);
13254 if (r)
13255 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013256 if (width > len && repeat_accumulate(&acc, blank, width - len))
13257 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013258 if (dict && (argidx < arglen) && c != '%') {
13259 PyErr_SetString(PyExc_TypeError,
13260 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013261 goto onError;
13262 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013263 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013264 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013265 } /* until end */
13266 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013267 PyErr_SetString(PyExc_TypeError,
13268 "not all arguments converted during string formatting");
13269 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013270 }
13271
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013272 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013273 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013274 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013275 }
13276 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013277 Py_XDECREF(temp);
13278 Py_XDECREF(second);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013279 return (PyObject *)result;
13280
Benjamin Peterson29060642009-01-31 22:14:21 +000013281 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013282 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013283 Py_XDECREF(temp);
13284 Py_XDECREF(second);
13285 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013286 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013287 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013288 }
13289 return NULL;
13290}
13291
Jeremy Hylton938ace62002-07-17 16:30:39 +000013292static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013293unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13294
Tim Peters6d6c1a32001-08-02 04:15:00 +000013295static PyObject *
13296unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13297{
Benjamin Peterson29060642009-01-31 22:14:21 +000013298 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013299 static char *kwlist[] = {"object", "encoding", "errors", 0};
13300 char *encoding = NULL;
13301 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013302
Benjamin Peterson14339b62009-01-31 16:36:08 +000013303 if (type != &PyUnicode_Type)
13304 return unicode_subtype_new(type, args, kwds);
13305 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013306 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013307 return NULL;
13308 if (x == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013309 return (PyObject *)PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013310 if (encoding == NULL && errors == NULL)
13311 return PyObject_Str(x);
13312 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013313 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013314}
13315
Guido van Rossume023fe02001-08-30 03:12:59 +000013316static PyObject *
13317unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13318{
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013319 PyUnicodeObject *unicode, *self;
13320 Py_ssize_t length, char_size;
13321 int share_wstr, share_utf8;
13322 unsigned int kind;
13323 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013324
Benjamin Peterson14339b62009-01-31 16:36:08 +000013325 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013326
13327 unicode = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
13328 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013329 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013330 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013331 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013332 return NULL;
13333
13334 self = (PyUnicodeObject *) type->tp_alloc(type, 0);
13335 if (self == NULL) {
13336 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013337 return NULL;
13338 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013339 kind = PyUnicode_KIND(unicode);
13340 length = PyUnicode_GET_LENGTH(unicode);
13341
13342 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013343#ifdef Py_DEBUG
13344 _PyUnicode_HASH(self) = -1;
13345#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013346 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013347#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013348 _PyUnicode_STATE(self).interned = 0;
13349 _PyUnicode_STATE(self).kind = kind;
13350 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013351 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013352 _PyUnicode_STATE(self).ready = 1;
13353 _PyUnicode_WSTR(self) = NULL;
13354 _PyUnicode_UTF8_LENGTH(self) = 0;
13355 _PyUnicode_UTF8(self) = NULL;
13356 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013357 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013358
13359 share_utf8 = 0;
13360 share_wstr = 0;
13361 if (kind == PyUnicode_1BYTE_KIND) {
13362 char_size = 1;
13363 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13364 share_utf8 = 1;
13365 }
13366 else if (kind == PyUnicode_2BYTE_KIND) {
13367 char_size = 2;
13368 if (sizeof(wchar_t) == 2)
13369 share_wstr = 1;
13370 }
13371 else {
13372 assert(kind == PyUnicode_4BYTE_KIND);
13373 char_size = 4;
13374 if (sizeof(wchar_t) == 4)
13375 share_wstr = 1;
13376 }
13377
13378 /* Ensure we won't overflow the length. */
13379 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13380 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013381 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013382 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013383 data = PyObject_MALLOC((length + 1) * char_size);
13384 if (data == NULL) {
13385 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013386 goto onError;
13387 }
13388
Victor Stinnerc3c74152011-10-02 20:39:55 +020013389 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013390 if (share_utf8) {
13391 _PyUnicode_UTF8_LENGTH(self) = length;
13392 _PyUnicode_UTF8(self) = data;
13393 }
13394 if (share_wstr) {
13395 _PyUnicode_WSTR_LENGTH(self) = length;
13396 _PyUnicode_WSTR(self) = (wchar_t *)data;
13397 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013398
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013399 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013400 kind * (length + 1));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013401 Py_DECREF(unicode);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013402 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013403#ifdef Py_DEBUG
13404 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13405#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013406 return (PyObject *)self;
13407
13408onError:
13409 Py_DECREF(unicode);
13410 Py_DECREF(self);
13411 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013412}
13413
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013414PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013415 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013416\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013417Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013418encoding defaults to the current default string encoding.\n\
13419errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013420
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013421static PyObject *unicode_iter(PyObject *seq);
13422
Guido van Rossumd57fd912000-03-10 22:53:23 +000013423PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013424 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013425 "str", /* tp_name */
13426 sizeof(PyUnicodeObject), /* tp_size */
13427 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013428 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013429 (destructor)unicode_dealloc, /* tp_dealloc */
13430 0, /* tp_print */
13431 0, /* tp_getattr */
13432 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013433 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013434 unicode_repr, /* tp_repr */
13435 &unicode_as_number, /* tp_as_number */
13436 &unicode_as_sequence, /* tp_as_sequence */
13437 &unicode_as_mapping, /* tp_as_mapping */
13438 (hashfunc) unicode_hash, /* tp_hash*/
13439 0, /* tp_call*/
13440 (reprfunc) unicode_str, /* tp_str */
13441 PyObject_GenericGetAttr, /* tp_getattro */
13442 0, /* tp_setattro */
13443 0, /* tp_as_buffer */
13444 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013445 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013446 unicode_doc, /* tp_doc */
13447 0, /* tp_traverse */
13448 0, /* tp_clear */
13449 PyUnicode_RichCompare, /* tp_richcompare */
13450 0, /* tp_weaklistoffset */
13451 unicode_iter, /* tp_iter */
13452 0, /* tp_iternext */
13453 unicode_methods, /* tp_methods */
13454 0, /* tp_members */
13455 0, /* tp_getset */
13456 &PyBaseObject_Type, /* tp_base */
13457 0, /* tp_dict */
13458 0, /* tp_descr_get */
13459 0, /* tp_descr_set */
13460 0, /* tp_dictoffset */
13461 0, /* tp_init */
13462 0, /* tp_alloc */
13463 unicode_new, /* tp_new */
13464 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013465};
13466
13467/* Initialize the Unicode implementation */
13468
Thomas Wouters78890102000-07-22 19:25:51 +000013469void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013470{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013471 int i;
13472
Thomas Wouters477c8d52006-05-27 19:21:47 +000013473 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013474 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013475 0x000A, /* LINE FEED */
13476 0x000D, /* CARRIAGE RETURN */
13477 0x001C, /* FILE SEPARATOR */
13478 0x001D, /* GROUP SEPARATOR */
13479 0x001E, /* RECORD SEPARATOR */
13480 0x0085, /* NEXT LINE */
13481 0x2028, /* LINE SEPARATOR */
13482 0x2029, /* PARAGRAPH SEPARATOR */
13483 };
13484
Fred Drakee4315f52000-05-09 19:53:39 +000013485 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013486 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013487 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013488 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013489 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013490
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013491 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013492 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013493 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013494 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013495
13496 /* initialize the linebreak bloom filter */
13497 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013498 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013499 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013500
13501 PyType_Ready(&EncodingMapType);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013502}
13503
13504/* Finalize the Unicode implementation */
13505
Christian Heimesa156e092008-02-16 07:38:31 +000013506int
13507PyUnicode_ClearFreeList(void)
13508{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013509 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013510}
13511
Guido van Rossumd57fd912000-03-10 22:53:23 +000013512void
Thomas Wouters78890102000-07-22 19:25:51 +000013513_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013514{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013515 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013516
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013517 Py_XDECREF(unicode_empty);
13518 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013519
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013520 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013521 if (unicode_latin1[i]) {
13522 Py_DECREF(unicode_latin1[i]);
13523 unicode_latin1[i] = NULL;
13524 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013525 }
Christian Heimesa156e092008-02-16 07:38:31 +000013526 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013527}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013528
Walter Dörwald16807132007-05-25 13:52:07 +000013529void
13530PyUnicode_InternInPlace(PyObject **p)
13531{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013532 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
13533 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013534#ifdef Py_DEBUG
13535 assert(s != NULL);
13536 assert(_PyUnicode_CHECK(s));
13537#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013538 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013539 return;
13540#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013541 /* If it's a subclass, we don't really know what putting
13542 it in the interned dict might do. */
13543 if (!PyUnicode_CheckExact(s))
13544 return;
13545 if (PyUnicode_CHECK_INTERNED(s))
13546 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013547 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013548 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013549 return;
13550 }
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013551 s = (PyUnicodeObject *)(*p);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013552 if (interned == NULL) {
13553 interned = PyDict_New();
13554 if (interned == NULL) {
13555 PyErr_Clear(); /* Don't leave an exception */
13556 return;
13557 }
13558 }
13559 /* It might be that the GetItem call fails even
13560 though the key is present in the dictionary,
13561 namely when this happens during a stack overflow. */
13562 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000013563 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013564 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013565
Benjamin Peterson29060642009-01-31 22:14:21 +000013566 if (t) {
13567 Py_INCREF(t);
13568 Py_DECREF(*p);
13569 *p = t;
13570 return;
13571 }
Walter Dörwald16807132007-05-25 13:52:07 +000013572
Benjamin Peterson14339b62009-01-31 16:36:08 +000013573 PyThreadState_GET()->recursion_critical = 1;
13574 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
13575 PyErr_Clear();
13576 PyThreadState_GET()->recursion_critical = 0;
13577 return;
13578 }
13579 PyThreadState_GET()->recursion_critical = 0;
13580 /* The two references in interned are not counted by refcnt.
13581 The deallocator will take care of this */
13582 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013583 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013584}
13585
13586void
13587PyUnicode_InternImmortal(PyObject **p)
13588{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013589 PyUnicodeObject *u = (PyUnicodeObject *)*p;
13590
Benjamin Peterson14339b62009-01-31 16:36:08 +000013591 PyUnicode_InternInPlace(p);
13592 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013593 _PyUnicode_STATE(u).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013594 Py_INCREF(*p);
13595 }
Walter Dörwald16807132007-05-25 13:52:07 +000013596}
13597
13598PyObject *
13599PyUnicode_InternFromString(const char *cp)
13600{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013601 PyObject *s = PyUnicode_FromString(cp);
13602 if (s == NULL)
13603 return NULL;
13604 PyUnicode_InternInPlace(&s);
13605 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000013606}
13607
Alexander Belopolsky40018472011-02-26 01:02:56 +000013608void
13609_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000013610{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013611 PyObject *keys;
13612 PyUnicodeObject *s;
13613 Py_ssize_t i, n;
13614 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000013615
Benjamin Peterson14339b62009-01-31 16:36:08 +000013616 if (interned == NULL || !PyDict_Check(interned))
13617 return;
13618 keys = PyDict_Keys(interned);
13619 if (keys == NULL || !PyList_Check(keys)) {
13620 PyErr_Clear();
13621 return;
13622 }
Walter Dörwald16807132007-05-25 13:52:07 +000013623
Benjamin Peterson14339b62009-01-31 16:36:08 +000013624 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
13625 detector, interned unicode strings are not forcibly deallocated;
13626 rather, we give them their stolen references back, and then clear
13627 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000013628
Benjamin Peterson14339b62009-01-31 16:36:08 +000013629 n = PyList_GET_SIZE(keys);
13630 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000013631 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013632 for (i = 0; i < n; i++) {
13633 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013634 if (PyUnicode_READY(s) == -1) {
13635 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013636 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013637 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013638 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013639 case SSTATE_NOT_INTERNED:
13640 /* XXX Shouldn't happen */
13641 break;
13642 case SSTATE_INTERNED_IMMORTAL:
13643 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013644 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013645 break;
13646 case SSTATE_INTERNED_MORTAL:
13647 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013648 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013649 break;
13650 default:
13651 Py_FatalError("Inconsistent interned string state.");
13652 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013653 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013654 }
13655 fprintf(stderr, "total size of all interned strings: "
13656 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
13657 "mortal/immortal\n", mortal_size, immortal_size);
13658 Py_DECREF(keys);
13659 PyDict_Clear(interned);
13660 Py_DECREF(interned);
13661 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000013662}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013663
13664
13665/********************* Unicode Iterator **************************/
13666
13667typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013668 PyObject_HEAD
13669 Py_ssize_t it_index;
13670 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013671} unicodeiterobject;
13672
13673static void
13674unicodeiter_dealloc(unicodeiterobject *it)
13675{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013676 _PyObject_GC_UNTRACK(it);
13677 Py_XDECREF(it->it_seq);
13678 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013679}
13680
13681static int
13682unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
13683{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013684 Py_VISIT(it->it_seq);
13685 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013686}
13687
13688static PyObject *
13689unicodeiter_next(unicodeiterobject *it)
13690{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013691 PyUnicodeObject *seq;
13692 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013693
Benjamin Peterson14339b62009-01-31 16:36:08 +000013694 assert(it != NULL);
13695 seq = it->it_seq;
13696 if (seq == NULL)
13697 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013698 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013699
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013700 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
13701 int kind = PyUnicode_KIND(seq);
13702 void *data = PyUnicode_DATA(seq);
13703 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
13704 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013705 if (item != NULL)
13706 ++it->it_index;
13707 return item;
13708 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013709
Benjamin Peterson14339b62009-01-31 16:36:08 +000013710 Py_DECREF(seq);
13711 it->it_seq = NULL;
13712 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013713}
13714
13715static PyObject *
13716unicodeiter_len(unicodeiterobject *it)
13717{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013718 Py_ssize_t len = 0;
13719 if (it->it_seq)
13720 len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index;
13721 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013722}
13723
13724PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
13725
13726static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013727 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000013728 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000013729 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013730};
13731
13732PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013733 PyVarObject_HEAD_INIT(&PyType_Type, 0)
13734 "str_iterator", /* tp_name */
13735 sizeof(unicodeiterobject), /* tp_basicsize */
13736 0, /* tp_itemsize */
13737 /* methods */
13738 (destructor)unicodeiter_dealloc, /* tp_dealloc */
13739 0, /* tp_print */
13740 0, /* tp_getattr */
13741 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013742 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013743 0, /* tp_repr */
13744 0, /* tp_as_number */
13745 0, /* tp_as_sequence */
13746 0, /* tp_as_mapping */
13747 0, /* tp_hash */
13748 0, /* tp_call */
13749 0, /* tp_str */
13750 PyObject_GenericGetAttr, /* tp_getattro */
13751 0, /* tp_setattro */
13752 0, /* tp_as_buffer */
13753 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
13754 0, /* tp_doc */
13755 (traverseproc)unicodeiter_traverse, /* tp_traverse */
13756 0, /* tp_clear */
13757 0, /* tp_richcompare */
13758 0, /* tp_weaklistoffset */
13759 PyObject_SelfIter, /* tp_iter */
13760 (iternextfunc)unicodeiter_next, /* tp_iternext */
13761 unicodeiter_methods, /* tp_methods */
13762 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013763};
13764
13765static PyObject *
13766unicode_iter(PyObject *seq)
13767{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013768 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013769
Benjamin Peterson14339b62009-01-31 16:36:08 +000013770 if (!PyUnicode_Check(seq)) {
13771 PyErr_BadInternalCall();
13772 return NULL;
13773 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013774 if (PyUnicode_READY(seq) == -1)
13775 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013776 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
13777 if (it == NULL)
13778 return NULL;
13779 it->it_index = 0;
13780 Py_INCREF(seq);
13781 it->it_seq = (PyUnicodeObject *)seq;
13782 _PyObject_GC_TRACK(it);
13783 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013784}
13785
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013786#define UNIOP(x) Py_UNICODE_##x
13787#define UNIOP_t Py_UNICODE
13788#include "uniops.h"
13789#undef UNIOP
13790#undef UNIOP_t
13791#define UNIOP(x) Py_UCS4_##x
13792#define UNIOP_t Py_UCS4
13793#include "uniops.h"
13794#undef UNIOP
13795#undef UNIOP_t
Victor Stinner331ea922010-08-10 16:37:20 +000013796
Victor Stinner71133ff2010-09-01 23:43:53 +000013797Py_UNICODE*
Victor Stinner46408602010-09-03 16:18:00 +000013798PyUnicode_AsUnicodeCopy(PyObject *object)
Victor Stinner71133ff2010-09-01 23:43:53 +000013799{
13800 PyUnicodeObject *unicode = (PyUnicodeObject *)object;
13801 Py_UNICODE *copy;
13802 Py_ssize_t size;
13803
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013804 if (!PyUnicode_Check(unicode)) {
13805 PyErr_BadArgument();
13806 return NULL;
13807 }
Victor Stinner71133ff2010-09-01 23:43:53 +000013808 /* Ensure we won't overflow the size. */
13809 if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
13810 PyErr_NoMemory();
13811 return NULL;
13812 }
13813 size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
13814 size *= sizeof(Py_UNICODE);
13815 copy = PyMem_Malloc(size);
13816 if (copy == NULL) {
13817 PyErr_NoMemory();
13818 return NULL;
13819 }
13820 memcpy(copy, PyUnicode_AS_UNICODE(unicode), size);
13821 return copy;
13822}
Martin v. Löwis5b222132007-06-10 09:51:05 +000013823
Georg Brandl66c221e2010-10-14 07:04:07 +000013824/* A _string module, to export formatter_parser and formatter_field_name_split
13825 to the string.Formatter class implemented in Python. */
13826
13827static PyMethodDef _string_methods[] = {
13828 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
13829 METH_O, PyDoc_STR("split the argument as a field name")},
13830 {"formatter_parser", (PyCFunction) formatter_parser,
13831 METH_O, PyDoc_STR("parse the argument as a format string")},
13832 {NULL, NULL}
13833};
13834
13835static struct PyModuleDef _string_module = {
13836 PyModuleDef_HEAD_INIT,
13837 "_string",
13838 PyDoc_STR("string helper module"),
13839 0,
13840 _string_methods,
13841 NULL,
13842 NULL,
13843 NULL,
13844 NULL
13845};
13846
13847PyMODINIT_FUNC
13848PyInit__string(void)
13849{
13850 return PyModule_Create(&_string_module);
13851}
13852
13853
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013854#ifdef __cplusplus
13855}
13856#endif