blob: d5ef87f9098ad09731dbc7b1c309de5f4a696666 [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,
Fred Drake785d14f2000-05-09 19:54:43 +00004modified by Marc-Andre Lemburg <mal@lemburg.com> according to the
Guido van Rossumd57fd912000-03-10 22:53:23 +00005Unicode Integration Proposal (see file Misc/unicode.txt).
6
Thomas Wouters477c8d52006-05-27 19:21:47 +00007Major speed upgrades to the method implementations at the Reykjavik
8NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
9
Guido van Rossum16b1ad92000-08-03 16:24:25 +000010Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000011
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000012--------------------------------------------------------------------
13The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000014
Benjamin Peterson29060642009-01-31 22:14:21 +000015 Copyright (c) 1999 by Secret Labs AB
16 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000017
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000018By obtaining, using, and/or copying this software and/or its
19associated documentation, you agree that you have read, understood,
20and will comply with the following terms and conditions:
21
22Permission to use, copy, modify, and distribute this software and its
23associated documentation for any purpose and without fee is hereby
24granted, provided that the above copyright notice appears in all
25copies, and that both that copyright notice and this permission notice
26appear in supporting documentation, and that the name of Secret Labs
27AB or the author not be used in advertising or publicity pertaining to
28distribution of the software without specific, written prior
29permission.
30
31SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
32THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
33FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
34ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
35WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
36ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
37OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
38--------------------------------------------------------------------
39
40*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000041
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000042#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000043#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000044#include "ucnhash.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000045
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000046#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000047#include <windows.h>
48#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000049
Guido van Rossumd57fd912000-03-10 22:53:23 +000050/* Limit for the Unicode object free list */
51
Christian Heimes2202f872008-02-06 14:31:34 +000052#define PyUnicode_MAXFREELIST 1024
Guido van Rossumd57fd912000-03-10 22:53:23 +000053
54/* Limit for the Unicode object free list stay alive optimization.
55
56 The implementation will keep allocated Unicode memory intact for
57 all objects on the free list having a size less than this
Tim Petersced69f82003-09-16 20:30:58 +000058 limit. This reduces malloc() overhead for small Unicode objects.
Guido van Rossumd57fd912000-03-10 22:53:23 +000059
Christian Heimes2202f872008-02-06 14:31:34 +000060 At worst this will result in PyUnicode_MAXFREELIST *
Guido van Rossumfd4b9572000-04-10 13:51:10 +000061 (sizeof(PyUnicodeObject) + KEEPALIVE_SIZE_LIMIT +
Guido van Rossumd57fd912000-03-10 22:53:23 +000062 malloc()-overhead) bytes of unused garbage.
63
64 Setting the limit to 0 effectively turns the feature off.
65
Guido van Rossumfd4b9572000-04-10 13:51:10 +000066 Note: This is an experimental feature ! If you get core dumps when
67 using Unicode objects, turn this feature off.
Guido van Rossumd57fd912000-03-10 22:53:23 +000068
69*/
70
Guido van Rossumfd4b9572000-04-10 13:51:10 +000071#define KEEPALIVE_SIZE_LIMIT 9
Guido van Rossumd57fd912000-03-10 22:53:23 +000072
73/* Endianness switches; defaults to little endian */
74
75#ifdef WORDS_BIGENDIAN
76# define BYTEORDER_IS_BIG_ENDIAN
77#else
78# define BYTEORDER_IS_LITTLE_ENDIAN
79#endif
80
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000081/* --- Globals ------------------------------------------------------------
82
83 The globals are initialized by the _PyUnicode_Init() API and should
84 not be used before calling that API.
85
86*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000087
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000088
89#ifdef __cplusplus
90extern "C" {
91#endif
92
Walter Dörwald16807132007-05-25 13:52:07 +000093/* This dictionary holds all interned unicode strings. Note that references
94 to strings in this dictionary are *not* counted in the string's ob_refcnt.
95 When the interned string reaches a refcnt of 0 the string deallocation
96 function will delete the reference from this dictionary.
97
98 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +000099 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000100*/
101static PyObject *interned;
102
Guido van Rossumd57fd912000-03-10 22:53:23 +0000103/* Free list for Unicode objects */
Christian Heimes2202f872008-02-06 14:31:34 +0000104static PyUnicodeObject *free_list;
105static int numfree;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000106
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000107/* The empty Unicode object is shared to improve performance. */
108static PyUnicodeObject *unicode_empty;
109
110/* Single character Unicode strings in the Latin-1 range are being
111 shared as well. */
112static PyUnicodeObject *unicode_latin1[256];
113
Christian Heimes190d79e2008-01-30 11:58:22 +0000114/* Fast detection of the most frequent whitespace characters */
115const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000116 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000117/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000118/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000119/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000120/* case 0x000C: * FORM FEED */
121/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000122 0, 1, 1, 1, 1, 1, 0, 0,
123 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000124/* case 0x001C: * FILE SEPARATOR */
125/* case 0x001D: * GROUP SEPARATOR */
126/* case 0x001E: * RECORD SEPARATOR */
127/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000128 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000129/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000130 1, 0, 0, 0, 0, 0, 0, 0,
131 0, 0, 0, 0, 0, 0, 0, 0,
132 0, 0, 0, 0, 0, 0, 0, 0,
133 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000134
Benjamin Peterson14339b62009-01-31 16:36:08 +0000135 0, 0, 0, 0, 0, 0, 0, 0,
136 0, 0, 0, 0, 0, 0, 0, 0,
137 0, 0, 0, 0, 0, 0, 0, 0,
138 0, 0, 0, 0, 0, 0, 0, 0,
139 0, 0, 0, 0, 0, 0, 0, 0,
140 0, 0, 0, 0, 0, 0, 0, 0,
141 0, 0, 0, 0, 0, 0, 0, 0,
142 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000143};
144
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000145static PyObject *unicode_encode_call_errorhandler(const char *errors,
146 PyObject **errorHandler,const char *encoding, const char *reason,
147 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
148 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
149
Victor Stinner31be90b2010-04-22 19:38:16 +0000150static void raise_encode_exception(PyObject **exceptionObject,
151 const char *encoding,
152 const Py_UNICODE *unicode, Py_ssize_t size,
153 Py_ssize_t startpos, Py_ssize_t endpos,
154 const char *reason);
155
Christian Heimes190d79e2008-01-30 11:58:22 +0000156/* Same for linebreaks */
157static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000158 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000159/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000160/* 0x000B, * LINE TABULATION */
161/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000162/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000163 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000164 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000165/* 0x001C, * FILE SEPARATOR */
166/* 0x001D, * GROUP SEPARATOR */
167/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000168 0, 0, 0, 0, 1, 1, 1, 0,
169 0, 0, 0, 0, 0, 0, 0, 0,
170 0, 0, 0, 0, 0, 0, 0, 0,
171 0, 0, 0, 0, 0, 0, 0, 0,
172 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000173
Benjamin Peterson14339b62009-01-31 16:36:08 +0000174 0, 0, 0, 0, 0, 0, 0, 0,
175 0, 0, 0, 0, 0, 0, 0, 0,
176 0, 0, 0, 0, 0, 0, 0, 0,
177 0, 0, 0, 0, 0, 0, 0, 0,
178 0, 0, 0, 0, 0, 0, 0, 0,
179 0, 0, 0, 0, 0, 0, 0, 0,
180 0, 0, 0, 0, 0, 0, 0, 0,
181 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000182};
183
184
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000185Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000186PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000187{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000188#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000189 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000190#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000191 /* This is actually an illegal character, so it should
192 not be passed to unichr. */
193 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000194#endif
195}
196
Thomas Wouters477c8d52006-05-27 19:21:47 +0000197/* --- Bloom Filters ----------------------------------------------------- */
198
199/* stuff to implement simple "bloom filters" for Unicode characters.
200 to keep things simple, we use a single bitmask, using the least 5
201 bits from each unicode characters as the bit index. */
202
203/* the linebreak mask is set up by Unicode_Init below */
204
Antoine Pitrouf068f942010-01-13 14:19:12 +0000205#if LONG_BIT >= 128
206#define BLOOM_WIDTH 128
207#elif LONG_BIT >= 64
208#define BLOOM_WIDTH 64
209#elif LONG_BIT >= 32
210#define BLOOM_WIDTH 32
211#else
212#error "LONG_BIT is smaller than 32"
213#endif
214
Thomas Wouters477c8d52006-05-27 19:21:47 +0000215#define BLOOM_MASK unsigned long
216
217static BLOOM_MASK bloom_linebreak;
218
Antoine Pitrouf068f942010-01-13 14:19:12 +0000219#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
220#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000221
Benjamin Peterson29060642009-01-31 22:14:21 +0000222#define BLOOM_LINEBREAK(ch) \
223 ((ch) < 128U ? ascii_linebreak[(ch)] : \
224 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000225
226Py_LOCAL_INLINE(BLOOM_MASK) make_bloom_mask(Py_UNICODE* ptr, Py_ssize_t len)
227{
228 /* calculate simple bloom-style bitmask for a given unicode string */
229
Antoine Pitrouf068f942010-01-13 14:19:12 +0000230 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000231 Py_ssize_t i;
232
233 mask = 0;
234 for (i = 0; i < len; i++)
Antoine Pitrouf2c54842010-01-13 08:07:53 +0000235 BLOOM_ADD(mask, ptr[i]);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000236
237 return mask;
238}
239
240Py_LOCAL_INLINE(int) unicode_member(Py_UNICODE chr, Py_UNICODE* set, Py_ssize_t setlen)
241{
242 Py_ssize_t i;
243
244 for (i = 0; i < setlen; i++)
245 if (set[i] == chr)
246 return 1;
247
248 return 0;
249}
250
Benjamin Peterson29060642009-01-31 22:14:21 +0000251#define BLOOM_MEMBER(mask, chr, set, setlen) \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000252 BLOOM(mask, chr) && unicode_member(chr, set, setlen)
253
Guido van Rossumd57fd912000-03-10 22:53:23 +0000254/* --- Unicode Object ----------------------------------------------------- */
255
256static
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000257int unicode_resize(register PyUnicodeObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +0000258 Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000259{
260 void *oldstr;
Tim Petersced69f82003-09-16 20:30:58 +0000261
Guido van Rossumfd4b9572000-04-10 13:51:10 +0000262 /* Shortcut if there's nothing much to do. */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000263 if (unicode->length == length)
Benjamin Peterson29060642009-01-31 22:14:21 +0000264 goto reset;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000265
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000266 /* Resizing shared object (unicode_empty or single character
267 objects) in-place is not allowed. Use PyUnicode_Resize()
268 instead ! */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000269
Benjamin Peterson14339b62009-01-31 16:36:08 +0000270 if (unicode == unicode_empty ||
Benjamin Peterson29060642009-01-31 22:14:21 +0000271 (unicode->length == 1 &&
272 unicode->str[0] < 256U &&
273 unicode_latin1[unicode->str[0]] == unicode)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +0000274 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson142957c2008-07-04 19:55:29 +0000275 "can't resize shared str objects");
Guido van Rossumd57fd912000-03-10 22:53:23 +0000276 return -1;
277 }
278
Thomas Wouters477c8d52006-05-27 19:21:47 +0000279 /* We allocate one more byte to make sure the string is Ux0000 terminated.
280 The overallocation is also used by fastsearch, which assumes that it's
281 safe to look at str[length] (without making any assumptions about what
282 it contains). */
283
Guido van Rossumd57fd912000-03-10 22:53:23 +0000284 oldstr = unicode->str;
Christian Heimesb186d002008-03-18 15:15:01 +0000285 unicode->str = PyObject_REALLOC(unicode->str,
Benjamin Peterson29060642009-01-31 22:14:21 +0000286 sizeof(Py_UNICODE) * (length + 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000287 if (!unicode->str) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000288 unicode->str = (Py_UNICODE *)oldstr;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000289 PyErr_NoMemory();
290 return -1;
291 }
292 unicode->str[length] = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000293 unicode->length = length;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000294
Benjamin Peterson29060642009-01-31 22:14:21 +0000295 reset:
Guido van Rossumd57fd912000-03-10 22:53:23 +0000296 /* Reset the object caches */
Marc-André Lemburgbff879c2000-08-03 18:46:08 +0000297 if (unicode->defenc) {
Georg Brandl8ee604b2010-07-29 14:23:06 +0000298 Py_CLEAR(unicode->defenc);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000299 }
300 unicode->hash = -1;
Tim Petersced69f82003-09-16 20:30:58 +0000301
Guido van Rossumd57fd912000-03-10 22:53:23 +0000302 return 0;
303}
304
305/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000306 Ux0000 terminated; some code (e.g. new_identifier)
307 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000308
309 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000310 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000311
312*/
313
314static
Martin v. Löwis18e16552006-02-15 17:27:45 +0000315PyUnicodeObject *_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000316{
317 register PyUnicodeObject *unicode;
318
Thomas Wouters477c8d52006-05-27 19:21:47 +0000319 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000320 if (length == 0 && unicode_empty != NULL) {
321 Py_INCREF(unicode_empty);
322 return unicode_empty;
323 }
324
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000325 /* Ensure we won't overflow the size. */
326 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
327 return (PyUnicodeObject *)PyErr_NoMemory();
328 }
329
Guido van Rossumd57fd912000-03-10 22:53:23 +0000330 /* Unicode freelist & memory allocation */
Christian Heimes2202f872008-02-06 14:31:34 +0000331 if (free_list) {
332 unicode = free_list;
333 free_list = *(PyUnicodeObject **)unicode;
334 numfree--;
Benjamin Peterson29060642009-01-31 22:14:21 +0000335 if (unicode->str) {
336 /* Keep-Alive optimization: we only upsize the buffer,
337 never downsize it. */
338 if ((unicode->length < length) &&
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +0000339 unicode_resize(unicode, length) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000340 PyObject_DEL(unicode->str);
341 unicode->str = NULL;
342 }
Benjamin Peterson14339b62009-01-31 16:36:08 +0000343 }
Guido van Rossumad98db12001-06-14 17:52:02 +0000344 else {
Benjamin Peterson29060642009-01-31 22:14:21 +0000345 size_t new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
346 unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
Guido van Rossumad98db12001-06-14 17:52:02 +0000347 }
348 PyObject_INIT(unicode, &PyUnicode_Type);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000349 }
350 else {
Benjamin Peterson29060642009-01-31 22:14:21 +0000351 size_t new_size;
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000352 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000353 if (unicode == NULL)
354 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +0000355 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
356 unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000357 }
358
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000359 if (!unicode->str) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000360 PyErr_NoMemory();
361 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000362 }
Jeremy Hyltond8082792003-09-16 19:41:39 +0000363 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000364 * the caller fails before initializing str -- unicode_resize()
365 * reads str[0], and the Keep-Alive optimization can keep memory
366 * allocated for str alive across a call to unicode_dealloc(unicode).
367 * We don't want unicode_resize to read uninitialized memory in
368 * that case.
369 */
Jeremy Hyltond8082792003-09-16 19:41:39 +0000370 unicode->str[0] = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000371 unicode->str[length] = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000372 unicode->length = length;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000373 unicode->hash = -1;
Walter Dörwald16807132007-05-25 13:52:07 +0000374 unicode->state = 0;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +0000375 unicode->defenc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000376 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000377
Benjamin Peterson29060642009-01-31 22:14:21 +0000378 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000379 /* XXX UNREF/NEWREF interface should be more symmetrical */
380 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000381 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000382 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000383 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000384}
385
386static
Guido van Rossum9475a232001-10-05 20:51:39 +0000387void unicode_dealloc(register PyUnicodeObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000388{
Walter Dörwald16807132007-05-25 13:52:07 +0000389 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000390 case SSTATE_NOT_INTERNED:
391 break;
Walter Dörwald16807132007-05-25 13:52:07 +0000392
Benjamin Peterson29060642009-01-31 22:14:21 +0000393 case SSTATE_INTERNED_MORTAL:
394 /* revive dead object temporarily for DelItem */
395 Py_REFCNT(unicode) = 3;
396 if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
397 Py_FatalError(
398 "deletion of interned string failed");
399 break;
Walter Dörwald16807132007-05-25 13:52:07 +0000400
Benjamin Peterson29060642009-01-31 22:14:21 +0000401 case SSTATE_INTERNED_IMMORTAL:
402 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +0000403
Benjamin Peterson29060642009-01-31 22:14:21 +0000404 default:
405 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +0000406 }
407
Guido van Rossum604ddf82001-12-06 20:03:56 +0000408 if (PyUnicode_CheckExact(unicode) &&
Benjamin Peterson29060642009-01-31 22:14:21 +0000409 numfree < PyUnicode_MAXFREELIST) {
Guido van Rossumfd4b9572000-04-10 13:51:10 +0000410 /* Keep-Alive optimization */
Benjamin Peterson29060642009-01-31 22:14:21 +0000411 if (unicode->length >= KEEPALIVE_SIZE_LIMIT) {
412 PyObject_DEL(unicode->str);
413 unicode->str = NULL;
414 unicode->length = 0;
415 }
416 if (unicode->defenc) {
Georg Brandl8ee604b2010-07-29 14:23:06 +0000417 Py_CLEAR(unicode->defenc);
Benjamin Peterson29060642009-01-31 22:14:21 +0000418 }
419 /* Add to free list */
Christian Heimes2202f872008-02-06 14:31:34 +0000420 *(PyUnicodeObject **)unicode = free_list;
421 free_list = unicode;
422 numfree++;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000423 }
424 else {
Benjamin Peterson29060642009-01-31 22:14:21 +0000425 PyObject_DEL(unicode->str);
426 Py_XDECREF(unicode->defenc);
427 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000428 }
429}
430
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000431static
432int _PyUnicode_Resize(PyUnicodeObject **unicode, Py_ssize_t length)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000433{
434 register PyUnicodeObject *v;
435
436 /* Argument checks */
437 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000438 PyErr_BadInternalCall();
439 return -1;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000440 }
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000441 v = *unicode;
Christian Heimes90aa7642007-12-19 02:45:37 +0000442 if (v == NULL || !PyUnicode_Check(v) || Py_REFCNT(v) != 1 || length < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000443 PyErr_BadInternalCall();
444 return -1;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000445 }
446
447 /* Resizing unicode_empty and single character objects is not
448 possible since these are being shared. We simply return a fresh
449 copy with the same Unicode content. */
Tim Petersced69f82003-09-16 20:30:58 +0000450 if (v->length != length &&
Benjamin Peterson29060642009-01-31 22:14:21 +0000451 (v == unicode_empty || v->length == 1)) {
452 PyUnicodeObject *w = _PyUnicode_New(length);
453 if (w == NULL)
454 return -1;
455 Py_UNICODE_COPY(w->str, v->str,
456 length < v->length ? length : v->length);
457 Py_DECREF(*unicode);
458 *unicode = w;
459 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000460 }
461
462 /* Note that we don't have to modify *unicode for unshared Unicode
463 objects, since we can modify them in-place. */
464 return unicode_resize(v, length);
465}
466
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000467int PyUnicode_Resize(PyObject **unicode, Py_ssize_t length)
468{
469 return _PyUnicode_Resize((PyUnicodeObject **)unicode, length);
470}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000471
Guido van Rossumd57fd912000-03-10 22:53:23 +0000472PyObject *PyUnicode_FromUnicode(const Py_UNICODE *u,
Benjamin Peterson29060642009-01-31 22:14:21 +0000473 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000474{
475 PyUnicodeObject *unicode;
476
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000477 /* If the Unicode data is known at construction time, we can apply
478 some optimizations which share commonly used objects. */
479 if (u != NULL) {
480
Benjamin Peterson29060642009-01-31 22:14:21 +0000481 /* Optimization for empty strings */
482 if (size == 0 && unicode_empty != NULL) {
483 Py_INCREF(unicode_empty);
484 return (PyObject *)unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000485 }
Benjamin Peterson29060642009-01-31 22:14:21 +0000486
487 /* Single character Unicode objects in the Latin-1 range are
488 shared when using this constructor */
489 if (size == 1 && *u < 256) {
490 unicode = unicode_latin1[*u];
491 if (!unicode) {
492 unicode = _PyUnicode_New(1);
493 if (!unicode)
494 return NULL;
495 unicode->str[0] = *u;
496 unicode_latin1[*u] = unicode;
497 }
498 Py_INCREF(unicode);
499 return (PyObject *)unicode;
500 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000501 }
Tim Petersced69f82003-09-16 20:30:58 +0000502
Guido van Rossumd57fd912000-03-10 22:53:23 +0000503 unicode = _PyUnicode_New(size);
504 if (!unicode)
505 return NULL;
506
507 /* Copy the Unicode data into the new object */
508 if (u != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +0000509 Py_UNICODE_COPY(unicode->str, u, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000510
511 return (PyObject *)unicode;
512}
513
Walter Dörwaldd2034312007-05-18 16:29:38 +0000514PyObject *PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000515{
516 PyUnicodeObject *unicode;
Christian Heimes33fe8092008-04-13 13:53:33 +0000517
Benjamin Peterson14339b62009-01-31 16:36:08 +0000518 if (size < 0) {
519 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +0000520 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +0000521 return NULL;
522 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000523
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000524 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +0000525 some optimizations which share commonly used objects.
526 Also, this means the input must be UTF-8, so fall back to the
527 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000528 if (u != NULL) {
529
Benjamin Peterson29060642009-01-31 22:14:21 +0000530 /* Optimization for empty strings */
531 if (size == 0 && unicode_empty != NULL) {
532 Py_INCREF(unicode_empty);
533 return (PyObject *)unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000534 }
Benjamin Peterson29060642009-01-31 22:14:21 +0000535
536 /* Single characters are shared when using this constructor.
537 Restrict to ASCII, since the input must be UTF-8. */
538 if (size == 1 && Py_CHARMASK(*u) < 128) {
539 unicode = unicode_latin1[Py_CHARMASK(*u)];
540 if (!unicode) {
541 unicode = _PyUnicode_New(1);
542 if (!unicode)
543 return NULL;
544 unicode->str[0] = Py_CHARMASK(*u);
545 unicode_latin1[Py_CHARMASK(*u)] = unicode;
546 }
547 Py_INCREF(unicode);
548 return (PyObject *)unicode;
549 }
Martin v. Löwis9c121062007-08-05 20:26:11 +0000550
551 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000552 }
553
Walter Dörwald55507312007-05-18 13:12:10 +0000554 unicode = _PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000555 if (!unicode)
556 return NULL;
557
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000558 return (PyObject *)unicode;
559}
560
Walter Dörwaldd2034312007-05-18 16:29:38 +0000561PyObject *PyUnicode_FromString(const char *u)
562{
563 size_t size = strlen(u);
564 if (size > PY_SSIZE_T_MAX) {
565 PyErr_SetString(PyExc_OverflowError, "input too long");
566 return NULL;
567 }
568
569 return PyUnicode_FromStringAndSize(u, size);
570}
571
Guido van Rossumd57fd912000-03-10 22:53:23 +0000572#ifdef HAVE_WCHAR_H
573
Mark Dickinson081dfee2009-03-18 14:47:41 +0000574#if (Py_UNICODE_SIZE == 2) && defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4)
575# define CONVERT_WCHAR_TO_SURROGATES
576#endif
577
578#ifdef CONVERT_WCHAR_TO_SURROGATES
579
580/* Here sizeof(wchar_t) is 4 but Py_UNICODE_SIZE == 2, so we need
581 to convert from UTF32 to UTF16. */
582
583PyObject *PyUnicode_FromWideChar(register const wchar_t *w,
584 Py_ssize_t size)
585{
586 PyUnicodeObject *unicode;
587 register Py_ssize_t i;
588 Py_ssize_t alloc;
589 const wchar_t *orig_w;
590
591 if (w == NULL) {
592 if (size == 0)
593 return PyUnicode_FromStringAndSize(NULL, 0);
594 PyErr_BadInternalCall();
595 return NULL;
596 }
597
598 if (size == -1) {
599 size = wcslen(w);
600 }
601
602 alloc = size;
603 orig_w = w;
604 for (i = size; i > 0; i--) {
605 if (*w > 0xFFFF)
606 alloc++;
607 w++;
608 }
609 w = orig_w;
610 unicode = _PyUnicode_New(alloc);
611 if (!unicode)
612 return NULL;
613
614 /* Copy the wchar_t data into the new object */
615 {
616 register Py_UNICODE *u;
617 u = PyUnicode_AS_UNICODE(unicode);
618 for (i = size; i > 0; i--) {
619 if (*w > 0xFFFF) {
620 wchar_t ordinal = *w++;
621 ordinal -= 0x10000;
622 *u++ = 0xD800 | (ordinal >> 10);
623 *u++ = 0xDC00 | (ordinal & 0x3FF);
624 }
625 else
626 *u++ = *w++;
627 }
628 }
629 return (PyObject *)unicode;
630}
631
632#else
633
Guido van Rossumd57fd912000-03-10 22:53:23 +0000634PyObject *PyUnicode_FromWideChar(register const wchar_t *w,
Benjamin Peterson29060642009-01-31 22:14:21 +0000635 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000636{
637 PyUnicodeObject *unicode;
638
639 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +0000640 if (size == 0)
641 return PyUnicode_FromStringAndSize(NULL, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +0000642 PyErr_BadInternalCall();
643 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000644 }
645
Martin v. Löwis790465f2008-04-05 20:41:37 +0000646 if (size == -1) {
647 size = wcslen(w);
648 }
649
Guido van Rossumd57fd912000-03-10 22:53:23 +0000650 unicode = _PyUnicode_New(size);
651 if (!unicode)
652 return NULL;
653
654 /* Copy the wchar_t data into the new object */
Daniel Stutzbach8515eae2010-08-24 21:57:33 +0000655#if Py_UNICODE_SIZE == SIZEOF_WCHAR_T
Guido van Rossumd57fd912000-03-10 22:53:23 +0000656 memcpy(unicode->str, w, size * sizeof(wchar_t));
Tim Petersced69f82003-09-16 20:30:58 +0000657#else
Guido van Rossumd57fd912000-03-10 22:53:23 +0000658 {
Benjamin Peterson29060642009-01-31 22:14:21 +0000659 register Py_UNICODE *u;
660 register Py_ssize_t i;
661 u = PyUnicode_AS_UNICODE(unicode);
662 for (i = size; i > 0; i--)
663 *u++ = *w++;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000664 }
665#endif
666
667 return (PyObject *)unicode;
668}
669
Mark Dickinson081dfee2009-03-18 14:47:41 +0000670#endif /* CONVERT_WCHAR_TO_SURROGATES */
671
672#undef CONVERT_WCHAR_TO_SURROGATES
673
Walter Dörwald346737f2007-05-31 10:44:43 +0000674static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000675makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
676 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +0000677{
Benjamin Peterson14339b62009-01-31 16:36:08 +0000678 *fmt++ = '%';
679 if (width) {
680 if (zeropad)
681 *fmt++ = '0';
682 fmt += sprintf(fmt, "%d", width);
683 }
684 if (precision)
685 fmt += sprintf(fmt, ".%d", precision);
686 if (longflag)
687 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000688 else if (longlongflag) {
689 /* longlongflag should only ever be nonzero on machines with
690 HAVE_LONG_LONG defined */
691#ifdef HAVE_LONG_LONG
692 char *f = PY_FORMAT_LONG_LONG;
693 while (*f)
694 *fmt++ = *f++;
695#else
696 /* we shouldn't ever get here */
697 assert(0);
698 *fmt++ = 'l';
699#endif
700 }
Benjamin Peterson14339b62009-01-31 16:36:08 +0000701 else if (size_tflag) {
702 char *f = PY_FORMAT_SIZE_T;
703 while (*f)
704 *fmt++ = *f++;
705 }
706 *fmt++ = c;
707 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +0000708}
709
Walter Dörwaldd2034312007-05-18 16:29:38 +0000710#define appendstring(string) {for (copy = string;*copy;) *s++ = *copy++;}
711
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000712/* size of fixed-size buffer for formatting single arguments */
713#define ITEM_BUFFER_LEN 21
714/* maximum number of characters required for output of %ld. 21 characters
715 allows for 64-bit integers (in decimal) and an optional sign. */
716#define MAX_LONG_CHARS 21
717/* maximum number of characters required for output of %lld.
718 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
719 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
720#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
721
Walter Dörwaldd2034312007-05-18 16:29:38 +0000722PyObject *
723PyUnicode_FromFormatV(const char *format, va_list vargs)
724{
Benjamin Peterson14339b62009-01-31 16:36:08 +0000725 va_list count;
726 Py_ssize_t callcount = 0;
727 PyObject **callresults = NULL;
728 PyObject **callresult = NULL;
729 Py_ssize_t n = 0;
730 int width = 0;
731 int precision = 0;
732 int zeropad;
733 const char* f;
734 Py_UNICODE *s;
735 PyObject *string;
736 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000737 char buffer[ITEM_BUFFER_LEN+1];
Benjamin Peterson14339b62009-01-31 16:36:08 +0000738 /* use abuffer instead of buffer, if we need more space
739 * (which can happen if there's a format specifier with width). */
740 char *abuffer = NULL;
741 char *realbuffer;
742 Py_ssize_t abuffersize = 0;
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000743 char fmt[61]; /* should be enough for %0width.precisionlld */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000744 const char *copy;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000745
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000746 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000747 /* step 1: count the number of %S/%R/%A/%s format specifications
748 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
749 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
750 * result in an array) */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000751 for (f = format; *f; f++) {
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000752 if (*f == '%') {
753 if (*(f+1)=='%')
754 continue;
Victor Stinner2b574a22011-03-01 22:48:49 +0000755 if (*(f+1)=='S' || *(f+1)=='R' || *(f+1)=='A' || *(f+1) == 'V')
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000756 ++callcount;
David Malcolm96960882010-11-05 17:23:41 +0000757 while (Py_ISDIGIT((unsigned)*f))
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000758 width = (width*10) + *f++ - '0';
David Malcolm96960882010-11-05 17:23:41 +0000759 while (*++f && *f != '%' && !Py_ISALPHA((unsigned)*f))
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000760 ;
761 if (*f == 's')
762 ++callcount;
763 }
Benjamin Peterson9be0b2e2010-09-12 03:40:54 +0000764 else if (128 <= (unsigned char)*f) {
765 PyErr_Format(PyExc_ValueError,
766 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
Victor Stinner4c7db312010-09-12 07:51:18 +0000767 "string, got a non-ASCII byte: 0x%02x",
Benjamin Peterson9be0b2e2010-09-12 03:40:54 +0000768 (unsigned char)*f);
Benjamin Petersond4ac96a2010-09-12 16:40:53 +0000769 return NULL;
Benjamin Peterson9be0b2e2010-09-12 03:40:54 +0000770 }
Benjamin Peterson14339b62009-01-31 16:36:08 +0000771 }
772 /* step 2: allocate memory for the results of
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000773 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000774 if (callcount) {
775 callresults = PyObject_Malloc(sizeof(PyObject *)*callcount);
776 if (!callresults) {
777 PyErr_NoMemory();
778 return NULL;
779 }
780 callresult = callresults;
781 }
782 /* step 3: figure out how large a buffer we need */
783 for (f = format; *f; f++) {
784 if (*f == '%') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000785#ifdef HAVE_LONG_LONG
786 int longlongflag = 0;
787#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +0000788 const char* p = f;
789 width = 0;
David Malcolm96960882010-11-05 17:23:41 +0000790 while (Py_ISDIGIT((unsigned)*f))
Benjamin Peterson14339b62009-01-31 16:36:08 +0000791 width = (width*10) + *f++ - '0';
David Malcolm96960882010-11-05 17:23:41 +0000792 while (*++f && *f != '%' && !Py_ISALPHA((unsigned)*f))
Benjamin Peterson14339b62009-01-31 16:36:08 +0000793 ;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000794
Benjamin Peterson14339b62009-01-31 16:36:08 +0000795 /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
796 * they don't affect the amount of space we reserve.
797 */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000798 if (*f == 'l') {
799 if (f[1] == 'd' || f[1] == 'u') {
800 ++f;
801 }
802#ifdef HAVE_LONG_LONG
803 else if (f[1] == 'l' &&
804 (f[2] == 'd' || f[2] == 'u')) {
805 longlongflag = 1;
806 f += 2;
807 }
808#endif
809 }
810 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000811 ++f;
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000812 }
Walter Dörwaldd2034312007-05-18 16:29:38 +0000813
Benjamin Peterson14339b62009-01-31 16:36:08 +0000814 switch (*f) {
815 case 'c':
Victor Stinner659eb842011-02-23 12:14:22 +0000816 {
817#ifndef Py_UNICODE_WIDE
818 int ordinal = va_arg(count, int);
819 if (ordinal > 0xffff)
820 n += 2;
821 else
822 n++;
823#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000824 (void)va_arg(count, int);
Victor Stinner659eb842011-02-23 12:14:22 +0000825 n++;
826#endif
827 break;
828 }
Benjamin Peterson14339b62009-01-31 16:36:08 +0000829 case '%':
830 n++;
831 break;
832 case 'd': case 'u': case 'i': case 'x':
833 (void) va_arg(count, int);
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000834#ifdef HAVE_LONG_LONG
835 if (longlongflag) {
836 if (width < MAX_LONG_LONG_CHARS)
837 width = MAX_LONG_LONG_CHARS;
838 }
839 else
840#endif
841 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
842 including sign. Decimal takes the most space. This
843 isn't enough for octal. If a width is specified we
844 need more (which we allocate later). */
845 if (width < MAX_LONG_CHARS)
846 width = MAX_LONG_CHARS;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000847 n += width;
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000848 /* XXX should allow for large precision here too. */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000849 if (abuffersize < width)
850 abuffersize = width;
851 break;
852 case 's':
853 {
854 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +0000855 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000856 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
857 if (!str)
858 goto fail;
859 n += PyUnicode_GET_SIZE(str);
860 /* Remember the str and switch to the next slot */
861 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000862 break;
863 }
864 case 'U':
865 {
866 PyObject *obj = va_arg(count, PyObject *);
867 assert(obj && PyUnicode_Check(obj));
868 n += PyUnicode_GET_SIZE(obj);
869 break;
870 }
871 case 'V':
872 {
873 PyObject *obj = va_arg(count, PyObject *);
874 const char *str = va_arg(count, const char *);
Victor Stinner2b574a22011-03-01 22:48:49 +0000875 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000876 assert(obj || str);
877 assert(!obj || PyUnicode_Check(obj));
Victor Stinner2b574a22011-03-01 22:48:49 +0000878 if (obj) {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000879 n += PyUnicode_GET_SIZE(obj);
Victor Stinner2b574a22011-03-01 22:48:49 +0000880 *callresult++ = NULL;
881 }
882 else {
883 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
884 if (!str_obj)
885 goto fail;
886 n += PyUnicode_GET_SIZE(str_obj);
887 *callresult++ = str_obj;
888 }
Benjamin Peterson14339b62009-01-31 16:36:08 +0000889 break;
890 }
891 case 'S':
892 {
893 PyObject *obj = va_arg(count, PyObject *);
894 PyObject *str;
895 assert(obj);
896 str = PyObject_Str(obj);
897 if (!str)
898 goto fail;
899 n += PyUnicode_GET_SIZE(str);
900 /* Remember the str and switch to the next slot */
901 *callresult++ = str;
902 break;
903 }
904 case 'R':
905 {
906 PyObject *obj = va_arg(count, PyObject *);
907 PyObject *repr;
908 assert(obj);
909 repr = PyObject_Repr(obj);
910 if (!repr)
911 goto fail;
912 n += PyUnicode_GET_SIZE(repr);
913 /* Remember the repr and switch to the next slot */
914 *callresult++ = repr;
915 break;
916 }
917 case 'A':
918 {
919 PyObject *obj = va_arg(count, PyObject *);
920 PyObject *ascii;
921 assert(obj);
922 ascii = PyObject_ASCII(obj);
923 if (!ascii)
924 goto fail;
925 n += PyUnicode_GET_SIZE(ascii);
926 /* Remember the repr and switch to the next slot */
927 *callresult++ = ascii;
928 break;
929 }
930 case 'p':
931 (void) va_arg(count, int);
932 /* maximum 64-bit pointer representation:
933 * 0xffffffffffffffff
934 * so 19 characters is enough.
935 * XXX I count 18 -- what's the extra for?
936 */
937 n += 19;
938 break;
939 default:
940 /* if we stumble upon an unknown
941 formatting code, copy the rest of
942 the format string to the output
943 string. (we cannot just skip the
944 code, since there's no way to know
945 what's in the argument list) */
946 n += strlen(p);
947 goto expand;
948 }
949 } else
950 n++;
951 }
Benjamin Peterson29060642009-01-31 22:14:21 +0000952 expand:
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000953 if (abuffersize > ITEM_BUFFER_LEN) {
954 /* add 1 for sprintf's trailing null byte */
955 abuffer = PyObject_Malloc(abuffersize + 1);
Benjamin Peterson14339b62009-01-31 16:36:08 +0000956 if (!abuffer) {
957 PyErr_NoMemory();
958 goto fail;
959 }
960 realbuffer = abuffer;
961 }
962 else
963 realbuffer = buffer;
964 /* step 4: fill the buffer */
965 /* Since we've analyzed how much space we need for the worst case,
966 we don't have to resize the string.
967 There can be no errors beyond this point. */
968 string = PyUnicode_FromUnicode(NULL, n);
969 if (!string)
970 goto fail;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000971
Benjamin Peterson14339b62009-01-31 16:36:08 +0000972 s = PyUnicode_AS_UNICODE(string);
973 callresult = callresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000974
Benjamin Peterson14339b62009-01-31 16:36:08 +0000975 for (f = format; *f; f++) {
976 if (*f == '%') {
977 const char* p = f++;
978 int longflag = 0;
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000979 int longlongflag = 0;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000980 int size_tflag = 0;
981 zeropad = (*f == '0');
982 /* parse the width.precision part */
983 width = 0;
David Malcolm96960882010-11-05 17:23:41 +0000984 while (Py_ISDIGIT((unsigned)*f))
Benjamin Peterson14339b62009-01-31 16:36:08 +0000985 width = (width*10) + *f++ - '0';
986 precision = 0;
987 if (*f == '.') {
988 f++;
David Malcolm96960882010-11-05 17:23:41 +0000989 while (Py_ISDIGIT((unsigned)*f))
Benjamin Peterson14339b62009-01-31 16:36:08 +0000990 precision = (precision*10) + *f++ - '0';
991 }
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000992 /* Handle %ld, %lu, %lld and %llu. */
993 if (*f == 'l') {
994 if (f[1] == 'd' || f[1] == 'u') {
995 longflag = 1;
996 ++f;
997 }
998#ifdef HAVE_LONG_LONG
999 else if (f[1] == 'l' &&
1000 (f[2] == 'd' || f[2] == 'u')) {
1001 longlongflag = 1;
1002 f += 2;
1003 }
1004#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001005 }
1006 /* handle the size_t flag. */
1007 if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
1008 size_tflag = 1;
1009 ++f;
1010 }
Walter Dörwaldd2034312007-05-18 16:29:38 +00001011
Benjamin Peterson14339b62009-01-31 16:36:08 +00001012 switch (*f) {
1013 case 'c':
Victor Stinner659eb842011-02-23 12:14:22 +00001014 {
1015 int ordinal = va_arg(vargs, int);
1016#ifndef Py_UNICODE_WIDE
1017 if (ordinal > 0xffff) {
1018 ordinal -= 0x10000;
1019 *s++ = 0xD800 | (ordinal >> 10);
1020 *s++ = 0xDC00 | (ordinal & 0x3FF);
1021 } else
1022#endif
1023 *s++ = ordinal;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001024 break;
Victor Stinner659eb842011-02-23 12:14:22 +00001025 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00001026 case 'd':
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001027 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
1028 width, precision, 'd');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001029 if (longflag)
1030 sprintf(realbuffer, fmt, va_arg(vargs, long));
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001031#ifdef HAVE_LONG_LONG
1032 else if (longlongflag)
1033 sprintf(realbuffer, fmt, va_arg(vargs, PY_LONG_LONG));
1034#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001035 else if (size_tflag)
1036 sprintf(realbuffer, fmt, va_arg(vargs, Py_ssize_t));
1037 else
1038 sprintf(realbuffer, fmt, va_arg(vargs, int));
1039 appendstring(realbuffer);
1040 break;
1041 case 'u':
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001042 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
1043 width, precision, 'u');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001044 if (longflag)
1045 sprintf(realbuffer, fmt, va_arg(vargs, unsigned long));
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001046#ifdef HAVE_LONG_LONG
1047 else if (longlongflag)
1048 sprintf(realbuffer, fmt, va_arg(vargs,
1049 unsigned PY_LONG_LONG));
1050#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001051 else if (size_tflag)
1052 sprintf(realbuffer, fmt, va_arg(vargs, size_t));
1053 else
1054 sprintf(realbuffer, fmt, va_arg(vargs, unsigned int));
1055 appendstring(realbuffer);
1056 break;
1057 case 'i':
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001058 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'i');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001059 sprintf(realbuffer, fmt, va_arg(vargs, int));
1060 appendstring(realbuffer);
1061 break;
1062 case 'x':
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001063 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001064 sprintf(realbuffer, fmt, va_arg(vargs, int));
1065 appendstring(realbuffer);
1066 break;
1067 case 's':
1068 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001069 /* unused, since we already have the result */
1070 (void) va_arg(vargs, char *);
1071 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(*callresult),
1072 PyUnicode_GET_SIZE(*callresult));
1073 s += PyUnicode_GET_SIZE(*callresult);
1074 /* We're done with the unicode()/repr() => forget it */
1075 Py_DECREF(*callresult);
1076 /* switch to next unicode()/repr() result */
1077 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001078 break;
1079 }
1080 case 'U':
1081 {
1082 PyObject *obj = va_arg(vargs, PyObject *);
1083 Py_ssize_t size = PyUnicode_GET_SIZE(obj);
1084 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size);
1085 s += size;
1086 break;
1087 }
1088 case 'V':
1089 {
1090 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2b574a22011-03-01 22:48:49 +00001091 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001092 if (obj) {
1093 Py_ssize_t size = PyUnicode_GET_SIZE(obj);
1094 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size);
1095 s += size;
1096 } else {
Victor Stinner2b574a22011-03-01 22:48:49 +00001097 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(*callresult),
1098 PyUnicode_GET_SIZE(*callresult));
1099 s += PyUnicode_GET_SIZE(*callresult);
1100 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001101 }
Victor Stinner2b574a22011-03-01 22:48:49 +00001102 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001103 break;
1104 }
1105 case 'S':
1106 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00001107 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00001108 {
1109 Py_UNICODE *ucopy;
1110 Py_ssize_t usize;
1111 Py_ssize_t upos;
1112 /* unused, since we already have the result */
1113 (void) va_arg(vargs, PyObject *);
1114 ucopy = PyUnicode_AS_UNICODE(*callresult);
1115 usize = PyUnicode_GET_SIZE(*callresult);
1116 for (upos = 0; upos<usize;)
1117 *s++ = ucopy[upos++];
1118 /* We're done with the unicode()/repr() => forget it */
1119 Py_DECREF(*callresult);
1120 /* switch to next unicode()/repr() result */
1121 ++callresult;
1122 break;
1123 }
1124 case 'p':
1125 sprintf(buffer, "%p", va_arg(vargs, void*));
1126 /* %p is ill-defined: ensure leading 0x. */
1127 if (buffer[1] == 'X')
1128 buffer[1] = 'x';
1129 else if (buffer[1] != 'x') {
1130 memmove(buffer+2, buffer, strlen(buffer)+1);
1131 buffer[0] = '0';
1132 buffer[1] = 'x';
1133 }
1134 appendstring(buffer);
1135 break;
1136 case '%':
1137 *s++ = '%';
1138 break;
1139 default:
1140 appendstring(p);
1141 goto end;
1142 }
Victor Stinner1205f272010-09-11 00:54:47 +00001143 }
Victor Stinner1205f272010-09-11 00:54:47 +00001144 else
Benjamin Peterson14339b62009-01-31 16:36:08 +00001145 *s++ = *f;
1146 }
Walter Dörwaldd2034312007-05-18 16:29:38 +00001147
Benjamin Peterson29060642009-01-31 22:14:21 +00001148 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001149 if (callresults)
1150 PyObject_Free(callresults);
1151 if (abuffer)
1152 PyObject_Free(abuffer);
1153 PyUnicode_Resize(&string, s - PyUnicode_AS_UNICODE(string));
1154 return string;
Benjamin Peterson29060642009-01-31 22:14:21 +00001155 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001156 if (callresults) {
1157 PyObject **callresult2 = callresults;
1158 while (callresult2 < callresult) {
Victor Stinner2b574a22011-03-01 22:48:49 +00001159 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001160 ++callresult2;
1161 }
1162 PyObject_Free(callresults);
1163 }
1164 if (abuffer)
1165 PyObject_Free(abuffer);
1166 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001167}
1168
1169#undef appendstring
1170
1171PyObject *
1172PyUnicode_FromFormat(const char *format, ...)
1173{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001174 PyObject* ret;
1175 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001176
1177#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00001178 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001179#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00001180 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001181#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001182 ret = PyUnicode_FromFormatV(format, vargs);
1183 va_end(vargs);
1184 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001185}
1186
Victor Stinner5593d8a2010-10-02 11:11:27 +00001187/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
1188 convert a Unicode object to a wide character string.
1189
Victor Stinnerd88d9832011-09-06 02:00:05 +02001190 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00001191 character) required to convert the unicode object. Ignore size argument.
1192
Victor Stinnerd88d9832011-09-06 02:00:05 +02001193 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00001194 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02001195 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00001196static Py_ssize_t
Victor Stinner137c34c2010-09-29 10:25:54 +00001197unicode_aswidechar(PyUnicodeObject *unicode,
1198 wchar_t *w,
1199 Py_ssize_t size)
1200{
1201#if Py_UNICODE_SIZE == SIZEOF_WCHAR_T
Victor Stinner5593d8a2010-10-02 11:11:27 +00001202 Py_ssize_t res;
1203 if (w != NULL) {
1204 res = PyUnicode_GET_SIZE(unicode);
1205 if (size > res)
1206 size = res + 1;
1207 else
1208 res = size;
1209 memcpy(w, unicode->str, size * sizeof(wchar_t));
1210 return res;
1211 }
1212 else
1213 return PyUnicode_GET_SIZE(unicode) + 1;
1214#elif Py_UNICODE_SIZE == 2 && SIZEOF_WCHAR_T == 4
1215 register const Py_UNICODE *u;
1216 const Py_UNICODE *uend;
1217 const wchar_t *worig, *wend;
1218 Py_ssize_t nchar;
1219
Victor Stinner137c34c2010-09-29 10:25:54 +00001220 u = PyUnicode_AS_UNICODE(unicode);
Victor Stinner5593d8a2010-10-02 11:11:27 +00001221 uend = u + PyUnicode_GET_SIZE(unicode);
1222 if (w != NULL) {
1223 worig = w;
1224 wend = w + size;
1225 while (u != uend && w != wend) {
1226 if (0xD800 <= u[0] && u[0] <= 0xDBFF
1227 && 0xDC00 <= u[1] && u[1] <= 0xDFFF)
1228 {
1229 *w = (((u[0] & 0x3FF) << 10) | (u[1] & 0x3FF)) + 0x10000;
1230 u += 2;
1231 }
1232 else {
1233 *w = *u;
1234 u++;
1235 }
1236 w++;
1237 }
1238 if (w != wend)
1239 *w = L'\0';
1240 return w - worig;
1241 }
1242 else {
Victor Stinnerd88d9832011-09-06 02:00:05 +02001243 nchar = 1; /* null character at the end */
Victor Stinner5593d8a2010-10-02 11:11:27 +00001244 while (u != uend) {
1245 if (0xD800 <= u[0] && u[0] <= 0xDBFF
1246 && 0xDC00 <= u[1] && u[1] <= 0xDFFF)
1247 u += 2;
1248 else
1249 u++;
1250 nchar++;
1251 }
1252 }
1253 return nchar;
1254#elif Py_UNICODE_SIZE == 4 && SIZEOF_WCHAR_T == 2
1255 register Py_UNICODE *u, *uend, ordinal;
1256 register Py_ssize_t i;
1257 wchar_t *worig, *wend;
1258 Py_ssize_t nchar;
1259
1260 u = PyUnicode_AS_UNICODE(unicode);
1261 uend = u + PyUnicode_GET_SIZE(u);
1262 if (w != NULL) {
1263 worig = w;
1264 wend = w + size;
1265 while (u != uend && w != wend) {
1266 ordinal = *u;
1267 if (ordinal > 0xffff) {
1268 ordinal -= 0x10000;
1269 *w++ = 0xD800 | (ordinal >> 10);
1270 *w++ = 0xDC00 | (ordinal & 0x3FF);
1271 }
1272 else
1273 *w++ = ordinal;
1274 u++;
1275 }
1276 if (w != wend)
1277 *w = 0;
1278 return w - worig;
1279 }
1280 else {
Victor Stinnerd88d9832011-09-06 02:00:05 +02001281 nchar = 1; /* null character */
Victor Stinner5593d8a2010-10-02 11:11:27 +00001282 while (u != uend) {
1283 if (*u > 0xffff)
1284 nchar += 2;
1285 else
1286 nchar++;
1287 u++;
1288 }
1289 return nchar;
1290 }
1291#else
1292# error "unsupported wchar_t and Py_UNICODE sizes, see issue #8670"
Victor Stinner137c34c2010-09-29 10:25:54 +00001293#endif
1294}
1295
1296Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001297PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00001298 wchar_t *w,
1299 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001300{
1301 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001302 PyErr_BadInternalCall();
1303 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001304 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001305 return unicode_aswidechar((PyUnicodeObject*)unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001306}
1307
Victor Stinner137c34c2010-09-29 10:25:54 +00001308wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00001309PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00001310 Py_ssize_t *size)
1311{
1312 wchar_t* buffer;
1313 Py_ssize_t buflen;
1314
1315 if (unicode == NULL) {
1316 PyErr_BadInternalCall();
1317 return NULL;
1318 }
1319
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00001320 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, NULL, 0);
Victor Stinner5593d8a2010-10-02 11:11:27 +00001321 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00001322 PyErr_NoMemory();
1323 return NULL;
1324 }
1325
Victor Stinner137c34c2010-09-29 10:25:54 +00001326 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
1327 if (buffer == NULL) {
1328 PyErr_NoMemory();
1329 return NULL;
1330 }
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00001331 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, buffer, buflen);
Victor Stinner5593d8a2010-10-02 11:11:27 +00001332 if (size != NULL)
1333 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00001334 return buffer;
1335}
1336
Guido van Rossumd57fd912000-03-10 22:53:23 +00001337#endif
1338
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001339PyObject *PyUnicode_FromOrdinal(int ordinal)
1340{
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001341 Py_UNICODE s[2];
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001342
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001343 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001344 PyErr_SetString(PyExc_ValueError,
1345 "chr() arg not in range(0x110000)");
1346 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001347 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001348
1349#ifndef Py_UNICODE_WIDE
1350 if (ordinal > 0xffff) {
1351 ordinal -= 0x10000;
1352 s[0] = 0xD800 | (ordinal >> 10);
1353 s[1] = 0xDC00 | (ordinal & 0x3FF);
1354 return PyUnicode_FromUnicode(s, 2);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001355 }
1356#endif
1357
Hye-Shik Chang40574832004-04-06 07:24:51 +00001358 s[0] = (Py_UNICODE)ordinal;
1359 return PyUnicode_FromUnicode(s, 1);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001360}
1361
Guido van Rossumd57fd912000-03-10 22:53:23 +00001362PyObject *PyUnicode_FromObject(register PyObject *obj)
1363{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001364 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00001365 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001366 if (PyUnicode_CheckExact(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001367 Py_INCREF(obj);
1368 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001369 }
1370 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001371 /* For a Unicode subtype that's not a Unicode object,
1372 return a true Unicode object with the same data. */
1373 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(obj),
1374 PyUnicode_GET_SIZE(obj));
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001375 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001376 PyErr_Format(PyExc_TypeError,
1377 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00001378 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001379 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001380}
1381
1382PyObject *PyUnicode_FromEncodedObject(register PyObject *obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00001383 const char *encoding,
1384 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001385{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001386 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001387 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00001388
Guido van Rossumd57fd912000-03-10 22:53:23 +00001389 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001390 PyErr_BadInternalCall();
1391 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001392 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001393
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001394 /* Decoding bytes objects is the most common case and should be fast */
1395 if (PyBytes_Check(obj)) {
1396 if (PyBytes_GET_SIZE(obj) == 0) {
1397 Py_INCREF(unicode_empty);
1398 v = (PyObject *) unicode_empty;
1399 }
1400 else {
1401 v = PyUnicode_Decode(
1402 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
1403 encoding, errors);
1404 }
1405 return v;
1406 }
1407
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001408 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001409 PyErr_SetString(PyExc_TypeError,
1410 "decoding str is not supported");
1411 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001412 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001413
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001414 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
1415 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
1416 PyErr_Format(PyExc_TypeError,
1417 "coercing to str: need bytes, bytearray "
1418 "or buffer-like object, %.80s found",
1419 Py_TYPE(obj)->tp_name);
1420 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00001421 }
Tim Petersced69f82003-09-16 20:30:58 +00001422
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001423 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001424 Py_INCREF(unicode_empty);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001425 v = (PyObject *) unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001426 }
Tim Petersced69f82003-09-16 20:30:58 +00001427 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001428 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00001429
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001430 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001431 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001432}
1433
Victor Stinner600d3be2010-06-10 12:00:55 +00001434/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00001435 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
1436 1 on success. */
1437static int
1438normalize_encoding(const char *encoding,
1439 char *lower,
1440 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001441{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001442 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00001443 char *l;
1444 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001445
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001446 e = encoding;
1447 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00001448 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00001449 while (*e) {
1450 if (l == l_end)
1451 return 0;
David Malcolm96960882010-11-05 17:23:41 +00001452 if (Py_ISUPPER(*e)) {
1453 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001454 }
1455 else if (*e == '_') {
1456 *l++ = '-';
1457 e++;
1458 }
1459 else {
1460 *l++ = *e++;
1461 }
1462 }
1463 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00001464 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00001465}
1466
1467PyObject *PyUnicode_Decode(const char *s,
1468 Py_ssize_t size,
1469 const char *encoding,
1470 const char *errors)
1471{
1472 PyObject *buffer = NULL, *unicode;
1473 Py_buffer info;
1474 char lower[11]; /* Enough for any encoding shortcut */
1475
1476 if (encoding == NULL)
1477 encoding = PyUnicode_GetDefaultEncoding();
Fred Drakee4315f52000-05-09 19:53:39 +00001478
1479 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00001480 if (normalize_encoding(encoding, lower, sizeof(lower))) {
1481 if (strcmp(lower, "utf-8") == 0)
1482 return PyUnicode_DecodeUTF8(s, size, errors);
1483 else if ((strcmp(lower, "latin-1") == 0) ||
1484 (strcmp(lower, "iso-8859-1") == 0))
1485 return PyUnicode_DecodeLatin1(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001486#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Victor Stinner37296e82010-06-10 13:36:23 +00001487 else if (strcmp(lower, "mbcs") == 0)
1488 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001489#endif
Victor Stinner37296e82010-06-10 13:36:23 +00001490 else if (strcmp(lower, "ascii") == 0)
1491 return PyUnicode_DecodeASCII(s, size, errors);
1492 else if (strcmp(lower, "utf-16") == 0)
1493 return PyUnicode_DecodeUTF16(s, size, errors, 0);
1494 else if (strcmp(lower, "utf-32") == 0)
1495 return PyUnicode_DecodeUTF32(s, size, errors, 0);
1496 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001497
1498 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00001499 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00001500 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00001501 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00001502 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001503 if (buffer == NULL)
1504 goto onError;
1505 unicode = PyCodec_Decode(buffer, encoding, errors);
1506 if (unicode == NULL)
1507 goto onError;
1508 if (!PyUnicode_Check(unicode)) {
1509 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001510 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00001511 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001512 Py_DECREF(unicode);
1513 goto onError;
1514 }
1515 Py_DECREF(buffer);
1516 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00001517
Benjamin Peterson29060642009-01-31 22:14:21 +00001518 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001519 Py_XDECREF(buffer);
1520 return NULL;
1521}
1522
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001523PyObject *PyUnicode_AsDecodedObject(PyObject *unicode,
1524 const char *encoding,
1525 const char *errors)
1526{
1527 PyObject *v;
1528
1529 if (!PyUnicode_Check(unicode)) {
1530 PyErr_BadArgument();
1531 goto onError;
1532 }
1533
1534 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001535 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001536
1537 /* Decode via the codec registry */
1538 v = PyCodec_Decode(unicode, encoding, errors);
1539 if (v == NULL)
1540 goto onError;
1541 return v;
1542
Benjamin Peterson29060642009-01-31 22:14:21 +00001543 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001544 return NULL;
1545}
1546
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001547PyObject *PyUnicode_AsDecodedUnicode(PyObject *unicode,
1548 const char *encoding,
1549 const char *errors)
1550{
1551 PyObject *v;
1552
1553 if (!PyUnicode_Check(unicode)) {
1554 PyErr_BadArgument();
1555 goto onError;
1556 }
1557
1558 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001559 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001560
1561 /* Decode via the codec registry */
1562 v = PyCodec_Decode(unicode, encoding, errors);
1563 if (v == NULL)
1564 goto onError;
1565 if (!PyUnicode_Check(v)) {
1566 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001567 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001568 Py_TYPE(v)->tp_name);
1569 Py_DECREF(v);
1570 goto onError;
1571 }
1572 return v;
1573
Benjamin Peterson29060642009-01-31 22:14:21 +00001574 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001575 return NULL;
1576}
1577
Guido van Rossumd57fd912000-03-10 22:53:23 +00001578PyObject *PyUnicode_Encode(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00001579 Py_ssize_t size,
1580 const char *encoding,
1581 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001582{
1583 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00001584
Guido van Rossumd57fd912000-03-10 22:53:23 +00001585 unicode = PyUnicode_FromUnicode(s, size);
1586 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001587 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001588 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
1589 Py_DECREF(unicode);
1590 return v;
1591}
1592
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001593PyObject *PyUnicode_AsEncodedObject(PyObject *unicode,
1594 const char *encoding,
1595 const char *errors)
1596{
1597 PyObject *v;
1598
1599 if (!PyUnicode_Check(unicode)) {
1600 PyErr_BadArgument();
1601 goto onError;
1602 }
1603
1604 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001605 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001606
1607 /* Encode via the codec registry */
1608 v = PyCodec_Encode(unicode, encoding, errors);
1609 if (v == NULL)
1610 goto onError;
1611 return v;
1612
Benjamin Peterson29060642009-01-31 22:14:21 +00001613 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001614 return NULL;
1615}
1616
Victor Stinnerad158722010-10-27 00:25:46 +00001617PyObject *
1618PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00001619{
Victor Stinner313a1202010-06-11 23:56:51 +00001620#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Victor Stinnerad158722010-10-27 00:25:46 +00001621 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
1622 PyUnicode_GET_SIZE(unicode),
1623 NULL);
1624#elif defined(__APPLE__)
1625 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
1626 PyUnicode_GET_SIZE(unicode),
1627 "surrogateescape");
1628#else
Victor Stinner3cbf14b2011-04-27 00:24:21 +02001629 PyInterpreterState *interp = PyThreadState_GET()->interp;
1630 /* Bootstrap check: if the filesystem codec is implemented in Python, we
1631 cannot use it to encode and decode filenames before it is loaded. Load
1632 the Python codec requires to encode at least its own filename. Use the C
1633 version of the locale codec until the codec registry is initialized and
1634 the Python codec is loaded.
1635
1636 Py_FileSystemDefaultEncoding is shared between all interpreters, we
1637 cannot only rely on it: check also interp->fscodec_initialized for
1638 subinterpreters. */
1639 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00001640 return PyUnicode_AsEncodedString(unicode,
1641 Py_FileSystemDefaultEncoding,
1642 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00001643 }
1644 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001645 /* locale encoding with surrogateescape */
1646 wchar_t *wchar;
1647 char *bytes;
1648 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00001649 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001650
1651 wchar = PyUnicode_AsWideCharString(unicode, NULL);
1652 if (wchar == NULL)
1653 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00001654 bytes = _Py_wchar2char(wchar, &error_pos);
1655 if (bytes == NULL) {
1656 if (error_pos != (size_t)-1) {
1657 char *errmsg = strerror(errno);
1658 PyObject *exc = NULL;
1659 if (errmsg == NULL)
1660 errmsg = "Py_wchar2char() failed";
1661 raise_encode_exception(&exc,
1662 "filesystemencoding",
1663 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
1664 error_pos, error_pos+1,
1665 errmsg);
1666 Py_XDECREF(exc);
1667 }
1668 else
1669 PyErr_NoMemory();
1670 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001671 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00001672 }
1673 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001674
1675 bytes_obj = PyBytes_FromString(bytes);
1676 PyMem_Free(bytes);
1677 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00001678 }
Victor Stinnerad158722010-10-27 00:25:46 +00001679#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00001680}
1681
Guido van Rossumd57fd912000-03-10 22:53:23 +00001682PyObject *PyUnicode_AsEncodedString(PyObject *unicode,
1683 const char *encoding,
1684 const char *errors)
1685{
1686 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00001687 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00001688
Guido van Rossumd57fd912000-03-10 22:53:23 +00001689 if (!PyUnicode_Check(unicode)) {
1690 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001691 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001692 }
Fred Drakee4315f52000-05-09 19:53:39 +00001693
Tim Petersced69f82003-09-16 20:30:58 +00001694 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001695 encoding = PyUnicode_GetDefaultEncoding();
Fred Drakee4315f52000-05-09 19:53:39 +00001696
1697 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00001698 if (normalize_encoding(encoding, lower, sizeof(lower))) {
1699 if (strcmp(lower, "utf-8") == 0)
1700 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
1701 PyUnicode_GET_SIZE(unicode),
1702 errors);
1703 else if ((strcmp(lower, "latin-1") == 0) ||
1704 (strcmp(lower, "iso-8859-1") == 0))
1705 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
1706 PyUnicode_GET_SIZE(unicode),
1707 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001708#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Victor Stinner37296e82010-06-10 13:36:23 +00001709 else if (strcmp(lower, "mbcs") == 0)
1710 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
1711 PyUnicode_GET_SIZE(unicode),
1712 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001713#endif
Victor Stinner37296e82010-06-10 13:36:23 +00001714 else if (strcmp(lower, "ascii") == 0)
1715 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
1716 PyUnicode_GET_SIZE(unicode),
1717 errors);
1718 }
Victor Stinner59e62db2010-05-15 13:14:32 +00001719 /* During bootstrap, we may need to find the encodings
1720 package, to load the file system encoding, and require the
1721 file system encoding in order to load the encodings
1722 package.
Christian Heimes6a27efa2008-10-30 21:48:26 +00001723
Victor Stinner59e62db2010-05-15 13:14:32 +00001724 Break out of this dependency by assuming that the path to
1725 the encodings module is ASCII-only. XXX could try wcstombs
1726 instead, if the file system encoding is the locale's
1727 encoding. */
Victor Stinner37296e82010-06-10 13:36:23 +00001728 if (Py_FileSystemDefaultEncoding &&
Victor Stinner59e62db2010-05-15 13:14:32 +00001729 strcmp(encoding, Py_FileSystemDefaultEncoding) == 0 &&
1730 !PyThreadState_GET()->interp->codecs_initialized)
1731 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
1732 PyUnicode_GET_SIZE(unicode),
1733 errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001734
1735 /* Encode via the codec registry */
1736 v = PyCodec_Encode(unicode, encoding, errors);
1737 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001738 return NULL;
1739
1740 /* The normal path */
1741 if (PyBytes_Check(v))
1742 return v;
1743
1744 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001745 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001746 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001747 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001748
1749 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1750 "encoder %s returned bytearray instead of bytes",
1751 encoding);
1752 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001753 Py_DECREF(v);
1754 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001755 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001756
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001757 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
1758 Py_DECREF(v);
1759 return b;
1760 }
1761
1762 PyErr_Format(PyExc_TypeError,
1763 "encoder did not return a bytes object (type=%.400s)",
1764 Py_TYPE(v)->tp_name);
1765 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001766 return NULL;
1767}
1768
1769PyObject *PyUnicode_AsEncodedUnicode(PyObject *unicode,
1770 const char *encoding,
1771 const char *errors)
1772{
1773 PyObject *v;
1774
1775 if (!PyUnicode_Check(unicode)) {
1776 PyErr_BadArgument();
1777 goto onError;
1778 }
1779
1780 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001781 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001782
1783 /* Encode via the codec registry */
1784 v = PyCodec_Encode(unicode, encoding, errors);
1785 if (v == NULL)
1786 goto onError;
1787 if (!PyUnicode_Check(v)) {
1788 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001789 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001790 Py_TYPE(v)->tp_name);
1791 Py_DECREF(v);
1792 goto onError;
1793 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001794 return v;
Tim Petersced69f82003-09-16 20:30:58 +00001795
Benjamin Peterson29060642009-01-31 22:14:21 +00001796 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001797 return NULL;
1798}
1799
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001800PyObject *_PyUnicode_AsDefaultEncodedString(PyObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00001801 const char *errors)
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001802{
1803 PyObject *v = ((PyUnicodeObject *)unicode)->defenc;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001804 if (v)
1805 return v;
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001806 if (errors != NULL)
1807 Py_FatalError("non-NULL encoding in _PyUnicode_AsDefaultEncodedString");
Guido van Rossum98297ee2007-11-06 21:34:58 +00001808 v = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
Guido van Rossum06610092007-08-16 21:02:22 +00001809 PyUnicode_GET_SIZE(unicode),
1810 NULL);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001811 if (!v)
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001812 return NULL;
Guido van Rossume7a0d392007-07-12 07:53:00 +00001813 ((PyUnicodeObject *)unicode)->defenc = v;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001814 return v;
1815}
1816
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001817PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00001818PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001819 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00001820 return PyUnicode_DecodeFSDefaultAndSize(s, size);
1821}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001822
Christian Heimes5894ba72007-11-04 11:43:14 +00001823PyObject*
1824PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
1825{
Victor Stinnerad158722010-10-27 00:25:46 +00001826#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
1827 return PyUnicode_DecodeMBCS(s, size, NULL);
1828#elif defined(__APPLE__)
1829 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
1830#else
Victor Stinner3cbf14b2011-04-27 00:24:21 +02001831 PyInterpreterState *interp = PyThreadState_GET()->interp;
1832 /* Bootstrap check: if the filesystem codec is implemented in Python, we
1833 cannot use it to encode and decode filenames before it is loaded. Load
1834 the Python codec requires to encode at least its own filename. Use the C
1835 version of the locale codec until the codec registry is initialized and
1836 the Python codec is loaded.
1837
1838 Py_FileSystemDefaultEncoding is shared between all interpreters, we
1839 cannot only rely on it: check also interp->fscodec_initialized for
1840 subinterpreters. */
1841 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001842 return PyUnicode_Decode(s, size,
1843 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00001844 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001845 }
1846 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001847 /* locale encoding with surrogateescape */
1848 wchar_t *wchar;
1849 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00001850 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001851
1852 if (s[size] != '\0' || size != strlen(s)) {
1853 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
1854 return NULL;
1855 }
1856
Victor Stinner168e1172010-10-16 23:16:16 +00001857 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001858 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00001859 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001860
Victor Stinner168e1172010-10-16 23:16:16 +00001861 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001862 PyMem_Free(wchar);
1863 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001864 }
Victor Stinnerad158722010-10-27 00:25:46 +00001865#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001866}
1867
Martin v. Löwis011e8422009-05-05 04:43:17 +00001868
1869int
Antoine Pitrou13348842012-01-29 18:36:34 +01001870_PyUnicode_HasNULChars(PyObject* s)
1871{
1872 static PyObject *nul = NULL;
1873
1874 if (nul == NULL)
1875 nul = PyUnicode_FromStringAndSize("\0", 1);
1876 if (nul == NULL)
1877 return -1;
1878 return PyUnicode_Contains(s, nul);
1879}
1880
1881
1882int
Martin v. Löwis011e8422009-05-05 04:43:17 +00001883PyUnicode_FSConverter(PyObject* arg, void* addr)
1884{
1885 PyObject *output = NULL;
1886 Py_ssize_t size;
1887 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00001888 if (arg == NULL) {
1889 Py_DECREF(*(PyObject**)addr);
1890 return 1;
1891 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00001892 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00001893 output = arg;
1894 Py_INCREF(output);
1895 }
1896 else {
1897 arg = PyUnicode_FromObject(arg);
1898 if (!arg)
1899 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00001900 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00001901 Py_DECREF(arg);
1902 if (!output)
1903 return 0;
1904 if (!PyBytes_Check(output)) {
1905 Py_DECREF(output);
1906 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
1907 return 0;
1908 }
1909 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00001910 size = PyBytes_GET_SIZE(output);
1911 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00001912 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05001913 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00001914 Py_DECREF(output);
1915 return 0;
1916 }
1917 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00001918 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00001919}
1920
1921
Victor Stinner47fcb5b2010-08-13 23:59:58 +00001922int
1923PyUnicode_FSDecoder(PyObject* arg, void* addr)
1924{
1925 PyObject *output = NULL;
1926 Py_ssize_t size;
1927 void *data;
1928 if (arg == NULL) {
1929 Py_DECREF(*(PyObject**)addr);
1930 return 1;
1931 }
1932 if (PyUnicode_Check(arg)) {
1933 output = arg;
1934 Py_INCREF(output);
1935 }
1936 else {
1937 arg = PyBytes_FromObject(arg);
1938 if (!arg)
1939 return 0;
1940 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
1941 PyBytes_GET_SIZE(arg));
1942 Py_DECREF(arg);
1943 if (!output)
1944 return 0;
1945 if (!PyUnicode_Check(output)) {
1946 Py_DECREF(output);
1947 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
1948 return 0;
1949 }
1950 }
1951 size = PyUnicode_GET_SIZE(output);
1952 data = PyUnicode_AS_UNICODE(output);
1953 if (size != Py_UNICODE_strlen(data)) {
1954 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
1955 Py_DECREF(output);
1956 return 0;
1957 }
1958 *(PyObject**)addr = output;
1959 return Py_CLEANUP_SUPPORTED;
1960}
1961
1962
Martin v. Löwis5b222132007-06-10 09:51:05 +00001963char*
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001964_PyUnicode_AsStringAndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00001965{
Christian Heimesf3863112007-11-22 07:46:41 +00001966 PyObject *bytes;
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00001967 if (!PyUnicode_Check(unicode)) {
1968 PyErr_BadArgument();
1969 return NULL;
1970 }
Christian Heimesf3863112007-11-22 07:46:41 +00001971 bytes = _PyUnicode_AsDefaultEncodedString(unicode, NULL);
1972 if (bytes == NULL)
Martin v. Löwis5b222132007-06-10 09:51:05 +00001973 return NULL;
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001974 if (psize != NULL)
Christian Heimes72b710a2008-05-26 13:28:38 +00001975 *psize = PyBytes_GET_SIZE(bytes);
1976 return PyBytes_AS_STRING(bytes);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001977}
1978
1979char*
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001980_PyUnicode_AsString(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001981{
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001982 return _PyUnicode_AsStringAndSize(unicode, NULL);
Martin v. Löwis5b222132007-06-10 09:51:05 +00001983}
1984
Guido van Rossumd57fd912000-03-10 22:53:23 +00001985Py_UNICODE *PyUnicode_AsUnicode(PyObject *unicode)
1986{
1987 if (!PyUnicode_Check(unicode)) {
1988 PyErr_BadArgument();
1989 goto onError;
1990 }
1991 return PyUnicode_AS_UNICODE(unicode);
1992
Benjamin Peterson29060642009-01-31 22:14:21 +00001993 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001994 return NULL;
1995}
1996
Martin v. Löwis18e16552006-02-15 17:27:45 +00001997Py_ssize_t PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001998{
1999 if (!PyUnicode_Check(unicode)) {
2000 PyErr_BadArgument();
2001 goto onError;
2002 }
2003 return PyUnicode_GET_SIZE(unicode);
2004
Benjamin Peterson29060642009-01-31 22:14:21 +00002005 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002006 return -1;
2007}
2008
Thomas Wouters78890102000-07-22 19:25:51 +00002009const char *PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00002010{
Victor Stinner42cb4622010-09-01 19:39:01 +00002011 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00002012}
2013
Victor Stinner554f3f02010-06-16 23:33:54 +00002014/* create or adjust a UnicodeDecodeError */
2015static void
2016make_decode_exception(PyObject **exceptionObject,
2017 const char *encoding,
2018 const char *input, Py_ssize_t length,
2019 Py_ssize_t startpos, Py_ssize_t endpos,
2020 const char *reason)
2021{
2022 if (*exceptionObject == NULL) {
2023 *exceptionObject = PyUnicodeDecodeError_Create(
2024 encoding, input, length, startpos, endpos, reason);
2025 }
2026 else {
2027 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
2028 goto onError;
2029 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
2030 goto onError;
2031 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
2032 goto onError;
2033 }
2034 return;
2035
2036onError:
2037 Py_DECREF(*exceptionObject);
2038 *exceptionObject = NULL;
2039}
2040
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002041/* error handling callback helper:
2042 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00002043 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002044 and adjust various state variables.
2045 return 0 on success, -1 on error
2046*/
2047
2048static
2049int unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00002050 const char *encoding, const char *reason,
2051 const char **input, const char **inend, Py_ssize_t *startinpos,
2052 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
2053 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002054{
Benjamin Peterson142957c2008-07-04 19:55:29 +00002055 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002056
2057 PyObject *restuple = NULL;
2058 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002059 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002060 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002061 Py_ssize_t requiredsize;
2062 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002063 Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002064 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002065 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002066 int res = -1;
2067
2068 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002069 *errorHandler = PyCodec_LookupError(errors);
2070 if (*errorHandler == NULL)
2071 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002072 }
2073
Victor Stinner554f3f02010-06-16 23:33:54 +00002074 make_decode_exception(exceptionObject,
2075 encoding,
2076 *input, *inend - *input,
2077 *startinpos, *endinpos,
2078 reason);
2079 if (*exceptionObject == NULL)
2080 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002081
2082 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
2083 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002084 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002085 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00002086 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00002087 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002088 }
2089 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00002090 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002091
2092 /* Copy back the bytes variables, which might have been modified by the
2093 callback */
2094 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
2095 if (!inputobj)
2096 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00002097 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002098 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00002099 }
Christian Heimes72b710a2008-05-26 13:28:38 +00002100 *input = PyBytes_AS_STRING(inputobj);
2101 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002102 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00002103 /* we can DECREF safely, as the exception has another reference,
2104 so the object won't go away. */
2105 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002106
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002107 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00002108 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00002109 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002110 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
2111 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00002112 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002113
2114 /* need more space? (at least enough for what we
2115 have+the replacement+the rest of the string (starting
2116 at the new input position), so we won't have to check space
2117 when there are no errors in the rest of the string) */
2118 repptr = PyUnicode_AS_UNICODE(repunicode);
2119 repsize = PyUnicode_GET_SIZE(repunicode);
2120 requiredsize = *outpos + repsize + insize-newpos;
2121 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002122 if (requiredsize<2*outsize)
2123 requiredsize = 2*outsize;
2124 if (_PyUnicode_Resize(output, requiredsize) < 0)
2125 goto onError;
2126 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002127 }
2128 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002129 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002130 Py_UNICODE_COPY(*outptr, repptr, repsize);
2131 *outptr += repsize;
2132 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002133
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002134 /* we made it! */
2135 res = 0;
2136
Benjamin Peterson29060642009-01-31 22:14:21 +00002137 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002138 Py_XDECREF(restuple);
2139 return res;
2140}
2141
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002142/* --- UTF-7 Codec -------------------------------------------------------- */
2143
Antoine Pitrou244651a2009-05-04 18:56:13 +00002144/* See RFC2152 for details. We encode conservatively and decode liberally. */
2145
2146/* Three simple macros defining base-64. */
2147
2148/* Is c a base-64 character? */
2149
2150#define IS_BASE64(c) \
2151 (((c) >= 'A' && (c) <= 'Z') || \
2152 ((c) >= 'a' && (c) <= 'z') || \
2153 ((c) >= '0' && (c) <= '9') || \
2154 (c) == '+' || (c) == '/')
2155
2156/* given that c is a base-64 character, what is its base-64 value? */
2157
2158#define FROM_BASE64(c) \
2159 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
2160 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
2161 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
2162 (c) == '+' ? 62 : 63)
2163
2164/* What is the base-64 character of the bottom 6 bits of n? */
2165
2166#define TO_BASE64(n) \
2167 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
2168
2169/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
2170 * decoded as itself. We are permissive on decoding; the only ASCII
2171 * byte not decoding to itself is the + which begins a base64
2172 * string. */
2173
2174#define DECODE_DIRECT(c) \
2175 ((c) <= 127 && (c) != '+')
2176
2177/* The UTF-7 encoder treats ASCII characters differently according to
2178 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
2179 * the above). See RFC2152. This array identifies these different
2180 * sets:
2181 * 0 : "Set D"
2182 * alphanumeric and '(),-./:?
2183 * 1 : "Set O"
2184 * !"#$%&*;<=>@[]^_`{|}
2185 * 2 : "whitespace"
2186 * ht nl cr sp
2187 * 3 : special (must be base64 encoded)
2188 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
2189 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002190
Tim Petersced69f82003-09-16 20:30:58 +00002191static
Antoine Pitrou244651a2009-05-04 18:56:13 +00002192char utf7_category[128] = {
2193/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
2194 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
2195/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
2196 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2197/* sp ! " # $ % & ' ( ) * + , - . / */
2198 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
2199/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
2200 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
2201/* @ A B C D E F G H I J K L M N O */
2202 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2203/* P Q R S T U V W X Y Z [ \ ] ^ _ */
2204 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
2205/* ` a b c d e f g h i j k l m n o */
2206 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2207/* p q r s t u v w x y z { | } ~ del */
2208 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002209};
2210
Antoine Pitrou244651a2009-05-04 18:56:13 +00002211/* ENCODE_DIRECT: this character should be encoded as itself. The
2212 * answer depends on whether we are encoding set O as itself, and also
2213 * on whether we are encoding whitespace as itself. RFC2152 makes it
2214 * clear that the answers to these questions vary between
2215 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00002216
Antoine Pitrou244651a2009-05-04 18:56:13 +00002217#define ENCODE_DIRECT(c, directO, directWS) \
2218 ((c) < 128 && (c) > 0 && \
2219 ((utf7_category[(c)] == 0) || \
2220 (directWS && (utf7_category[(c)] == 2)) || \
2221 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002222
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002223PyObject *PyUnicode_DecodeUTF7(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002224 Py_ssize_t size,
2225 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002226{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002227 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
2228}
2229
Antoine Pitrou244651a2009-05-04 18:56:13 +00002230/* The decoder. The only state we preserve is our read position,
2231 * i.e. how many characters we have consumed. So if we end in the
2232 * middle of a shift sequence we have to back off the read position
2233 * and the output to the beginning of the sequence, otherwise we lose
2234 * all the shift state (seen bits, number of bits seen, high
2235 * surrogate). */
2236
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002237PyObject *PyUnicode_DecodeUTF7Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002238 Py_ssize_t size,
2239 const char *errors,
2240 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002241{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002242 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002243 Py_ssize_t startinpos;
2244 Py_ssize_t endinpos;
2245 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002246 const char *e;
2247 PyUnicodeObject *unicode;
2248 Py_UNICODE *p;
2249 const char *errmsg = "";
2250 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002251 Py_UNICODE *shiftOutStart;
2252 unsigned int base64bits = 0;
2253 unsigned long base64buffer = 0;
2254 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002255 PyObject *errorHandler = NULL;
2256 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002257
2258 unicode = _PyUnicode_New(size);
2259 if (!unicode)
2260 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002261 if (size == 0) {
2262 if (consumed)
2263 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002264 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002265 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002266
2267 p = unicode->str;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002268 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002269 e = s + size;
2270
2271 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002272 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00002273 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00002274 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002275
Antoine Pitrou244651a2009-05-04 18:56:13 +00002276 if (inShift) { /* in a base-64 section */
2277 if (IS_BASE64(ch)) { /* consume a base-64 character */
2278 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
2279 base64bits += 6;
2280 s++;
2281 if (base64bits >= 16) {
2282 /* we have enough bits for a UTF-16 value */
2283 Py_UNICODE outCh = (Py_UNICODE)
2284 (base64buffer >> (base64bits-16));
2285 base64bits -= 16;
2286 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
2287 if (surrogate) {
2288 /* expecting a second surrogate */
2289 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
2290#ifdef Py_UNICODE_WIDE
2291 *p++ = (((surrogate & 0x3FF)<<10)
2292 | (outCh & 0x3FF)) + 0x10000;
2293#else
2294 *p++ = surrogate;
2295 *p++ = outCh;
2296#endif
2297 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01002298 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002299 }
2300 else {
Antoine Pitrou5418ee02011-11-15 01:42:21 +01002301 *p++ = surrogate;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002302 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002303 }
2304 }
Antoine Pitrou5418ee02011-11-15 01:42:21 +01002305 if (outCh >= 0xD800 && outCh <= 0xDBFF) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00002306 /* first surrogate */
2307 surrogate = outCh;
2308 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002309 else {
2310 *p++ = outCh;
2311 }
2312 }
2313 }
2314 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002315 inShift = 0;
2316 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002317 if (surrogate) {
Antoine Pitrou5418ee02011-11-15 01:42:21 +01002318 *p++ = surrogate;
2319 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002320 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002321 if (base64bits > 0) { /* left-over bits */
2322 if (base64bits >= 6) {
2323 /* We've seen at least one base-64 character */
2324 errmsg = "partial character in shift sequence";
2325 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002326 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002327 else {
2328 /* Some bits remain; they should be zero */
2329 if (base64buffer != 0) {
2330 errmsg = "non-zero padding bits in shift sequence";
2331 goto utf7Error;
2332 }
2333 }
2334 }
2335 if (ch != '-') {
2336 /* '-' is absorbed; other terminating
2337 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002338 *p++ = ch;
2339 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002340 }
2341 }
2342 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002343 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002344 s++; /* consume '+' */
2345 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002346 s++;
2347 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00002348 }
2349 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002350 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002351 shiftOutStart = p;
2352 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002353 }
2354 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002355 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002356 *p++ = ch;
2357 s++;
2358 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002359 else {
2360 startinpos = s-starts;
2361 s++;
2362 errmsg = "unexpected special character";
2363 goto utf7Error;
2364 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002365 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002366utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002367 outpos = p-PyUnicode_AS_UNICODE(unicode);
2368 endinpos = s-starts;
2369 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00002370 errors, &errorHandler,
2371 "utf7", errmsg,
2372 &starts, &e, &startinpos, &endinpos, &exc, &s,
2373 &unicode, &outpos, &p))
2374 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002375 }
2376
Antoine Pitrou244651a2009-05-04 18:56:13 +00002377 /* end of string */
2378
2379 if (inShift && !consumed) { /* in shift sequence, no more to follow */
2380 /* if we're in an inconsistent state, that's an error */
2381 if (surrogate ||
2382 (base64bits >= 6) ||
2383 (base64bits > 0 && base64buffer != 0)) {
2384 outpos = p-PyUnicode_AS_UNICODE(unicode);
2385 endinpos = size;
2386 if (unicode_decode_call_errorhandler(
2387 errors, &errorHandler,
2388 "utf7", "unterminated shift sequence",
2389 &starts, &e, &startinpos, &endinpos, &exc, &s,
2390 &unicode, &outpos, &p))
2391 goto onError;
2392 if (s < e)
2393 goto restart;
2394 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002395 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002396
2397 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002398 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00002399 if (inShift) {
2400 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002401 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002402 }
2403 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002404 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002405 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002406 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002407
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00002408 if (_PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002409 goto onError;
2410
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002411 Py_XDECREF(errorHandler);
2412 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002413 return (PyObject *)unicode;
2414
Benjamin Peterson29060642009-01-31 22:14:21 +00002415 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002416 Py_XDECREF(errorHandler);
2417 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002418 Py_DECREF(unicode);
2419 return NULL;
2420}
2421
2422
2423PyObject *PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002424 Py_ssize_t size,
Antoine Pitrou244651a2009-05-04 18:56:13 +00002425 int base64SetO,
2426 int base64WhiteSpace,
Benjamin Peterson29060642009-01-31 22:14:21 +00002427 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002428{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002429 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002430 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00002431 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002432 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002433 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002434 unsigned int base64bits = 0;
2435 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002436 char * out;
2437 char * start;
2438
2439 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00002440 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002441
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00002442 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00002443 return PyErr_NoMemory();
2444
Antoine Pitrou244651a2009-05-04 18:56:13 +00002445 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002446 if (v == NULL)
2447 return NULL;
2448
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002449 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002450 for (;i < size; ++i) {
2451 Py_UNICODE ch = s[i];
2452
Antoine Pitrou244651a2009-05-04 18:56:13 +00002453 if (inShift) {
2454 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
2455 /* shifting out */
2456 if (base64bits) { /* output remaining bits */
2457 *out++ = TO_BASE64(base64buffer << (6-base64bits));
2458 base64buffer = 0;
2459 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002460 }
2461 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002462 /* Characters not in the BASE64 set implicitly unshift the sequence
2463 so no '-' is required, except if the character is itself a '-' */
2464 if (IS_BASE64(ch) || ch == '-') {
2465 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002466 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002467 *out++ = (char) ch;
2468 }
2469 else {
2470 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00002471 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002472 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002473 else { /* not in a shift sequence */
2474 if (ch == '+') {
2475 *out++ = '+';
2476 *out++ = '-';
2477 }
2478 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
2479 *out++ = (char) ch;
2480 }
2481 else {
2482 *out++ = '+';
2483 inShift = 1;
2484 goto encode_char;
2485 }
2486 }
2487 continue;
2488encode_char:
2489#ifdef Py_UNICODE_WIDE
2490 if (ch >= 0x10000) {
2491 /* code first surrogate */
2492 base64bits += 16;
2493 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
2494 while (base64bits >= 6) {
2495 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
2496 base64bits -= 6;
2497 }
2498 /* prepare second surrogate */
2499 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
2500 }
2501#endif
2502 base64bits += 16;
2503 base64buffer = (base64buffer << 16) | ch;
2504 while (base64bits >= 6) {
2505 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
2506 base64bits -= 6;
2507 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00002508 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002509 if (base64bits)
2510 *out++= TO_BASE64(base64buffer << (6-base64bits) );
2511 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002512 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002513 if (_PyBytes_Resize(&v, out - start) < 0)
2514 return NULL;
2515 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002516}
2517
Antoine Pitrou244651a2009-05-04 18:56:13 +00002518#undef IS_BASE64
2519#undef FROM_BASE64
2520#undef TO_BASE64
2521#undef DECODE_DIRECT
2522#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002523
Guido van Rossumd57fd912000-03-10 22:53:23 +00002524/* --- UTF-8 Codec -------------------------------------------------------- */
2525
Tim Petersced69f82003-09-16 20:30:58 +00002526static
Guido van Rossumd57fd912000-03-10 22:53:23 +00002527char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00002528 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
2529 illegal prefix. See RFC 3629 for details */
2530 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
2531 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002532 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00002533 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2534 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2535 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2536 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00002537 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
2538 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 +00002539 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2540 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00002541 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
2542 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
2543 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
2544 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
2545 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 +00002546};
2547
Guido van Rossumd57fd912000-03-10 22:53:23 +00002548PyObject *PyUnicode_DecodeUTF8(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002549 Py_ssize_t size,
2550 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002551{
Walter Dörwald69652032004-09-07 20:24:22 +00002552 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
2553}
2554
Antoine Pitrouab868312009-01-10 15:40:25 +00002555/* Mask to check or force alignment of a pointer to C 'long' boundaries */
2556#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
2557
2558/* Mask to quickly check whether a C 'long' contains a
2559 non-ASCII, UTF8-encoded char. */
2560#if (SIZEOF_LONG == 8)
2561# define ASCII_CHAR_MASK 0x8080808080808080L
2562#elif (SIZEOF_LONG == 4)
2563# define ASCII_CHAR_MASK 0x80808080L
2564#else
2565# error C 'long' size should be either 4 or 8!
2566#endif
2567
Walter Dörwald69652032004-09-07 20:24:22 +00002568PyObject *PyUnicode_DecodeUTF8Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002569 Py_ssize_t size,
2570 const char *errors,
2571 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00002572{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002573 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002574 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00002575 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002576 Py_ssize_t startinpos;
2577 Py_ssize_t endinpos;
2578 Py_ssize_t outpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00002579 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002580 PyUnicodeObject *unicode;
2581 Py_UNICODE *p;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002582 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002583 PyObject *errorHandler = NULL;
2584 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002585
2586 /* Note: size will always be longer than the resulting Unicode
2587 character count */
2588 unicode = _PyUnicode_New(size);
2589 if (!unicode)
2590 return NULL;
Walter Dörwald69652032004-09-07 20:24:22 +00002591 if (size == 0) {
2592 if (consumed)
2593 *consumed = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002594 return (PyObject *)unicode;
Walter Dörwald69652032004-09-07 20:24:22 +00002595 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002596
2597 /* Unpack UTF-8 encoded data */
2598 p = unicode->str;
2599 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00002600 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002601
2602 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002603 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002604
2605 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00002606 /* Fast path for runs of ASCII characters. Given that common UTF-8
2607 input will consist of an overwhelming majority of ASCII
2608 characters, we try to optimize for this case by checking
2609 as many characters as a C 'long' can contain.
2610 First, check if we can do an aligned read, as most CPUs have
2611 a penalty for unaligned reads.
2612 */
2613 if (!((size_t) s & LONG_PTR_MASK)) {
2614 /* Help register allocation */
2615 register const char *_s = s;
2616 register Py_UNICODE *_p = p;
2617 while (_s < aligned_end) {
2618 /* Read a whole long at a time (either 4 or 8 bytes),
2619 and do a fast unrolled copy if it only contains ASCII
2620 characters. */
2621 unsigned long data = *(unsigned long *) _s;
2622 if (data & ASCII_CHAR_MASK)
2623 break;
2624 _p[0] = (unsigned char) _s[0];
2625 _p[1] = (unsigned char) _s[1];
2626 _p[2] = (unsigned char) _s[2];
2627 _p[3] = (unsigned char) _s[3];
2628#if (SIZEOF_LONG == 8)
2629 _p[4] = (unsigned char) _s[4];
2630 _p[5] = (unsigned char) _s[5];
2631 _p[6] = (unsigned char) _s[6];
2632 _p[7] = (unsigned char) _s[7];
2633#endif
2634 _s += SIZEOF_LONG;
2635 _p += SIZEOF_LONG;
2636 }
2637 s = _s;
2638 p = _p;
2639 if (s == e)
2640 break;
2641 ch = (unsigned char)*s;
2642 }
2643 }
2644
2645 if (ch < 0x80) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002646 *p++ = (Py_UNICODE)ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002647 s++;
2648 continue;
2649 }
2650
2651 n = utf8_code_length[ch];
2652
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002653 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002654 if (consumed)
2655 break;
2656 else {
2657 errmsg = "unexpected end of data";
2658 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002659 endinpos = startinpos+1;
2660 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
2661 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00002662 goto utf8Error;
2663 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002664 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002665
2666 switch (n) {
2667
2668 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00002669 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002670 startinpos = s-starts;
2671 endinpos = startinpos+1;
2672 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002673
2674 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002675 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00002676 startinpos = s-starts;
2677 endinpos = startinpos+1;
2678 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002679
2680 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002681 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00002682 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002683 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002684 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00002685 goto utf8Error;
2686 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002687 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00002688 assert ((ch > 0x007F) && (ch <= 0x07FF));
2689 *p++ = (Py_UNICODE)ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002690 break;
2691
2692 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00002693 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
2694 will result in surrogates in range d800-dfff. Surrogates are
2695 not valid UTF-8 so they are rejected.
2696 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
2697 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00002698 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00002699 (s[2] & 0xc0) != 0x80 ||
2700 ((unsigned char)s[0] == 0xE0 &&
2701 (unsigned char)s[1] < 0xA0) ||
2702 ((unsigned char)s[0] == 0xED &&
2703 (unsigned char)s[1] > 0x9F)) {
2704 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002705 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002706 endinpos = startinpos + 1;
2707
2708 /* if s[1] first two bits are 1 and 0, then the invalid
2709 continuation byte is s[2], so increment endinpos by 1,
2710 if not, s[1] is invalid and endinpos doesn't need to
2711 be incremented. */
2712 if ((s[1] & 0xC0) == 0x80)
2713 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00002714 goto utf8Error;
2715 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002716 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00002717 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
2718 *p++ = (Py_UNICODE)ch;
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002719 break;
2720
2721 case 4:
2722 if ((s[1] & 0xc0) != 0x80 ||
2723 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00002724 (s[3] & 0xc0) != 0x80 ||
2725 ((unsigned char)s[0] == 0xF0 &&
2726 (unsigned char)s[1] < 0x90) ||
2727 ((unsigned char)s[0] == 0xF4 &&
2728 (unsigned char)s[1] > 0x8F)) {
2729 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002730 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002731 endinpos = startinpos + 1;
2732 if ((s[1] & 0xC0) == 0x80) {
2733 endinpos++;
2734 if ((s[2] & 0xC0) == 0x80)
2735 endinpos++;
2736 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002737 goto utf8Error;
2738 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002739 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00002740 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
2741 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
2742
Fredrik Lundh8f455852001-06-27 18:59:43 +00002743#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00002744 *p++ = (Py_UNICODE)ch;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002745#else
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002746 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00002747
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002748 /* translate from 10000..10FFFF to 0..FFFF */
2749 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00002750
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002751 /* high surrogate = top 10 bits added to D800 */
2752 *p++ = (Py_UNICODE)(0xD800 + (ch >> 10));
Tim Petersced69f82003-09-16 20:30:58 +00002753
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002754 /* low surrogate = bottom 10 bits added to DC00 */
Fredrik Lundh45714e92001-06-26 16:39:36 +00002755 *p++ = (Py_UNICODE)(0xDC00 + (ch & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002756#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00002757 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002758 }
2759 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00002760 continue;
Tim Petersced69f82003-09-16 20:30:58 +00002761
Benjamin Peterson29060642009-01-31 22:14:21 +00002762 utf8Error:
2763 outpos = p-PyUnicode_AS_UNICODE(unicode);
2764 if (unicode_decode_call_errorhandler(
2765 errors, &errorHandler,
Victor Stinnercbe01342012-02-14 01:17:45 +01002766 "utf-8", errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00002767 &starts, &e, &startinpos, &endinpos, &exc, &s,
2768 &unicode, &outpos, &p))
2769 goto onError;
2770 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002771 }
Walter Dörwald69652032004-09-07 20:24:22 +00002772 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00002773 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002774
2775 /* Adjust length */
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00002776 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002777 goto onError;
2778
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002779 Py_XDECREF(errorHandler);
2780 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002781 return (PyObject *)unicode;
2782
Benjamin Peterson29060642009-01-31 22:14:21 +00002783 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002784 Py_XDECREF(errorHandler);
2785 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002786 Py_DECREF(unicode);
2787 return NULL;
2788}
2789
Antoine Pitrouab868312009-01-10 15:40:25 +00002790#undef ASCII_CHAR_MASK
2791
Victor Stinnerf933e1a2010-10-20 22:58:25 +00002792#ifdef __APPLE__
2793
2794/* Simplified UTF-8 decoder using surrogateescape error handler,
2795 used to decode the command line arguments on Mac OS X. */
2796
2797wchar_t*
2798_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
2799{
2800 int n;
2801 const char *e;
2802 wchar_t *unicode, *p;
2803
2804 /* Note: size will always be longer than the resulting Unicode
2805 character count */
2806 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
2807 PyErr_NoMemory();
2808 return NULL;
2809 }
2810 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
2811 if (!unicode)
2812 return NULL;
2813
2814 /* Unpack UTF-8 encoded data */
2815 p = unicode;
2816 e = s + size;
2817 while (s < e) {
2818 Py_UCS4 ch = (unsigned char)*s;
2819
2820 if (ch < 0x80) {
2821 *p++ = (wchar_t)ch;
2822 s++;
2823 continue;
2824 }
2825
2826 n = utf8_code_length[ch];
2827 if (s + n > e) {
2828 goto surrogateescape;
2829 }
2830
2831 switch (n) {
2832 case 0:
2833 case 1:
2834 goto surrogateescape;
2835
2836 case 2:
2837 if ((s[1] & 0xc0) != 0x80)
2838 goto surrogateescape;
2839 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
2840 assert ((ch > 0x007F) && (ch <= 0x07FF));
2841 *p++ = (wchar_t)ch;
2842 break;
2843
2844 case 3:
2845 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
2846 will result in surrogates in range d800-dfff. Surrogates are
2847 not valid UTF-8 so they are rejected.
2848 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
2849 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
2850 if ((s[1] & 0xc0) != 0x80 ||
2851 (s[2] & 0xc0) != 0x80 ||
2852 ((unsigned char)s[0] == 0xE0 &&
2853 (unsigned char)s[1] < 0xA0) ||
2854 ((unsigned char)s[0] == 0xED &&
2855 (unsigned char)s[1] > 0x9F)) {
2856
2857 goto surrogateescape;
2858 }
2859 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
2860 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
2861 *p++ = (Py_UNICODE)ch;
2862 break;
2863
2864 case 4:
2865 if ((s[1] & 0xc0) != 0x80 ||
2866 (s[2] & 0xc0) != 0x80 ||
2867 (s[3] & 0xc0) != 0x80 ||
2868 ((unsigned char)s[0] == 0xF0 &&
2869 (unsigned char)s[1] < 0x90) ||
2870 ((unsigned char)s[0] == 0xF4 &&
2871 (unsigned char)s[1] > 0x8F)) {
2872 goto surrogateescape;
2873 }
2874 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
2875 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
2876 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
2877
2878#if SIZEOF_WCHAR_T == 4
2879 *p++ = (wchar_t)ch;
2880#else
2881 /* compute and append the two surrogates: */
2882
2883 /* translate from 10000..10FFFF to 0..FFFF */
2884 ch -= 0x10000;
2885
2886 /* high surrogate = top 10 bits added to D800 */
2887 *p++ = (wchar_t)(0xD800 + (ch >> 10));
2888
2889 /* low surrogate = bottom 10 bits added to DC00 */
2890 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
2891#endif
2892 break;
2893 }
2894 s += n;
2895 continue;
2896
2897 surrogateescape:
2898 *p++ = 0xDC00 + ch;
2899 s++;
2900 }
2901 *p = L'\0';
2902 return unicode;
2903}
2904
2905#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00002906
Tim Peters602f7402002-04-27 18:03:26 +00002907/* Allocation strategy: if the string is short, convert into a stack buffer
2908 and allocate exactly as much space needed at the end. Else allocate the
2909 maximum possible needed (4 result bytes per Unicode character), and return
2910 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002911*/
Tim Peters7e3d9612002-04-21 03:26:37 +00002912PyObject *
2913PyUnicode_EncodeUTF8(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002914 Py_ssize_t size,
2915 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002916{
Tim Peters602f7402002-04-27 18:03:26 +00002917#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00002918
Guido van Rossum98297ee2007-11-06 21:34:58 +00002919 Py_ssize_t i; /* index into s of next input byte */
2920 PyObject *result; /* result string object */
2921 char *p; /* next free byte in output buffer */
2922 Py_ssize_t nallocated; /* number of result bytes allocated */
2923 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00002924 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002925 PyObject *errorHandler = NULL;
2926 PyObject *exc = NULL;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00002927
Tim Peters602f7402002-04-27 18:03:26 +00002928 assert(s != NULL);
2929 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002930
Tim Peters602f7402002-04-27 18:03:26 +00002931 if (size <= MAX_SHORT_UNICHARS) {
2932 /* Write into the stack buffer; nallocated can't overflow.
2933 * At the end, we'll allocate exactly as much heap space as it
2934 * turns out we need.
2935 */
2936 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002937 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00002938 p = stackbuf;
2939 }
2940 else {
2941 /* Overallocate on the heap, and give the excess back at the end. */
2942 nallocated = size * 4;
2943 if (nallocated / 4 != size) /* overflow! */
2944 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00002945 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002946 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00002947 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00002948 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00002949 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002950
Tim Peters602f7402002-04-27 18:03:26 +00002951 for (i = 0; i < size;) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002952 Py_UCS4 ch = s[i++];
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002953
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002954 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00002955 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002956 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002957
Guido van Rossumd57fd912000-03-10 22:53:23 +00002958 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00002959 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00002960 *p++ = (char)(0xc0 | (ch >> 6));
2961 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00002962 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002963#ifndef Py_UNICODE_WIDE
Victor Stinner31be90b2010-04-22 19:38:16 +00002964 /* Special case: check for high and low surrogate */
2965 if (ch <= 0xDBFF && i != size && 0xDC00 <= s[i] && s[i] <= 0xDFFF) {
2966 Py_UCS4 ch2 = s[i];
2967 /* Combine the two surrogates to form a UCS4 value */
2968 ch = ((ch - 0xD800) << 10 | (ch2 - 0xDC00)) + 0x10000;
2969 i++;
2970
2971 /* Encode UCS4 Unicode ordinals */
2972 *p++ = (char)(0xf0 | (ch >> 18));
2973 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
Tim Peters602f7402002-04-27 18:03:26 +00002974 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2975 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00002976 } else {
Victor Stinner445a6232010-04-22 20:01:57 +00002977#endif
Victor Stinner31be90b2010-04-22 19:38:16 +00002978 Py_ssize_t newpos;
2979 PyObject *rep;
2980 Py_ssize_t repsize, k;
2981 rep = unicode_encode_call_errorhandler
2982 (errors, &errorHandler, "utf-8", "surrogates not allowed",
2983 s, size, &exc, i-1, i, &newpos);
2984 if (!rep)
2985 goto error;
2986
2987 if (PyBytes_Check(rep))
2988 repsize = PyBytes_GET_SIZE(rep);
2989 else
2990 repsize = PyUnicode_GET_SIZE(rep);
2991
2992 if (repsize > 4) {
2993 Py_ssize_t offset;
2994
2995 if (result == NULL)
2996 offset = p - stackbuf;
2997 else
2998 offset = p - PyBytes_AS_STRING(result);
2999
3000 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
3001 /* integer overflow */
3002 PyErr_NoMemory();
3003 goto error;
3004 }
3005 nallocated += repsize - 4;
3006 if (result != NULL) {
3007 if (_PyBytes_Resize(&result, nallocated) < 0)
3008 goto error;
3009 } else {
3010 result = PyBytes_FromStringAndSize(NULL, nallocated);
3011 if (result == NULL)
3012 goto error;
3013 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
3014 }
3015 p = PyBytes_AS_STRING(result) + offset;
3016 }
3017
3018 if (PyBytes_Check(rep)) {
3019 char *prep = PyBytes_AS_STRING(rep);
3020 for(k = repsize; k > 0; k--)
3021 *p++ = *prep++;
3022 } else /* rep is unicode */ {
3023 Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
3024 Py_UNICODE c;
3025
3026 for(k=0; k<repsize; k++) {
3027 c = prep[k];
3028 if (0x80 <= c) {
3029 raise_encode_exception(&exc, "utf-8", s, size,
3030 i-1, i, "surrogates not allowed");
3031 goto error;
3032 }
3033 *p++ = (char)prep[k];
3034 }
3035 }
3036 Py_DECREF(rep);
Victor Stinner445a6232010-04-22 20:01:57 +00003037#ifndef Py_UNICODE_WIDE
Victor Stinner31be90b2010-04-22 19:38:16 +00003038 }
Victor Stinner445a6232010-04-22 20:01:57 +00003039#endif
Victor Stinner31be90b2010-04-22 19:38:16 +00003040 } else if (ch < 0x10000) {
3041 *p++ = (char)(0xe0 | (ch >> 12));
3042 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
3043 *p++ = (char)(0x80 | (ch & 0x3f));
3044 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00003045 /* Encode UCS4 Unicode ordinals */
3046 *p++ = (char)(0xf0 | (ch >> 18));
3047 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
3048 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
3049 *p++ = (char)(0x80 | (ch & 0x3f));
3050 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003051 }
Tim Peters0eca65c2002-04-21 17:28:06 +00003052
Guido van Rossum98297ee2007-11-06 21:34:58 +00003053 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00003054 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003055 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00003056 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00003057 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00003058 }
3059 else {
Christian Heimesf3863112007-11-22 07:46:41 +00003060 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00003061 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00003062 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00003063 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00003064 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00003065 Py_XDECREF(errorHandler);
3066 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003067 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00003068 error:
3069 Py_XDECREF(errorHandler);
3070 Py_XDECREF(exc);
3071 Py_XDECREF(result);
3072 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00003073
Tim Peters602f7402002-04-27 18:03:26 +00003074#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00003075}
3076
Guido van Rossumd57fd912000-03-10 22:53:23 +00003077PyObject *PyUnicode_AsUTF8String(PyObject *unicode)
3078{
Guido van Rossumd57fd912000-03-10 22:53:23 +00003079 if (!PyUnicode_Check(unicode)) {
3080 PyErr_BadArgument();
3081 return NULL;
3082 }
Barry Warsaw2dd4abf2000-08-18 06:58:15 +00003083 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003084 PyUnicode_GET_SIZE(unicode),
3085 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003086}
3087
Walter Dörwald41980ca2007-08-16 21:55:45 +00003088/* --- UTF-32 Codec ------------------------------------------------------- */
3089
3090PyObject *
3091PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003092 Py_ssize_t size,
3093 const char *errors,
3094 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00003095{
3096 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
3097}
3098
3099PyObject *
3100PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003101 Py_ssize_t size,
3102 const char *errors,
3103 int *byteorder,
3104 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00003105{
3106 const char *starts = s;
3107 Py_ssize_t startinpos;
3108 Py_ssize_t endinpos;
3109 Py_ssize_t outpos;
3110 PyUnicodeObject *unicode;
3111 Py_UNICODE *p;
3112#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00003113 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00003114 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003115#else
3116 const int pairs = 0;
3117#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00003118 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003119 int bo = 0; /* assume native ordering by default */
3120 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00003121 /* Offsets from q for retrieving bytes in the right order. */
3122#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3123 int iorder[] = {0, 1, 2, 3};
3124#else
3125 int iorder[] = {3, 2, 1, 0};
3126#endif
3127 PyObject *errorHandler = NULL;
3128 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00003129
Walter Dörwald41980ca2007-08-16 21:55:45 +00003130 q = (unsigned char *)s;
3131 e = q + size;
3132
3133 if (byteorder)
3134 bo = *byteorder;
3135
3136 /* Check for BOM marks (U+FEFF) in the input and adjust current
3137 byte order setting accordingly. In native mode, the leading BOM
3138 mark is skipped, in all other modes, it is copied to the output
3139 stream as-is (giving a ZWNBSP character). */
3140 if (bo == 0) {
3141 if (size >= 4) {
3142 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00003143 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00003144#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00003145 if (bom == 0x0000FEFF) {
3146 q += 4;
3147 bo = -1;
3148 }
3149 else if (bom == 0xFFFE0000) {
3150 q += 4;
3151 bo = 1;
3152 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003153#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003154 if (bom == 0x0000FEFF) {
3155 q += 4;
3156 bo = 1;
3157 }
3158 else if (bom == 0xFFFE0000) {
3159 q += 4;
3160 bo = -1;
3161 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003162#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003163 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003164 }
3165
3166 if (bo == -1) {
3167 /* force LE */
3168 iorder[0] = 0;
3169 iorder[1] = 1;
3170 iorder[2] = 2;
3171 iorder[3] = 3;
3172 }
3173 else if (bo == 1) {
3174 /* force BE */
3175 iorder[0] = 3;
3176 iorder[1] = 2;
3177 iorder[2] = 1;
3178 iorder[3] = 0;
3179 }
3180
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00003181 /* On narrow builds we split characters outside the BMP into two
3182 codepoints => count how much extra space we need. */
3183#ifndef Py_UNICODE_WIDE
3184 for (qq = q; qq < e; qq += 4)
3185 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
3186 pairs++;
3187#endif
3188
3189 /* This might be one to much, because of a BOM */
3190 unicode = _PyUnicode_New((size+3)/4+pairs);
3191 if (!unicode)
3192 return NULL;
3193 if (size == 0)
3194 return (PyObject *)unicode;
3195
3196 /* Unpack UTF-32 encoded data */
3197 p = unicode->str;
3198
Walter Dörwald41980ca2007-08-16 21:55:45 +00003199 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003200 Py_UCS4 ch;
3201 /* remaining bytes at the end? (size should be divisible by 4) */
3202 if (e-q<4) {
3203 if (consumed)
3204 break;
3205 errmsg = "truncated data";
3206 startinpos = ((const char *)q)-starts;
3207 endinpos = ((const char *)e)-starts;
3208 goto utf32Error;
3209 /* The remaining input chars are ignored if the callback
3210 chooses to skip the input */
3211 }
3212 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
3213 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00003214
Benjamin Peterson29060642009-01-31 22:14:21 +00003215 if (ch >= 0x110000)
3216 {
3217 errmsg = "codepoint not in range(0x110000)";
3218 startinpos = ((const char *)q)-starts;
3219 endinpos = startinpos+4;
3220 goto utf32Error;
3221 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003222#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003223 if (ch >= 0x10000)
3224 {
3225 *p++ = 0xD800 | ((ch-0x10000) >> 10);
3226 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
3227 }
3228 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00003229#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003230 *p++ = ch;
3231 q += 4;
3232 continue;
3233 utf32Error:
3234 outpos = p-PyUnicode_AS_UNICODE(unicode);
3235 if (unicode_decode_call_errorhandler(
3236 errors, &errorHandler,
3237 "utf32", errmsg,
3238 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
3239 &unicode, &outpos, &p))
3240 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003241 }
3242
3243 if (byteorder)
3244 *byteorder = bo;
3245
3246 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00003247 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003248
3249 /* Adjust length */
3250 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
3251 goto onError;
3252
3253 Py_XDECREF(errorHandler);
3254 Py_XDECREF(exc);
3255 return (PyObject *)unicode;
3256
Benjamin Peterson29060642009-01-31 22:14:21 +00003257 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00003258 Py_DECREF(unicode);
3259 Py_XDECREF(errorHandler);
3260 Py_XDECREF(exc);
3261 return NULL;
3262}
3263
3264PyObject *
3265PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003266 Py_ssize_t size,
3267 const char *errors,
3268 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00003269{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003270 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003271 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003272 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003273#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003274 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003275#else
3276 const int pairs = 0;
3277#endif
3278 /* Offsets from p for storing byte pairs in the right order. */
3279#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3280 int iorder[] = {0, 1, 2, 3};
3281#else
3282 int iorder[] = {3, 2, 1, 0};
3283#endif
3284
Benjamin Peterson29060642009-01-31 22:14:21 +00003285#define STORECHAR(CH) \
3286 do { \
3287 p[iorder[3]] = ((CH) >> 24) & 0xff; \
3288 p[iorder[2]] = ((CH) >> 16) & 0xff; \
3289 p[iorder[1]] = ((CH) >> 8) & 0xff; \
3290 p[iorder[0]] = (CH) & 0xff; \
3291 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00003292 } while(0)
3293
3294 /* In narrow builds we can output surrogate pairs as one codepoint,
3295 so we need less space. */
3296#ifndef Py_UNICODE_WIDE
3297 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00003298 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
3299 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
3300 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003301#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003302 nsize = (size - pairs + (byteorder == 0));
3303 bytesize = nsize * 4;
3304 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003305 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003306 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003307 if (v == NULL)
3308 return NULL;
3309
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003310 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003311 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003312 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003313 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00003314 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003315
3316 if (byteorder == -1) {
3317 /* force LE */
3318 iorder[0] = 0;
3319 iorder[1] = 1;
3320 iorder[2] = 2;
3321 iorder[3] = 3;
3322 }
3323 else if (byteorder == 1) {
3324 /* force BE */
3325 iorder[0] = 3;
3326 iorder[1] = 2;
3327 iorder[2] = 1;
3328 iorder[3] = 0;
3329 }
3330
3331 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003332 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003333#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003334 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
3335 Py_UCS4 ch2 = *s;
3336 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
3337 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
3338 s++;
3339 size--;
3340 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00003341 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003342#endif
3343 STORECHAR(ch);
3344 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003345
3346 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003347 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003348#undef STORECHAR
3349}
3350
3351PyObject *PyUnicode_AsUTF32String(PyObject *unicode)
3352{
3353 if (!PyUnicode_Check(unicode)) {
3354 PyErr_BadArgument();
3355 return NULL;
3356 }
3357 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003358 PyUnicode_GET_SIZE(unicode),
3359 NULL,
3360 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003361}
3362
Guido van Rossumd57fd912000-03-10 22:53:23 +00003363/* --- UTF-16 Codec ------------------------------------------------------- */
3364
Tim Peters772747b2001-08-09 22:21:55 +00003365PyObject *
3366PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003367 Py_ssize_t size,
3368 const char *errors,
3369 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003370{
Walter Dörwald69652032004-09-07 20:24:22 +00003371 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
3372}
3373
Antoine Pitrouab868312009-01-10 15:40:25 +00003374/* Two masks for fast checking of whether a C 'long' may contain
3375 UTF16-encoded surrogate characters. This is an efficient heuristic,
3376 assuming that non-surrogate characters with a code point >= 0x8000 are
3377 rare in most input.
3378 FAST_CHAR_MASK is used when the input is in native byte ordering,
3379 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00003380*/
Antoine Pitrouab868312009-01-10 15:40:25 +00003381#if (SIZEOF_LONG == 8)
3382# define FAST_CHAR_MASK 0x8000800080008000L
3383# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
3384#elif (SIZEOF_LONG == 4)
3385# define FAST_CHAR_MASK 0x80008000L
3386# define SWAPPED_FAST_CHAR_MASK 0x00800080L
3387#else
3388# error C 'long' size should be either 4 or 8!
3389#endif
3390
Walter Dörwald69652032004-09-07 20:24:22 +00003391PyObject *
3392PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003393 Py_ssize_t size,
3394 const char *errors,
3395 int *byteorder,
3396 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00003397{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003398 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003399 Py_ssize_t startinpos;
3400 Py_ssize_t endinpos;
3401 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003402 PyUnicodeObject *unicode;
3403 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00003404 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00003405 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00003406 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003407 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00003408 /* Offsets from q for retrieving byte pairs in the right order. */
3409#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3410 int ihi = 1, ilo = 0;
3411#else
3412 int ihi = 0, ilo = 1;
3413#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003414 PyObject *errorHandler = NULL;
3415 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003416
3417 /* Note: size will always be longer than the resulting Unicode
3418 character count */
3419 unicode = _PyUnicode_New(size);
3420 if (!unicode)
3421 return NULL;
3422 if (size == 0)
3423 return (PyObject *)unicode;
3424
3425 /* Unpack UTF-16 encoded data */
3426 p = unicode->str;
Tim Peters772747b2001-08-09 22:21:55 +00003427 q = (unsigned char *)s;
Antoine Pitroub4bbee22012-07-21 00:45:14 +02003428 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003429
3430 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00003431 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003432
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003433 /* Check for BOM marks (U+FEFF) in the input and adjust current
3434 byte order setting accordingly. In native mode, the leading BOM
3435 mark is skipped, in all other modes, it is copied to the output
3436 stream as-is (giving a ZWNBSP character). */
3437 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00003438 if (size >= 2) {
3439 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003440#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00003441 if (bom == 0xFEFF) {
3442 q += 2;
3443 bo = -1;
3444 }
3445 else if (bom == 0xFFFE) {
3446 q += 2;
3447 bo = 1;
3448 }
Tim Petersced69f82003-09-16 20:30:58 +00003449#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003450 if (bom == 0xFEFF) {
3451 q += 2;
3452 bo = 1;
3453 }
3454 else if (bom == 0xFFFE) {
3455 q += 2;
3456 bo = -1;
3457 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003458#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003459 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003460 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003461
Tim Peters772747b2001-08-09 22:21:55 +00003462 if (bo == -1) {
3463 /* force LE */
3464 ihi = 1;
3465 ilo = 0;
3466 }
3467 else if (bo == 1) {
3468 /* force BE */
3469 ihi = 0;
3470 ilo = 1;
3471 }
Antoine Pitrouab868312009-01-10 15:40:25 +00003472#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3473 native_ordering = ilo < ihi;
3474#else
3475 native_ordering = ilo > ihi;
3476#endif
Tim Peters772747b2001-08-09 22:21:55 +00003477
Antoine Pitrouab868312009-01-10 15:40:25 +00003478 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Antoine Pitroub4bbee22012-07-21 00:45:14 +02003479 while (1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003480 Py_UNICODE ch;
Antoine Pitroub4bbee22012-07-21 00:45:14 +02003481 if (e - q < 2) {
3482 /* remaining byte at the end? (size should be even) */
3483 if (q == e || consumed)
3484 break;
3485 errmsg = "truncated data";
3486 startinpos = ((const char *)q) - starts;
3487 endinpos = ((const char *)e) - starts;
3488 outpos = p - PyUnicode_AS_UNICODE(unicode);
3489 goto utf16Error;
3490 /* The remaining input chars are ignored if the callback
3491 chooses to skip the input */
3492 }
Antoine Pitrouab868312009-01-10 15:40:25 +00003493 /* First check for possible aligned read of a C 'long'. Unaligned
3494 reads are more expensive, better to defer to another iteration. */
3495 if (!((size_t) q & LONG_PTR_MASK)) {
3496 /* Fast path for runs of non-surrogate chars. */
3497 register const unsigned char *_q = q;
3498 Py_UNICODE *_p = p;
3499 if (native_ordering) {
3500 /* Native ordering is simple: as long as the input cannot
3501 possibly contain a surrogate char, do an unrolled copy
3502 of several 16-bit code points to the target object.
3503 The non-surrogate check is done on several input bytes
3504 at a time (as many as a C 'long' can contain). */
3505 while (_q < aligned_end) {
3506 unsigned long data = * (unsigned long *) _q;
3507 if (data & FAST_CHAR_MASK)
3508 break;
3509 _p[0] = ((unsigned short *) _q)[0];
3510 _p[1] = ((unsigned short *) _q)[1];
3511#if (SIZEOF_LONG == 8)
3512 _p[2] = ((unsigned short *) _q)[2];
3513 _p[3] = ((unsigned short *) _q)[3];
3514#endif
3515 _q += SIZEOF_LONG;
3516 _p += SIZEOF_LONG / 2;
3517 }
3518 }
3519 else {
3520 /* Byteswapped ordering is similar, but we must decompose
3521 the copy bytewise, and take care of zero'ing out the
3522 upper bytes if the target object is in 32-bit units
3523 (that is, in UCS-4 builds). */
3524 while (_q < aligned_end) {
3525 unsigned long data = * (unsigned long *) _q;
3526 if (data & SWAPPED_FAST_CHAR_MASK)
3527 break;
3528 /* Zero upper bytes in UCS-4 builds */
3529#if (Py_UNICODE_SIZE > 2)
3530 _p[0] = 0;
3531 _p[1] = 0;
3532#if (SIZEOF_LONG == 8)
3533 _p[2] = 0;
3534 _p[3] = 0;
3535#endif
3536#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00003537 /* Issue #4916; UCS-4 builds on big endian machines must
3538 fill the two last bytes of each 4-byte unit. */
3539#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
3540# define OFF 2
3541#else
3542# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00003543#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00003544 ((unsigned char *) _p)[OFF + 1] = _q[0];
3545 ((unsigned char *) _p)[OFF + 0] = _q[1];
3546 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
3547 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
3548#if (SIZEOF_LONG == 8)
3549 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
3550 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
3551 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
3552 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
3553#endif
3554#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00003555 _q += SIZEOF_LONG;
3556 _p += SIZEOF_LONG / 2;
3557 }
3558 }
3559 p = _p;
3560 q = _q;
Antoine Pitroub4bbee22012-07-21 00:45:14 +02003561 if (e - q < 2)
3562 continue;
Antoine Pitrouab868312009-01-10 15:40:25 +00003563 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003564 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003565
Benjamin Peterson14339b62009-01-31 16:36:08 +00003566 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00003567
3568 if (ch < 0xD800 || ch > 0xDFFF) {
3569 *p++ = ch;
3570 continue;
3571 }
3572
3573 /* UTF-16 code pair: */
Antoine Pitroub4bbee22012-07-21 00:45:14 +02003574 if (e - q < 2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003575 errmsg = "unexpected end of data";
3576 startinpos = (((const char *)q) - 2) - starts;
Antoine Pitroub4bbee22012-07-21 00:45:14 +02003577 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00003578 goto utf16Error;
3579 }
3580 if (0xD800 <= ch && ch <= 0xDBFF) {
3581 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
3582 q += 2;
3583 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00003584#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003585 *p++ = ch;
3586 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003587#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003588 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003589#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003590 continue;
3591 }
3592 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003593 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00003594 startinpos = (((const char *)q)-4)-starts;
3595 endinpos = startinpos+2;
3596 goto utf16Error;
3597 }
3598
Benjamin Peterson14339b62009-01-31 16:36:08 +00003599 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003600 errmsg = "illegal encoding";
3601 startinpos = (((const char *)q)-2)-starts;
3602 endinpos = startinpos+2;
3603 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003604
Benjamin Peterson29060642009-01-31 22:14:21 +00003605 utf16Error:
3606 outpos = p - PyUnicode_AS_UNICODE(unicode);
3607 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00003608 errors,
3609 &errorHandler,
3610 "utf16", errmsg,
3611 &starts,
3612 (const char **)&e,
3613 &startinpos,
3614 &endinpos,
3615 &exc,
3616 (const char **)&q,
3617 &unicode,
3618 &outpos,
3619 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00003620 goto onError;
Antoine Pitroub4bbee22012-07-21 00:45:14 +02003621 /* Update data because unicode_decode_call_errorhandler might have
3622 changed the input object. */
3623 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Antoine Pitrouab868312009-01-10 15:40:25 +00003624 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003625
3626 if (byteorder)
3627 *byteorder = bo;
3628
Walter Dörwald69652032004-09-07 20:24:22 +00003629 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00003630 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00003631
Guido van Rossumd57fd912000-03-10 22:53:23 +00003632 /* Adjust length */
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00003633 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003634 goto onError;
3635
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003636 Py_XDECREF(errorHandler);
3637 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003638 return (PyObject *)unicode;
3639
Benjamin Peterson29060642009-01-31 22:14:21 +00003640 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003641 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003642 Py_XDECREF(errorHandler);
3643 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003644 return NULL;
3645}
3646
Antoine Pitrouab868312009-01-10 15:40:25 +00003647#undef FAST_CHAR_MASK
3648#undef SWAPPED_FAST_CHAR_MASK
3649
Tim Peters772747b2001-08-09 22:21:55 +00003650PyObject *
3651PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003652 Py_ssize_t size,
3653 const char *errors,
3654 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003655{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003656 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00003657 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003658 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003659#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003660 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003661#else
3662 const int pairs = 0;
3663#endif
Tim Peters772747b2001-08-09 22:21:55 +00003664 /* Offsets from p for storing byte pairs in the right order. */
3665#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3666 int ihi = 1, ilo = 0;
3667#else
3668 int ihi = 0, ilo = 1;
3669#endif
3670
Benjamin Peterson29060642009-01-31 22:14:21 +00003671#define STORECHAR(CH) \
3672 do { \
3673 p[ihi] = ((CH) >> 8) & 0xff; \
3674 p[ilo] = (CH) & 0xff; \
3675 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00003676 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003677
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003678#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003679 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00003680 if (s[i] >= 0x10000)
3681 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003682#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003683 /* 2 * (size + pairs + (byteorder == 0)) */
3684 if (size > PY_SSIZE_T_MAX ||
3685 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00003686 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003687 nsize = size + pairs + (byteorder == 0);
3688 bytesize = nsize * 2;
3689 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003690 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003691 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003692 if (v == NULL)
3693 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003694
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003695 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003696 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003697 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00003698 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00003699 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00003700
3701 if (byteorder == -1) {
3702 /* force LE */
3703 ihi = 1;
3704 ilo = 0;
3705 }
3706 else if (byteorder == 1) {
3707 /* force BE */
3708 ihi = 0;
3709 ilo = 1;
3710 }
3711
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003712 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003713 Py_UNICODE ch = *s++;
3714 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003715#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003716 if (ch >= 0x10000) {
3717 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
3718 ch = 0xD800 | ((ch-0x10000) >> 10);
3719 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003720#endif
Tim Peters772747b2001-08-09 22:21:55 +00003721 STORECHAR(ch);
3722 if (ch2)
3723 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003724 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003725
3726 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003727 return v;
Tim Peters772747b2001-08-09 22:21:55 +00003728#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00003729}
3730
3731PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
3732{
3733 if (!PyUnicode_Check(unicode)) {
3734 PyErr_BadArgument();
3735 return NULL;
3736 }
3737 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003738 PyUnicode_GET_SIZE(unicode),
3739 NULL,
3740 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003741}
3742
3743/* --- Unicode Escape Codec ----------------------------------------------- */
3744
Fredrik Lundh06d12682001-01-24 07:59:11 +00003745static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00003746
Guido van Rossumd57fd912000-03-10 22:53:23 +00003747PyObject *PyUnicode_DecodeUnicodeEscape(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003748 Py_ssize_t size,
3749 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003750{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003751 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003752 Py_ssize_t startinpos;
3753 Py_ssize_t endinpos;
3754 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003755 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003756 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003757 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003758 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003759 char* message;
3760 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003761 PyObject *errorHandler = NULL;
3762 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003763
Guido van Rossumd57fd912000-03-10 22:53:23 +00003764 /* Escaped strings will always be longer than the resulting
3765 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003766 length after conversion to the true value.
3767 (but if the error callback returns a long replacement string
3768 we'll have to allocate more space) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003769 v = _PyUnicode_New(size);
3770 if (v == NULL)
3771 goto onError;
3772 if (size == 0)
3773 return (PyObject *)v;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003774
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003775 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003776 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003777
Guido van Rossumd57fd912000-03-10 22:53:23 +00003778 while (s < end) {
3779 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00003780 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003781 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003782
3783 /* Non-escape characters are interpreted as Unicode ordinals */
3784 if (*s != '\\') {
Fredrik Lundhccc74732001-02-18 22:13:49 +00003785 *p++ = (unsigned char) *s++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003786 continue;
3787 }
3788
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003789 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003790 /* \ - Escapes */
3791 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003792 c = *s++;
3793 if (s > end)
3794 c = '\0'; /* Invalid after \ */
3795 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003796
Benjamin Peterson29060642009-01-31 22:14:21 +00003797 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003798 case '\n': break;
3799 case '\\': *p++ = '\\'; break;
3800 case '\'': *p++ = '\''; break;
3801 case '\"': *p++ = '\"'; break;
3802 case 'b': *p++ = '\b'; break;
3803 case 'f': *p++ = '\014'; break; /* FF */
3804 case 't': *p++ = '\t'; break;
3805 case 'n': *p++ = '\n'; break;
3806 case 'r': *p++ = '\r'; break;
3807 case 'v': *p++ = '\013'; break; /* VT */
3808 case 'a': *p++ = '\007'; break; /* BEL, not classic C */
3809
Benjamin Peterson29060642009-01-31 22:14:21 +00003810 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003811 case '0': case '1': case '2': case '3':
3812 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003813 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003814 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003815 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003816 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003817 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00003818 }
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003819 *p++ = x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003820 break;
3821
Benjamin Peterson29060642009-01-31 22:14:21 +00003822 /* hex escapes */
3823 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003824 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003825 digits = 2;
3826 message = "truncated \\xXX escape";
3827 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003828
Benjamin Peterson29060642009-01-31 22:14:21 +00003829 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003830 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003831 digits = 4;
3832 message = "truncated \\uXXXX escape";
3833 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003834
Benjamin Peterson29060642009-01-31 22:14:21 +00003835 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00003836 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003837 digits = 8;
3838 message = "truncated \\UXXXXXXXX escape";
3839 hexescape:
3840 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003841 outpos = p-PyUnicode_AS_UNICODE(v);
3842 if (s+digits>end) {
3843 endinpos = size;
3844 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003845 errors, &errorHandler,
3846 "unicodeescape", "end of string in escape sequence",
3847 &starts, &end, &startinpos, &endinpos, &exc, &s,
3848 &v, &outpos, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003849 goto onError;
3850 goto nextByte;
3851 }
3852 for (i = 0; i < digits; ++i) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00003853 c = (unsigned char) s[i];
David Malcolm96960882010-11-05 17:23:41 +00003854 if (!Py_ISXDIGIT(c)) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003855 endinpos = (s+i+1)-starts;
3856 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003857 errors, &errorHandler,
3858 "unicodeescape", message,
3859 &starts, &end, &startinpos, &endinpos, &exc, &s,
3860 &v, &outpos, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00003861 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003862 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00003863 }
3864 chr = (chr<<4) & ~0xF;
3865 if (c >= '0' && c <= '9')
3866 chr += c - '0';
3867 else if (c >= 'a' && c <= 'f')
3868 chr += 10 + c - 'a';
3869 else
3870 chr += 10 + c - 'A';
3871 }
3872 s += i;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00003873 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003874 /* _decoding_error will have already written into the
3875 target buffer. */
3876 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003877 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00003878 /* when we get here, chr is a 32-bit unicode character */
3879 if (chr <= 0xffff)
3880 /* UCS-2 character */
3881 *p++ = (Py_UNICODE) chr;
3882 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00003883 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00003884 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00003885#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003886 *p++ = chr;
3887#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00003888 chr -= 0x10000L;
3889 *p++ = 0xD800 + (Py_UNICODE) (chr >> 10);
Fredrik Lundh45714e92001-06-26 16:39:36 +00003890 *p++ = 0xDC00 + (Py_UNICODE) (chr & 0x03FF);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003891#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00003892 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003893 endinpos = s-starts;
3894 outpos = p-PyUnicode_AS_UNICODE(v);
3895 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003896 errors, &errorHandler,
3897 "unicodeescape", "illegal Unicode character",
3898 &starts, &end, &startinpos, &endinpos, &exc, &s,
3899 &v, &outpos, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00003900 goto onError;
3901 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00003902 break;
3903
Benjamin Peterson29060642009-01-31 22:14:21 +00003904 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00003905 case 'N':
3906 message = "malformed \\N character escape";
3907 if (ucnhash_CAPI == NULL) {
3908 /* load the unicode data module */
Benjamin Petersonb173f782009-05-05 22:31:58 +00003909 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00003910 if (ucnhash_CAPI == NULL)
3911 goto ucnhashError;
3912 }
3913 if (*s == '{') {
3914 const char *start = s+1;
3915 /* look for the closing brace */
3916 while (*s != '}' && s < end)
3917 s++;
3918 if (s > start && s < end && *s == '}') {
3919 /* found a name. look it up in the unicode database */
3920 message = "unknown Unicode character name";
3921 s++;
Martin v. Löwis480f1bb2006-03-09 23:38:20 +00003922 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1), &chr))
Fredrik Lundhccc74732001-02-18 22:13:49 +00003923 goto store;
3924 }
3925 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003926 endinpos = s-starts;
3927 outpos = p-PyUnicode_AS_UNICODE(v);
3928 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003929 errors, &errorHandler,
3930 "unicodeescape", message,
3931 &starts, &end, &startinpos, &endinpos, &exc, &s,
3932 &v, &outpos, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00003933 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003934 break;
3935
3936 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00003937 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003938 message = "\\ at end of string";
3939 s--;
3940 endinpos = s-starts;
3941 outpos = p-PyUnicode_AS_UNICODE(v);
3942 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003943 errors, &errorHandler,
3944 "unicodeescape", message,
3945 &starts, &end, &startinpos, &endinpos, &exc, &s,
3946 &v, &outpos, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00003947 goto onError;
3948 }
3949 else {
3950 *p++ = '\\';
3951 *p++ = (unsigned char)s[-1];
3952 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00003953 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003954 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003955 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003956 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003957 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003958 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003959 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00003960 Py_XDECREF(errorHandler);
3961 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003962 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00003963
Benjamin Peterson29060642009-01-31 22:14:21 +00003964 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00003965 PyErr_SetString(
3966 PyExc_UnicodeError,
3967 "\\N escapes not supported (can't load unicodedata module)"
3968 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003969 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003970 Py_XDECREF(errorHandler);
3971 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00003972 return NULL;
3973
Benjamin Peterson29060642009-01-31 22:14:21 +00003974 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003975 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003976 Py_XDECREF(errorHandler);
3977 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003978 return NULL;
3979}
3980
3981/* Return a Unicode-Escape string version of the Unicode object.
3982
3983 If quotes is true, the string is enclosed in u"" or u'' quotes as
3984 appropriate.
3985
3986*/
3987
Thomas Wouters477c8d52006-05-27 19:21:47 +00003988Py_LOCAL_INLINE(const Py_UNICODE *) findchar(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003989 Py_ssize_t size,
3990 Py_UNICODE ch)
Thomas Wouters477c8d52006-05-27 19:21:47 +00003991{
3992 /* like wcschr, but doesn't stop at NULL characters */
3993
3994 while (size-- > 0) {
3995 if (*s == ch)
3996 return s;
3997 s++;
3998 }
3999
4000 return NULL;
4001}
Barry Warsaw51ac5802000-03-20 16:36:48 +00004002
Walter Dörwald79e913e2007-05-12 11:08:06 +00004003static const char *hexdigits = "0123456789abcdef";
4004
4005PyObject *PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004006 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004007{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004008 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004009 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004010
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004011#ifdef Py_UNICODE_WIDE
4012 const Py_ssize_t expandsize = 10;
4013#else
4014 const Py_ssize_t expandsize = 6;
4015#endif
4016
Thomas Wouters89f507f2006-12-13 04:49:30 +00004017 /* XXX(nnorwitz): rather than over-allocating, it would be
4018 better to choose a different scheme. Perhaps scan the
4019 first N-chars of the string and allocate based on that size.
4020 */
4021 /* Initial allocation is based on the longest-possible unichr
4022 escape.
4023
4024 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
4025 unichr, so in this case it's the longest unichr escape. In
4026 narrow (UTF-16) builds this is five chars per source unichr
4027 since there are two unichrs in the surrogate pair, so in narrow
4028 (UTF-16) builds it's not the longest unichr escape.
4029
4030 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
4031 so in the narrow (UTF-16) build case it's the longest unichr
4032 escape.
4033 */
4034
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004035 if (size == 0)
4036 return PyBytes_FromStringAndSize(NULL, 0);
4037
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004038 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00004039 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004040
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004041 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00004042 2
4043 + expandsize*size
4044 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004045 if (repr == NULL)
4046 return NULL;
4047
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004048 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004049
Guido van Rossumd57fd912000-03-10 22:53:23 +00004050 while (size-- > 0) {
4051 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004052
Walter Dörwald79e913e2007-05-12 11:08:06 +00004053 /* Escape backslashes */
4054 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004055 *p++ = '\\';
4056 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00004057 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004058 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004059
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00004060#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004061 /* Map 21-bit characters to '\U00xxxxxx' */
4062 else if (ch >= 0x10000) {
4063 *p++ = '\\';
4064 *p++ = 'U';
Walter Dörwald79e913e2007-05-12 11:08:06 +00004065 *p++ = hexdigits[(ch >> 28) & 0x0000000F];
4066 *p++ = hexdigits[(ch >> 24) & 0x0000000F];
4067 *p++ = hexdigits[(ch >> 20) & 0x0000000F];
4068 *p++ = hexdigits[(ch >> 16) & 0x0000000F];
4069 *p++ = hexdigits[(ch >> 12) & 0x0000000F];
4070 *p++ = hexdigits[(ch >> 8) & 0x0000000F];
4071 *p++ = hexdigits[(ch >> 4) & 0x0000000F];
4072 *p++ = hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00004073 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004074 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00004075#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004076 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
4077 else if (ch >= 0xD800 && ch < 0xDC00) {
4078 Py_UNICODE ch2;
4079 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00004080
Benjamin Peterson29060642009-01-31 22:14:21 +00004081 ch2 = *s++;
4082 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00004083 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004084 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
4085 *p++ = '\\';
4086 *p++ = 'U';
4087 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
4088 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
4089 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
4090 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
4091 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
4092 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
4093 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
4094 *p++ = hexdigits[ucs & 0x0000000F];
4095 continue;
4096 }
4097 /* Fall through: isolated surrogates are copied as-is */
4098 s--;
4099 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004100 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00004101#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00004102
Guido van Rossumd57fd912000-03-10 22:53:23 +00004103 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00004104 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004105 *p++ = '\\';
4106 *p++ = 'u';
Walter Dörwald79e913e2007-05-12 11:08:06 +00004107 *p++ = hexdigits[(ch >> 12) & 0x000F];
4108 *p++ = hexdigits[(ch >> 8) & 0x000F];
4109 *p++ = hexdigits[(ch >> 4) & 0x000F];
4110 *p++ = hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00004111 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004112
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00004113 /* Map special whitespace to '\t', \n', '\r' */
4114 else if (ch == '\t') {
4115 *p++ = '\\';
4116 *p++ = 't';
4117 }
4118 else if (ch == '\n') {
4119 *p++ = '\\';
4120 *p++ = 'n';
4121 }
4122 else if (ch == '\r') {
4123 *p++ = '\\';
4124 *p++ = 'r';
4125 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004126
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00004127 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00004128 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004129 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00004130 *p++ = 'x';
Walter Dörwald79e913e2007-05-12 11:08:06 +00004131 *p++ = hexdigits[(ch >> 4) & 0x000F];
4132 *p++ = hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00004133 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004134
Guido van Rossumd57fd912000-03-10 22:53:23 +00004135 /* Copy everything else as-is */
4136 else
4137 *p++ = (char) ch;
4138 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004139
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004140 assert(p - PyBytes_AS_STRING(repr) > 0);
4141 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
4142 return NULL;
4143 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004144}
4145
Alexandre Vassalotti2056bed2008-12-27 19:46:35 +00004146PyObject *PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004147{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004148 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004149 if (!PyUnicode_Check(unicode)) {
4150 PyErr_BadArgument();
4151 return NULL;
4152 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00004153 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
4154 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004155 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004156}
4157
4158/* --- Raw Unicode Escape Codec ------------------------------------------- */
4159
4160PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004161 Py_ssize_t size,
4162 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004163{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004164 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004165 Py_ssize_t startinpos;
4166 Py_ssize_t endinpos;
4167 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004168 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004169 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004170 const char *end;
4171 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004172 PyObject *errorHandler = NULL;
4173 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00004174
Guido van Rossumd57fd912000-03-10 22:53:23 +00004175 /* Escaped strings will always be longer than the resulting
4176 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004177 length after conversion to the true value. (But decoding error
4178 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004179 v = _PyUnicode_New(size);
4180 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004181 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004182 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004183 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004184 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004185 end = s + size;
4186 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004187 unsigned char c;
4188 Py_UCS4 x;
4189 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004190 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004191
Benjamin Peterson29060642009-01-31 22:14:21 +00004192 /* Non-escape characters are interpreted as Unicode ordinals */
4193 if (*s != '\\') {
4194 *p++ = (unsigned char)*s++;
4195 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004196 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004197 startinpos = s-starts;
4198
4199 /* \u-escapes are only interpreted iff the number of leading
4200 backslashes if odd */
4201 bs = s;
4202 for (;s < end;) {
4203 if (*s != '\\')
4204 break;
4205 *p++ = (unsigned char)*s++;
4206 }
4207 if (((s - bs) & 1) == 0 ||
4208 s >= end ||
4209 (*s != 'u' && *s != 'U')) {
4210 continue;
4211 }
4212 p--;
4213 count = *s=='u' ? 4 : 8;
4214 s++;
4215
4216 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
4217 outpos = p-PyUnicode_AS_UNICODE(v);
4218 for (x = 0, i = 0; i < count; ++i, ++s) {
4219 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00004220 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004221 endinpos = s-starts;
4222 if (unicode_decode_call_errorhandler(
4223 errors, &errorHandler,
4224 "rawunicodeescape", "truncated \\uXXXX",
4225 &starts, &end, &startinpos, &endinpos, &exc, &s,
4226 &v, &outpos, &p))
4227 goto onError;
4228 goto nextByte;
4229 }
4230 x = (x<<4) & ~0xF;
4231 if (c >= '0' && c <= '9')
4232 x += c - '0';
4233 else if (c >= 'a' && c <= 'f')
4234 x += 10 + c - 'a';
4235 else
4236 x += 10 + c - 'A';
4237 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00004238 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00004239 /* UCS-2 character */
4240 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004241 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004242 /* UCS-4 character. Either store directly, or as
4243 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00004244#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004245 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004246#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004247 x -= 0x10000L;
4248 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
4249 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00004250#endif
4251 } else {
4252 endinpos = s-starts;
4253 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004254 if (unicode_decode_call_errorhandler(
4255 errors, &errorHandler,
4256 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00004257 &starts, &end, &startinpos, &endinpos, &exc, &s,
4258 &v, &outpos, &p))
4259 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004260 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004261 nextByte:
4262 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004263 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004264 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004265 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004266 Py_XDECREF(errorHandler);
4267 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004268 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004269
Benjamin Peterson29060642009-01-31 22:14:21 +00004270 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004271 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004272 Py_XDECREF(errorHandler);
4273 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004274 return NULL;
4275}
4276
4277PyObject *PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004278 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004279{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004280 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004281 char *p;
4282 char *q;
4283
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004284#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004285 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004286#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004287 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004288#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00004289
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004290 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00004291 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00004292
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004293 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004294 if (repr == NULL)
4295 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00004296 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004297 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004298
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004299 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004300 while (size-- > 0) {
4301 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004302#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004303 /* Map 32-bit characters to '\Uxxxxxxxx' */
4304 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004305 *p++ = '\\';
4306 *p++ = 'U';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00004307 *p++ = hexdigits[(ch >> 28) & 0xf];
4308 *p++ = hexdigits[(ch >> 24) & 0xf];
4309 *p++ = hexdigits[(ch >> 20) & 0xf];
4310 *p++ = hexdigits[(ch >> 16) & 0xf];
4311 *p++ = hexdigits[(ch >> 12) & 0xf];
4312 *p++ = hexdigits[(ch >> 8) & 0xf];
4313 *p++ = hexdigits[(ch >> 4) & 0xf];
4314 *p++ = hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00004315 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004316 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00004317#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004318 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
4319 if (ch >= 0xD800 && ch < 0xDC00) {
4320 Py_UNICODE ch2;
4321 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004322
Benjamin Peterson29060642009-01-31 22:14:21 +00004323 ch2 = *s++;
4324 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00004325 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004326 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
4327 *p++ = '\\';
4328 *p++ = 'U';
4329 *p++ = hexdigits[(ucs >> 28) & 0xf];
4330 *p++ = hexdigits[(ucs >> 24) & 0xf];
4331 *p++ = hexdigits[(ucs >> 20) & 0xf];
4332 *p++ = hexdigits[(ucs >> 16) & 0xf];
4333 *p++ = hexdigits[(ucs >> 12) & 0xf];
4334 *p++ = hexdigits[(ucs >> 8) & 0xf];
4335 *p++ = hexdigits[(ucs >> 4) & 0xf];
4336 *p++ = hexdigits[ucs & 0xf];
4337 continue;
4338 }
4339 /* Fall through: isolated surrogates are copied as-is */
4340 s--;
4341 size++;
4342 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004343#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004344 /* Map 16-bit characters to '\uxxxx' */
4345 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004346 *p++ = '\\';
4347 *p++ = 'u';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00004348 *p++ = hexdigits[(ch >> 12) & 0xf];
4349 *p++ = hexdigits[(ch >> 8) & 0xf];
4350 *p++ = hexdigits[(ch >> 4) & 0xf];
4351 *p++ = hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00004352 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004353 /* Copy everything else as-is */
4354 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00004355 *p++ = (char) ch;
4356 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00004357 size = p - q;
4358
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004359 assert(size > 0);
4360 if (_PyBytes_Resize(&repr, size) < 0)
4361 return NULL;
4362 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004363}
4364
4365PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
4366{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004367 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004368 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00004369 PyErr_BadArgument();
4370 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004371 }
Walter Dörwald711005d2007-05-12 12:03:26 +00004372 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
4373 PyUnicode_GET_SIZE(unicode));
4374
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004375 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004376}
4377
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004378/* --- Unicode Internal Codec ------------------------------------------- */
4379
4380PyObject *_PyUnicode_DecodeUnicodeInternal(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004381 Py_ssize_t size,
4382 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004383{
4384 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004385 Py_ssize_t startinpos;
4386 Py_ssize_t endinpos;
4387 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004388 PyUnicodeObject *v;
4389 Py_UNICODE *p;
4390 const char *end;
4391 const char *reason;
4392 PyObject *errorHandler = NULL;
4393 PyObject *exc = NULL;
4394
Neal Norwitzd43069c2006-01-08 01:12:10 +00004395#ifdef Py_UNICODE_WIDE
4396 Py_UNICODE unimax = PyUnicode_GetMax();
4397#endif
4398
Thomas Wouters89f507f2006-12-13 04:49:30 +00004399 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004400 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
4401 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004402 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004403 if (PyUnicode_GetSize((PyObject *)v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004404 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004405 p = PyUnicode_AS_UNICODE(v);
4406 end = s + size;
4407
4408 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00004409 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004410 /* We have to sanity check the raw data, otherwise doom looms for
4411 some malformed UCS-4 data. */
4412 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00004413#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004414 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00004415#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004416 end-s < Py_UNICODE_SIZE
4417 )
Benjamin Peterson29060642009-01-31 22:14:21 +00004418 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004419 startinpos = s - starts;
4420 if (end-s < Py_UNICODE_SIZE) {
4421 endinpos = end-starts;
4422 reason = "truncated input";
4423 }
4424 else {
4425 endinpos = s - starts + Py_UNICODE_SIZE;
4426 reason = "illegal code point (> 0x10FFFF)";
4427 }
4428 outpos = p - PyUnicode_AS_UNICODE(v);
4429 if (unicode_decode_call_errorhandler(
4430 errors, &errorHandler,
4431 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00004432 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00004433 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004434 goto onError;
4435 }
4436 }
4437 else {
4438 p++;
4439 s += Py_UNICODE_SIZE;
4440 }
4441 }
4442
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004443 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004444 goto onError;
4445 Py_XDECREF(errorHandler);
4446 Py_XDECREF(exc);
4447 return (PyObject *)v;
4448
Benjamin Peterson29060642009-01-31 22:14:21 +00004449 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004450 Py_XDECREF(v);
4451 Py_XDECREF(errorHandler);
4452 Py_XDECREF(exc);
4453 return NULL;
4454}
4455
Guido van Rossumd57fd912000-03-10 22:53:23 +00004456/* --- Latin-1 Codec ------------------------------------------------------ */
4457
4458PyObject *PyUnicode_DecodeLatin1(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004459 Py_ssize_t size,
4460 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004461{
4462 PyUnicodeObject *v;
4463 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00004464 const char *e, *unrolled_end;
Tim Petersced69f82003-09-16 20:30:58 +00004465
Guido van Rossumd57fd912000-03-10 22:53:23 +00004466 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004467 if (size == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004468 Py_UNICODE r = *(unsigned char*)s;
4469 return PyUnicode_FromUnicode(&r, 1);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004470 }
4471
Guido van Rossumd57fd912000-03-10 22:53:23 +00004472 v = _PyUnicode_New(size);
4473 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004474 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004475 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004476 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004477 p = PyUnicode_AS_UNICODE(v);
Antoine Pitrouab868312009-01-10 15:40:25 +00004478 e = s + size;
4479 /* Unrolling the copy makes it much faster by reducing the looping
4480 overhead. This is similar to what many memcpy() implementations do. */
4481 unrolled_end = e - 4;
4482 while (s < unrolled_end) {
4483 p[0] = (unsigned char) s[0];
4484 p[1] = (unsigned char) s[1];
4485 p[2] = (unsigned char) s[2];
4486 p[3] = (unsigned char) s[3];
4487 s += 4;
4488 p += 4;
4489 }
4490 while (s < e)
4491 *p++ = (unsigned char) *s++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004492 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004493
Benjamin Peterson29060642009-01-31 22:14:21 +00004494 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004495 Py_XDECREF(v);
4496 return NULL;
4497}
4498
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004499/* create or adjust a UnicodeEncodeError */
4500static void make_encode_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004501 const char *encoding,
4502 const Py_UNICODE *unicode, Py_ssize_t size,
4503 Py_ssize_t startpos, Py_ssize_t endpos,
4504 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004505{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004506 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004507 *exceptionObject = PyUnicodeEncodeError_Create(
4508 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004509 }
4510 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004511 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
4512 goto onError;
4513 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
4514 goto onError;
4515 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
4516 goto onError;
4517 return;
4518 onError:
4519 Py_DECREF(*exceptionObject);
4520 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004521 }
4522}
4523
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004524/* raises a UnicodeEncodeError */
4525static void raise_encode_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004526 const char *encoding,
4527 const Py_UNICODE *unicode, Py_ssize_t size,
4528 Py_ssize_t startpos, Py_ssize_t endpos,
4529 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004530{
4531 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004532 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004533 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004534 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004535}
4536
4537/* error handling callback helper:
4538 build arguments, call the callback and check the arguments,
4539 put the result into newpos and return the replacement string, which
4540 has to be freed by the caller */
4541static PyObject *unicode_encode_call_errorhandler(const char *errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00004542 PyObject **errorHandler,
4543 const char *encoding, const char *reason,
4544 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
4545 Py_ssize_t startpos, Py_ssize_t endpos,
4546 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004547{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004548 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004549
4550 PyObject *restuple;
4551 PyObject *resunicode;
4552
4553 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004554 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004555 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004556 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004557 }
4558
4559 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004560 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004561 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004562 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004563
4564 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00004565 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004566 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004567 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004568 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004569 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004570 Py_DECREF(restuple);
4571 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004572 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004573 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00004574 &resunicode, newpos)) {
4575 Py_DECREF(restuple);
4576 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004577 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004578 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
4579 PyErr_SetString(PyExc_TypeError, &argparse[3]);
4580 Py_DECREF(restuple);
4581 return NULL;
4582 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004583 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004584 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004585 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004586 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
4587 Py_DECREF(restuple);
4588 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004589 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004590 Py_INCREF(resunicode);
4591 Py_DECREF(restuple);
4592 return resunicode;
4593}
4594
4595static PyObject *unicode_encode_ucs1(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004596 Py_ssize_t size,
4597 const char *errors,
4598 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004599{
4600 /* output object */
4601 PyObject *res;
4602 /* pointers to the beginning and end+1 of input */
4603 const Py_UNICODE *startp = p;
4604 const Py_UNICODE *endp = p + size;
4605 /* pointer to the beginning of the unencodable characters */
4606 /* const Py_UNICODE *badp = NULL; */
4607 /* pointer into the output */
4608 char *str;
4609 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00004610 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004611 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
4612 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004613 PyObject *errorHandler = NULL;
4614 PyObject *exc = NULL;
4615 /* the following variable is used for caching string comparisons
4616 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
4617 int known_errorHandler = -1;
4618
4619 /* allocate enough for a simple encoding without
4620 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00004621 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00004622 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004623 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004624 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00004625 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004626 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004627 ressize = size;
4628
4629 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004630 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004631
Benjamin Peterson29060642009-01-31 22:14:21 +00004632 /* can we encode this? */
4633 if (c<limit) {
4634 /* no overflow check, because we know that the space is enough */
4635 *str++ = (char)c;
4636 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004637 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004638 else {
4639 Py_ssize_t unicodepos = p-startp;
4640 Py_ssize_t requiredsize;
4641 PyObject *repunicode;
4642 Py_ssize_t repsize;
4643 Py_ssize_t newpos;
4644 Py_ssize_t respos;
4645 Py_UNICODE *uni2;
4646 /* startpos for collecting unencodable chars */
4647 const Py_UNICODE *collstart = p;
4648 const Py_UNICODE *collend = p;
4649 /* find all unecodable characters */
4650 while ((collend < endp) && ((*collend)>=limit))
4651 ++collend;
4652 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
4653 if (known_errorHandler==-1) {
4654 if ((errors==NULL) || (!strcmp(errors, "strict")))
4655 known_errorHandler = 1;
4656 else if (!strcmp(errors, "replace"))
4657 known_errorHandler = 2;
4658 else if (!strcmp(errors, "ignore"))
4659 known_errorHandler = 3;
4660 else if (!strcmp(errors, "xmlcharrefreplace"))
4661 known_errorHandler = 4;
4662 else
4663 known_errorHandler = 0;
4664 }
4665 switch (known_errorHandler) {
4666 case 1: /* strict */
4667 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
4668 goto onError;
4669 case 2: /* replace */
4670 while (collstart++<collend)
4671 *str++ = '?'; /* fall through */
4672 case 3: /* ignore */
4673 p = collend;
4674 break;
4675 case 4: /* xmlcharrefreplace */
4676 respos = str - PyBytes_AS_STRING(res);
4677 /* determine replacement size (temporarily (mis)uses p) */
4678 for (p = collstart, repsize = 0; p < collend; ++p) {
4679 if (*p<10)
4680 repsize += 2+1+1;
4681 else if (*p<100)
4682 repsize += 2+2+1;
4683 else if (*p<1000)
4684 repsize += 2+3+1;
4685 else if (*p<10000)
4686 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00004687#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004688 else
4689 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00004690#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004691 else if (*p<100000)
4692 repsize += 2+5+1;
4693 else if (*p<1000000)
4694 repsize += 2+6+1;
4695 else
4696 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004697#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004698 }
4699 requiredsize = respos+repsize+(endp-collend);
4700 if (requiredsize > ressize) {
4701 if (requiredsize<2*ressize)
4702 requiredsize = 2*ressize;
4703 if (_PyBytes_Resize(&res, requiredsize))
4704 goto onError;
4705 str = PyBytes_AS_STRING(res) + respos;
4706 ressize = requiredsize;
4707 }
4708 /* generate replacement (temporarily (mis)uses p) */
4709 for (p = collstart; p < collend; ++p) {
4710 str += sprintf(str, "&#%d;", (int)*p);
4711 }
4712 p = collend;
4713 break;
4714 default:
4715 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
4716 encoding, reason, startp, size, &exc,
4717 collstart-startp, collend-startp, &newpos);
4718 if (repunicode == NULL)
4719 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004720 if (PyBytes_Check(repunicode)) {
4721 /* Directly copy bytes result to output. */
4722 repsize = PyBytes_Size(repunicode);
4723 if (repsize > 1) {
4724 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00004725 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00004726 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
4727 Py_DECREF(repunicode);
4728 goto onError;
4729 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00004730 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004731 ressize += repsize-1;
4732 }
4733 memcpy(str, PyBytes_AsString(repunicode), repsize);
4734 str += repsize;
4735 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004736 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00004737 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004738 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004739 /* need more space? (at least enough for what we
4740 have+the replacement+the rest of the string, so
4741 we won't have to check space for encodable characters) */
4742 respos = str - PyBytes_AS_STRING(res);
4743 repsize = PyUnicode_GET_SIZE(repunicode);
4744 requiredsize = respos+repsize+(endp-collend);
4745 if (requiredsize > ressize) {
4746 if (requiredsize<2*ressize)
4747 requiredsize = 2*ressize;
4748 if (_PyBytes_Resize(&res, requiredsize)) {
4749 Py_DECREF(repunicode);
4750 goto onError;
4751 }
4752 str = PyBytes_AS_STRING(res) + respos;
4753 ressize = requiredsize;
4754 }
4755 /* check if there is anything unencodable in the replacement
4756 and copy it to the output */
4757 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
4758 c = *uni2;
4759 if (c >= limit) {
4760 raise_encode_exception(&exc, encoding, startp, size,
4761 unicodepos, unicodepos+1, reason);
4762 Py_DECREF(repunicode);
4763 goto onError;
4764 }
4765 *str = (char)c;
4766 }
4767 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004768 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00004769 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004770 }
4771 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004772 /* Resize if we allocated to much */
4773 size = str - PyBytes_AS_STRING(res);
4774 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00004775 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004776 if (_PyBytes_Resize(&res, size) < 0)
4777 goto onError;
4778 }
4779
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004780 Py_XDECREF(errorHandler);
4781 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004782 return res;
4783
4784 onError:
4785 Py_XDECREF(res);
4786 Py_XDECREF(errorHandler);
4787 Py_XDECREF(exc);
4788 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004789}
4790
Guido van Rossumd57fd912000-03-10 22:53:23 +00004791PyObject *PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004792 Py_ssize_t size,
4793 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004794{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004795 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004796}
4797
4798PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
4799{
4800 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004801 PyErr_BadArgument();
4802 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004803 }
4804 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004805 PyUnicode_GET_SIZE(unicode),
4806 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004807}
4808
4809/* --- 7-bit ASCII Codec -------------------------------------------------- */
4810
Guido van Rossumd57fd912000-03-10 22:53:23 +00004811PyObject *PyUnicode_DecodeASCII(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004812 Py_ssize_t size,
4813 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004814{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004815 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004816 PyUnicodeObject *v;
4817 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004818 Py_ssize_t startinpos;
4819 Py_ssize_t endinpos;
4820 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004821 const char *e;
4822 PyObject *errorHandler = NULL;
4823 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00004824
Guido van Rossumd57fd912000-03-10 22:53:23 +00004825 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004826 if (size == 1 && *(unsigned char*)s < 128) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004827 Py_UNICODE r = *(unsigned char*)s;
4828 return PyUnicode_FromUnicode(&r, 1);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004829 }
Tim Petersced69f82003-09-16 20:30:58 +00004830
Guido van Rossumd57fd912000-03-10 22:53:23 +00004831 v = _PyUnicode_New(size);
4832 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004833 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004834 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004835 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004836 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004837 e = s + size;
4838 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004839 register unsigned char c = (unsigned char)*s;
4840 if (c < 128) {
4841 *p++ = c;
4842 ++s;
4843 }
4844 else {
4845 startinpos = s-starts;
4846 endinpos = startinpos + 1;
4847 outpos = p - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
4848 if (unicode_decode_call_errorhandler(
4849 errors, &errorHandler,
4850 "ascii", "ordinal not in range(128)",
4851 &starts, &e, &startinpos, &endinpos, &exc, &s,
4852 &v, &outpos, &p))
4853 goto onError;
4854 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004855 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00004856 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00004857 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
4858 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004859 Py_XDECREF(errorHandler);
4860 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004861 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004862
Benjamin Peterson29060642009-01-31 22:14:21 +00004863 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004864 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004865 Py_XDECREF(errorHandler);
4866 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004867 return NULL;
4868}
4869
Guido van Rossumd57fd912000-03-10 22:53:23 +00004870PyObject *PyUnicode_EncodeASCII(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004871 Py_ssize_t size,
4872 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004873{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004874 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004875}
4876
4877PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
4878{
4879 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004880 PyErr_BadArgument();
4881 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004882 }
4883 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004884 PyUnicode_GET_SIZE(unicode),
4885 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004886}
4887
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004888#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004889
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004890/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004891
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00004892#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004893#define NEED_RETRY
4894#endif
4895
4896/* XXX This code is limited to "true" double-byte encodings, as
4897 a) it assumes an incomplete character consists of a single byte, and
4898 b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
Benjamin Peterson29060642009-01-31 22:14:21 +00004899 encodings, see IsDBCSLeadByteEx documentation. */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004900
4901static int is_dbcs_lead_byte(const char *s, int offset)
4902{
4903 const char *curr = s + offset;
4904
4905 if (IsDBCSLeadByte(*curr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004906 const char *prev = CharPrev(s, curr);
4907 return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004908 }
4909 return 0;
4910}
4911
4912/*
4913 * Decode MBCS string into unicode object. If 'final' is set, converts
4914 * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
4915 */
4916static int decode_mbcs(PyUnicodeObject **v,
Benjamin Peterson29060642009-01-31 22:14:21 +00004917 const char *s, /* MBCS string */
4918 int size, /* sizeof MBCS string */
Victor Stinner554f3f02010-06-16 23:33:54 +00004919 int final,
4920 const char *errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004921{
4922 Py_UNICODE *p;
Victor Stinner554f3f02010-06-16 23:33:54 +00004923 Py_ssize_t n;
4924 DWORD usize;
4925 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004926
4927 assert(size >= 0);
4928
Victor Stinner554f3f02010-06-16 23:33:54 +00004929 /* check and handle 'errors' arg */
4930 if (errors==NULL || strcmp(errors, "strict")==0)
4931 flags = MB_ERR_INVALID_CHARS;
4932 else if (strcmp(errors, "ignore")==0)
4933 flags = 0;
4934 else {
4935 PyErr_Format(PyExc_ValueError,
4936 "mbcs encoding does not support errors='%s'",
4937 errors);
4938 return -1;
4939 }
4940
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004941 /* Skip trailing lead-byte unless 'final' is set */
4942 if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
Benjamin Peterson29060642009-01-31 22:14:21 +00004943 --size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004944
4945 /* First get the size of the result */
4946 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00004947 usize = MultiByteToWideChar(CP_ACP, flags, s, size, NULL, 0);
4948 if (usize==0)
4949 goto mbcs_decode_error;
4950 } else
4951 usize = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004952
4953 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004954 /* Create unicode object */
4955 *v = _PyUnicode_New(usize);
4956 if (*v == NULL)
4957 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00004958 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004959 }
4960 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004961 /* Extend unicode object */
4962 n = PyUnicode_GET_SIZE(*v);
4963 if (_PyUnicode_Resize(v, n + usize) < 0)
4964 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004965 }
4966
4967 /* Do the conversion */
Victor Stinner554f3f02010-06-16 23:33:54 +00004968 if (usize > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004969 p = PyUnicode_AS_UNICODE(*v) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00004970 if (0 == MultiByteToWideChar(CP_ACP, flags, s, size, p, usize)) {
4971 goto mbcs_decode_error;
Benjamin Peterson29060642009-01-31 22:14:21 +00004972 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004973 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004974 return size;
Victor Stinner554f3f02010-06-16 23:33:54 +00004975
4976mbcs_decode_error:
4977 /* If the last error was ERROR_NO_UNICODE_TRANSLATION, then
4978 we raise a UnicodeDecodeError - else it is a 'generic'
4979 windows error
4980 */
4981 if (GetLastError()==ERROR_NO_UNICODE_TRANSLATION) {
4982 /* Ideally, we should get reason from FormatMessage - this
4983 is the Windows 2000 English version of the message
4984 */
4985 PyObject *exc = NULL;
4986 const char *reason = "No mapping for the Unicode character exists "
4987 "in the target multi-byte code page.";
4988 make_decode_exception(&exc, "mbcs", s, size, 0, 0, reason);
4989 if (exc != NULL) {
4990 PyCodec_StrictErrors(exc);
4991 Py_DECREF(exc);
4992 }
4993 } else {
4994 PyErr_SetFromWindowsErrWithFilename(0, NULL);
4995 }
4996 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004997}
4998
4999PyObject *PyUnicode_DecodeMBCSStateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005000 Py_ssize_t size,
5001 const char *errors,
5002 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005003{
5004 PyUnicodeObject *v = NULL;
5005 int done;
5006
5007 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005008 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005009
5010#ifdef NEED_RETRY
5011 retry:
5012 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00005013 done = decode_mbcs(&v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005014 else
5015#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00005016 done = decode_mbcs(&v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005017
5018 if (done < 0) {
5019 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00005020 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005021 }
5022
5023 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005024 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005025
5026#ifdef NEED_RETRY
5027 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005028 s += done;
5029 size -= done;
5030 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005031 }
5032#endif
5033
5034 return (PyObject *)v;
5035}
5036
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005037PyObject *PyUnicode_DecodeMBCS(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005038 Py_ssize_t size,
5039 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005040{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005041 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
5042}
5043
5044/*
5045 * Convert unicode into string object (MBCS).
5046 * Returns 0 if succeed, -1 otherwise.
5047 */
5048static int encode_mbcs(PyObject **repr,
Benjamin Peterson29060642009-01-31 22:14:21 +00005049 const Py_UNICODE *p, /* unicode */
Victor Stinner554f3f02010-06-16 23:33:54 +00005050 int size, /* size of unicode */
5051 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005052{
Victor Stinner554f3f02010-06-16 23:33:54 +00005053 BOOL usedDefaultChar = FALSE;
5054 BOOL *pusedDefaultChar;
5055 int mbcssize;
5056 Py_ssize_t n;
5057 PyObject *exc = NULL;
5058 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005059
5060 assert(size >= 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005061
Victor Stinner554f3f02010-06-16 23:33:54 +00005062 /* check and handle 'errors' arg */
5063 if (errors==NULL || strcmp(errors, "strict")==0) {
5064 flags = WC_NO_BEST_FIT_CHARS;
5065 pusedDefaultChar = &usedDefaultChar;
5066 } else if (strcmp(errors, "replace")==0) {
5067 flags = 0;
5068 pusedDefaultChar = NULL;
5069 } else {
5070 PyErr_Format(PyExc_ValueError,
5071 "mbcs encoding does not support errors='%s'",
5072 errors);
5073 return -1;
5074 }
5075
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005076 /* First get the size of the result */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005077 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00005078 mbcssize = WideCharToMultiByte(CP_ACP, flags, p, size, NULL, 0,
5079 NULL, pusedDefaultChar);
Benjamin Peterson29060642009-01-31 22:14:21 +00005080 if (mbcssize == 0) {
5081 PyErr_SetFromWindowsErrWithFilename(0, NULL);
5082 return -1;
5083 }
Victor Stinner554f3f02010-06-16 23:33:54 +00005084 /* If we used a default char, then we failed! */
5085 if (pusedDefaultChar && *pusedDefaultChar)
5086 goto mbcs_encode_error;
5087 } else {
5088 mbcssize = 0;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005089 }
5090
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005091 if (*repr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005092 /* Create string object */
5093 *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
5094 if (*repr == NULL)
5095 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00005096 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005097 }
5098 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005099 /* Extend string object */
5100 n = PyBytes_Size(*repr);
5101 if (_PyBytes_Resize(repr, n + mbcssize) < 0)
5102 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005103 }
5104
5105 /* Do the conversion */
5106 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005107 char *s = PyBytes_AS_STRING(*repr) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00005108 if (0 == WideCharToMultiByte(CP_ACP, flags, p, size, s, mbcssize,
5109 NULL, pusedDefaultChar)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005110 PyErr_SetFromWindowsErrWithFilename(0, NULL);
5111 return -1;
5112 }
Victor Stinner554f3f02010-06-16 23:33:54 +00005113 if (pusedDefaultChar && *pusedDefaultChar)
5114 goto mbcs_encode_error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005115 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005116 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00005117
5118mbcs_encode_error:
5119 raise_encode_exception(&exc, "mbcs", p, size, 0, 0, "invalid character");
5120 Py_XDECREF(exc);
5121 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005122}
5123
5124PyObject *PyUnicode_EncodeMBCS(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00005125 Py_ssize_t size,
5126 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005127{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005128 PyObject *repr = NULL;
5129 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00005130
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005131#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00005132 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005133 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00005134 ret = encode_mbcs(&repr, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005135 else
5136#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00005137 ret = encode_mbcs(&repr, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005138
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005139 if (ret < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005140 Py_XDECREF(repr);
5141 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005142 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005143
5144#ifdef NEED_RETRY
5145 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005146 p += INT_MAX;
5147 size -= INT_MAX;
5148 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005149 }
5150#endif
5151
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005152 return repr;
5153}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00005154
Mark Hammond0ccda1e2003-07-01 00:13:27 +00005155PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
5156{
5157 if (!PyUnicode_Check(unicode)) {
5158 PyErr_BadArgument();
5159 return NULL;
5160 }
5161 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005162 PyUnicode_GET_SIZE(unicode),
5163 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00005164}
5165
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005166#undef NEED_RETRY
5167
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00005168#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005169
Guido van Rossumd57fd912000-03-10 22:53:23 +00005170/* --- Character Mapping Codec -------------------------------------------- */
5171
Guido van Rossumd57fd912000-03-10 22:53:23 +00005172PyObject *PyUnicode_DecodeCharmap(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005173 Py_ssize_t size,
5174 PyObject *mapping,
5175 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005176{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005177 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005178 Py_ssize_t startinpos;
5179 Py_ssize_t endinpos;
5180 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005181 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005182 PyUnicodeObject *v;
5183 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005184 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005185 PyObject *errorHandler = NULL;
5186 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005187 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005188 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00005189
Guido van Rossumd57fd912000-03-10 22:53:23 +00005190 /* Default to Latin-1 */
5191 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005192 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005193
5194 v = _PyUnicode_New(size);
5195 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005196 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005197 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005198 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005199 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005200 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005201 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005202 mapstring = PyUnicode_AS_UNICODE(mapping);
5203 maplen = PyUnicode_GET_SIZE(mapping);
5204 while (s < e) {
5205 unsigned char ch = *s;
5206 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005207
Benjamin Peterson29060642009-01-31 22:14:21 +00005208 if (ch < maplen)
5209 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005210
Benjamin Peterson29060642009-01-31 22:14:21 +00005211 if (x == 0xfffe) {
5212 /* undefined mapping */
5213 outpos = p-PyUnicode_AS_UNICODE(v);
5214 startinpos = s-starts;
5215 endinpos = startinpos+1;
5216 if (unicode_decode_call_errorhandler(
5217 errors, &errorHandler,
5218 "charmap", "character maps to <undefined>",
5219 &starts, &e, &startinpos, &endinpos, &exc, &s,
5220 &v, &outpos, &p)) {
5221 goto onError;
5222 }
5223 continue;
5224 }
5225 *p++ = x;
5226 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005227 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005228 }
5229 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005230 while (s < e) {
5231 unsigned char ch = *s;
5232 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005233
Benjamin Peterson29060642009-01-31 22:14:21 +00005234 /* Get mapping (char ordinal -> integer, Unicode char or None) */
5235 w = PyLong_FromLong((long)ch);
5236 if (w == NULL)
5237 goto onError;
5238 x = PyObject_GetItem(mapping, w);
5239 Py_DECREF(w);
5240 if (x == NULL) {
5241 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5242 /* No mapping found means: mapping is undefined. */
5243 PyErr_Clear();
5244 x = Py_None;
5245 Py_INCREF(x);
5246 } else
5247 goto onError;
5248 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005249
Benjamin Peterson29060642009-01-31 22:14:21 +00005250 /* Apply mapping */
5251 if (PyLong_Check(x)) {
5252 long value = PyLong_AS_LONG(x);
5253 if (value < 0 || value > 65535) {
5254 PyErr_SetString(PyExc_TypeError,
5255 "character mapping must be in range(65536)");
5256 Py_DECREF(x);
5257 goto onError;
5258 }
5259 *p++ = (Py_UNICODE)value;
5260 }
5261 else if (x == Py_None) {
5262 /* undefined mapping */
5263 outpos = p-PyUnicode_AS_UNICODE(v);
5264 startinpos = s-starts;
5265 endinpos = startinpos+1;
5266 if (unicode_decode_call_errorhandler(
5267 errors, &errorHandler,
5268 "charmap", "character maps to <undefined>",
5269 &starts, &e, &startinpos, &endinpos, &exc, &s,
5270 &v, &outpos, &p)) {
5271 Py_DECREF(x);
5272 goto onError;
5273 }
5274 Py_DECREF(x);
5275 continue;
5276 }
5277 else if (PyUnicode_Check(x)) {
5278 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005279
Benjamin Peterson29060642009-01-31 22:14:21 +00005280 if (targetsize == 1)
5281 /* 1-1 mapping */
5282 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005283
Benjamin Peterson29060642009-01-31 22:14:21 +00005284 else if (targetsize > 1) {
5285 /* 1-n mapping */
5286 if (targetsize > extrachars) {
5287 /* resize first */
5288 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
5289 Py_ssize_t needed = (targetsize - extrachars) + \
5290 (targetsize << 2);
5291 extrachars += needed;
5292 /* XXX overflow detection missing */
5293 if (_PyUnicode_Resize(&v,
5294 PyUnicode_GET_SIZE(v) + needed) < 0) {
5295 Py_DECREF(x);
5296 goto onError;
5297 }
5298 p = PyUnicode_AS_UNICODE(v) + oldpos;
5299 }
5300 Py_UNICODE_COPY(p,
5301 PyUnicode_AS_UNICODE(x),
5302 targetsize);
5303 p += targetsize;
5304 extrachars -= targetsize;
5305 }
5306 /* 1-0 mapping: skip the character */
5307 }
5308 else {
5309 /* wrong return value */
5310 PyErr_SetString(PyExc_TypeError,
5311 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00005312 Py_DECREF(x);
5313 goto onError;
5314 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005315 Py_DECREF(x);
5316 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005317 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005318 }
5319 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00005320 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
5321 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005322 Py_XDECREF(errorHandler);
5323 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005324 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00005325
Benjamin Peterson29060642009-01-31 22:14:21 +00005326 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005327 Py_XDECREF(errorHandler);
5328 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005329 Py_XDECREF(v);
5330 return NULL;
5331}
5332
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005333/* Charmap encoding: the lookup table */
5334
5335struct encoding_map{
Benjamin Peterson29060642009-01-31 22:14:21 +00005336 PyObject_HEAD
5337 unsigned char level1[32];
5338 int count2, count3;
5339 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005340};
5341
5342static PyObject*
5343encoding_map_size(PyObject *obj, PyObject* args)
5344{
5345 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005346 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00005347 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005348}
5349
5350static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005351 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00005352 PyDoc_STR("Return the size (in bytes) of this object") },
5353 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005354};
5355
5356static void
5357encoding_map_dealloc(PyObject* o)
5358{
Benjamin Peterson14339b62009-01-31 16:36:08 +00005359 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005360}
5361
5362static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005363 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005364 "EncodingMap", /*tp_name*/
5365 sizeof(struct encoding_map), /*tp_basicsize*/
5366 0, /*tp_itemsize*/
5367 /* methods */
5368 encoding_map_dealloc, /*tp_dealloc*/
5369 0, /*tp_print*/
5370 0, /*tp_getattr*/
5371 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00005372 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00005373 0, /*tp_repr*/
5374 0, /*tp_as_number*/
5375 0, /*tp_as_sequence*/
5376 0, /*tp_as_mapping*/
5377 0, /*tp_hash*/
5378 0, /*tp_call*/
5379 0, /*tp_str*/
5380 0, /*tp_getattro*/
5381 0, /*tp_setattro*/
5382 0, /*tp_as_buffer*/
5383 Py_TPFLAGS_DEFAULT, /*tp_flags*/
5384 0, /*tp_doc*/
5385 0, /*tp_traverse*/
5386 0, /*tp_clear*/
5387 0, /*tp_richcompare*/
5388 0, /*tp_weaklistoffset*/
5389 0, /*tp_iter*/
5390 0, /*tp_iternext*/
5391 encoding_map_methods, /*tp_methods*/
5392 0, /*tp_members*/
5393 0, /*tp_getset*/
5394 0, /*tp_base*/
5395 0, /*tp_dict*/
5396 0, /*tp_descr_get*/
5397 0, /*tp_descr_set*/
5398 0, /*tp_dictoffset*/
5399 0, /*tp_init*/
5400 0, /*tp_alloc*/
5401 0, /*tp_new*/
5402 0, /*tp_free*/
5403 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005404};
5405
5406PyObject*
5407PyUnicode_BuildEncodingMap(PyObject* string)
5408{
5409 Py_UNICODE *decode;
5410 PyObject *result;
5411 struct encoding_map *mresult;
5412 int i;
5413 int need_dict = 0;
5414 unsigned char level1[32];
5415 unsigned char level2[512];
5416 unsigned char *mlevel1, *mlevel2, *mlevel3;
5417 int count2 = 0, count3 = 0;
5418
5419 if (!PyUnicode_Check(string) || PyUnicode_GetSize(string) != 256) {
5420 PyErr_BadArgument();
5421 return NULL;
5422 }
5423 decode = PyUnicode_AS_UNICODE(string);
5424 memset(level1, 0xFF, sizeof level1);
5425 memset(level2, 0xFF, sizeof level2);
5426
5427 /* If there isn't a one-to-one mapping of NULL to \0,
5428 or if there are non-BMP characters, we need to use
5429 a mapping dictionary. */
5430 if (decode[0] != 0)
5431 need_dict = 1;
5432 for (i = 1; i < 256; i++) {
5433 int l1, l2;
5434 if (decode[i] == 0
Benjamin Peterson29060642009-01-31 22:14:21 +00005435#ifdef Py_UNICODE_WIDE
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005436 || decode[i] > 0xFFFF
Benjamin Peterson29060642009-01-31 22:14:21 +00005437#endif
5438 ) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005439 need_dict = 1;
5440 break;
5441 }
5442 if (decode[i] == 0xFFFE)
5443 /* unmapped character */
5444 continue;
5445 l1 = decode[i] >> 11;
5446 l2 = decode[i] >> 7;
5447 if (level1[l1] == 0xFF)
5448 level1[l1] = count2++;
5449 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00005450 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005451 }
5452
5453 if (count2 >= 0xFF || count3 >= 0xFF)
5454 need_dict = 1;
5455
5456 if (need_dict) {
5457 PyObject *result = PyDict_New();
5458 PyObject *key, *value;
5459 if (!result)
5460 return NULL;
5461 for (i = 0; i < 256; i++) {
5462 key = value = NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00005463 key = PyLong_FromLong(decode[i]);
5464 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005465 if (!key || !value)
5466 goto failed1;
5467 if (PyDict_SetItem(result, key, value) == -1)
5468 goto failed1;
5469 Py_DECREF(key);
5470 Py_DECREF(value);
5471 }
5472 return result;
5473 failed1:
5474 Py_XDECREF(key);
5475 Py_XDECREF(value);
5476 Py_DECREF(result);
5477 return NULL;
5478 }
5479
5480 /* Create a three-level trie */
5481 result = PyObject_MALLOC(sizeof(struct encoding_map) +
5482 16*count2 + 128*count3 - 1);
5483 if (!result)
5484 return PyErr_NoMemory();
5485 PyObject_Init(result, &EncodingMapType);
5486 mresult = (struct encoding_map*)result;
5487 mresult->count2 = count2;
5488 mresult->count3 = count3;
5489 mlevel1 = mresult->level1;
5490 mlevel2 = mresult->level23;
5491 mlevel3 = mresult->level23 + 16*count2;
5492 memcpy(mlevel1, level1, 32);
5493 memset(mlevel2, 0xFF, 16*count2);
5494 memset(mlevel3, 0, 128*count3);
5495 count3 = 0;
5496 for (i = 1; i < 256; i++) {
5497 int o1, o2, o3, i2, i3;
5498 if (decode[i] == 0xFFFE)
5499 /* unmapped character */
5500 continue;
5501 o1 = decode[i]>>11;
5502 o2 = (decode[i]>>7) & 0xF;
5503 i2 = 16*mlevel1[o1] + o2;
5504 if (mlevel2[i2] == 0xFF)
5505 mlevel2[i2] = count3++;
5506 o3 = decode[i] & 0x7F;
5507 i3 = 128*mlevel2[i2] + o3;
5508 mlevel3[i3] = i;
5509 }
5510 return result;
5511}
5512
5513static int
5514encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
5515{
5516 struct encoding_map *map = (struct encoding_map*)mapping;
5517 int l1 = c>>11;
5518 int l2 = (c>>7) & 0xF;
5519 int l3 = c & 0x7F;
5520 int i;
5521
5522#ifdef Py_UNICODE_WIDE
5523 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005524 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005525 }
5526#endif
5527 if (c == 0)
5528 return 0;
5529 /* level 1*/
5530 i = map->level1[l1];
5531 if (i == 0xFF) {
5532 return -1;
5533 }
5534 /* level 2*/
5535 i = map->level23[16*i+l2];
5536 if (i == 0xFF) {
5537 return -1;
5538 }
5539 /* level 3 */
5540 i = map->level23[16*map->count2 + 128*i + l3];
5541 if (i == 0) {
5542 return -1;
5543 }
5544 return i;
5545}
5546
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005547/* Lookup the character ch in the mapping. If the character
5548 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00005549 error occurred). */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005550static PyObject *charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005551{
Christian Heimes217cfd12007-12-02 14:31:20 +00005552 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005553 PyObject *x;
5554
5555 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005556 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005557 x = PyObject_GetItem(mapping, w);
5558 Py_DECREF(w);
5559 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005560 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5561 /* No mapping found means: mapping is undefined. */
5562 PyErr_Clear();
5563 x = Py_None;
5564 Py_INCREF(x);
5565 return x;
5566 } else
5567 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005568 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00005569 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00005570 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00005571 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005572 long value = PyLong_AS_LONG(x);
5573 if (value < 0 || value > 255) {
5574 PyErr_SetString(PyExc_TypeError,
5575 "character mapping must be in range(256)");
5576 Py_DECREF(x);
5577 return NULL;
5578 }
5579 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005580 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005581 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00005582 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005583 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005584 /* wrong return value */
5585 PyErr_Format(PyExc_TypeError,
5586 "character mapping must return integer, bytes or None, not %.400s",
5587 x->ob_type->tp_name);
5588 Py_DECREF(x);
5589 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005590 }
5591}
5592
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005593static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00005594charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005595{
Benjamin Peterson14339b62009-01-31 16:36:08 +00005596 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
5597 /* exponentially overallocate to minimize reallocations */
5598 if (requiredsize < 2*outsize)
5599 requiredsize = 2*outsize;
5600 if (_PyBytes_Resize(outobj, requiredsize))
5601 return -1;
5602 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005603}
5604
Benjamin Peterson14339b62009-01-31 16:36:08 +00005605typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00005606 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005607}charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005608/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00005609 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005610 space is available. Return a new reference to the object that
5611 was put in the output buffer, or Py_None, if the mapping was undefined
5612 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00005613 reallocation error occurred. The caller must decref the result */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005614static
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005615charmapencode_result charmapencode_output(Py_UNICODE c, PyObject *mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00005616 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005617{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005618 PyObject *rep;
5619 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00005620 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005621
Christian Heimes90aa7642007-12-19 02:45:37 +00005622 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005623 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00005624 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005625 if (res == -1)
5626 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00005627 if (outsize<requiredsize)
5628 if (charmapencode_resize(outobj, outpos, requiredsize))
5629 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00005630 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005631 outstart[(*outpos)++] = (char)res;
5632 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005633 }
5634
5635 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005636 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005637 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005638 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005639 Py_DECREF(rep);
5640 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005641 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005642 if (PyLong_Check(rep)) {
5643 Py_ssize_t requiredsize = *outpos+1;
5644 if (outsize<requiredsize)
5645 if (charmapencode_resize(outobj, outpos, requiredsize)) {
5646 Py_DECREF(rep);
5647 return enc_EXCEPTION;
5648 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005649 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005650 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005651 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005652 else {
5653 const char *repchars = PyBytes_AS_STRING(rep);
5654 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
5655 Py_ssize_t requiredsize = *outpos+repsize;
5656 if (outsize<requiredsize)
5657 if (charmapencode_resize(outobj, outpos, requiredsize)) {
5658 Py_DECREF(rep);
5659 return enc_EXCEPTION;
5660 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005661 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005662 memcpy(outstart + *outpos, repchars, repsize);
5663 *outpos += repsize;
5664 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005665 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005666 Py_DECREF(rep);
5667 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005668}
5669
5670/* handle an error in PyUnicode_EncodeCharmap
5671 Return 0 on success, -1 on error */
5672static
5673int charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00005674 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005675 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00005676 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00005677 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005678{
5679 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005680 Py_ssize_t repsize;
5681 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005682 Py_UNICODE *uni2;
5683 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005684 Py_ssize_t collstartpos = *inpos;
5685 Py_ssize_t collendpos = *inpos+1;
5686 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005687 char *encoding = "charmap";
5688 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005689 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005690
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005691 /* find all unencodable characters */
5692 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005693 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00005694 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005695 int res = encoding_map_lookup(p[collendpos], mapping);
5696 if (res != -1)
5697 break;
5698 ++collendpos;
5699 continue;
5700 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005701
Benjamin Peterson29060642009-01-31 22:14:21 +00005702 rep = charmapencode_lookup(p[collendpos], mapping);
5703 if (rep==NULL)
5704 return -1;
5705 else if (rep!=Py_None) {
5706 Py_DECREF(rep);
5707 break;
5708 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005709 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00005710 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005711 }
5712 /* cache callback name lookup
5713 * (if not done yet, i.e. it's the first error) */
5714 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005715 if ((errors==NULL) || (!strcmp(errors, "strict")))
5716 *known_errorHandler = 1;
5717 else if (!strcmp(errors, "replace"))
5718 *known_errorHandler = 2;
5719 else if (!strcmp(errors, "ignore"))
5720 *known_errorHandler = 3;
5721 else if (!strcmp(errors, "xmlcharrefreplace"))
5722 *known_errorHandler = 4;
5723 else
5724 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005725 }
5726 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005727 case 1: /* strict */
5728 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5729 return -1;
5730 case 2: /* replace */
5731 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005732 x = charmapencode_output('?', mapping, res, respos);
5733 if (x==enc_EXCEPTION) {
5734 return -1;
5735 }
5736 else if (x==enc_FAILED) {
5737 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5738 return -1;
5739 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005740 }
5741 /* fall through */
5742 case 3: /* ignore */
5743 *inpos = collendpos;
5744 break;
5745 case 4: /* xmlcharrefreplace */
5746 /* generate replacement (temporarily (mis)uses p) */
5747 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005748 char buffer[2+29+1+1];
5749 char *cp;
5750 sprintf(buffer, "&#%d;", (int)p[collpos]);
5751 for (cp = buffer; *cp; ++cp) {
5752 x = charmapencode_output(*cp, mapping, res, respos);
5753 if (x==enc_EXCEPTION)
5754 return -1;
5755 else if (x==enc_FAILED) {
5756 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5757 return -1;
5758 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005759 }
5760 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005761 *inpos = collendpos;
5762 break;
5763 default:
5764 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00005765 encoding, reason, p, size, exceptionObject,
5766 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005767 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005768 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005769 if (PyBytes_Check(repunicode)) {
5770 /* Directly copy bytes result to output. */
5771 Py_ssize_t outsize = PyBytes_Size(*res);
5772 Py_ssize_t requiredsize;
5773 repsize = PyBytes_Size(repunicode);
5774 requiredsize = *respos + repsize;
5775 if (requiredsize > outsize)
5776 /* Make room for all additional bytes. */
5777 if (charmapencode_resize(res, respos, requiredsize)) {
5778 Py_DECREF(repunicode);
5779 return -1;
5780 }
5781 memcpy(PyBytes_AsString(*res) + *respos,
5782 PyBytes_AsString(repunicode), repsize);
5783 *respos += repsize;
5784 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005785 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00005786 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005787 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005788 /* generate replacement */
5789 repsize = PyUnicode_GET_SIZE(repunicode);
5790 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005791 x = charmapencode_output(*uni2, mapping, res, respos);
5792 if (x==enc_EXCEPTION) {
5793 return -1;
5794 }
5795 else if (x==enc_FAILED) {
5796 Py_DECREF(repunicode);
5797 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5798 return -1;
5799 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005800 }
5801 *inpos = newpos;
5802 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005803 }
5804 return 0;
5805}
5806
Guido van Rossumd57fd912000-03-10 22:53:23 +00005807PyObject *PyUnicode_EncodeCharmap(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00005808 Py_ssize_t size,
5809 PyObject *mapping,
5810 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005811{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005812 /* output object */
5813 PyObject *res = NULL;
5814 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005815 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005816 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005817 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005818 PyObject *errorHandler = NULL;
5819 PyObject *exc = NULL;
5820 /* the following variable is used for caching string comparisons
5821 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
5822 * 3=ignore, 4=xmlcharrefreplace */
5823 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005824
5825 /* Default to Latin-1 */
5826 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005827 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005828
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005829 /* allocate enough for a simple encoding without
5830 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00005831 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005832 if (res == NULL)
5833 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00005834 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005835 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005836
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005837 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005838 /* try to encode it */
5839 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
5840 if (x==enc_EXCEPTION) /* error */
5841 goto onError;
5842 if (x==enc_FAILED) { /* unencodable character */
5843 if (charmap_encoding_error(p, size, &inpos, mapping,
5844 &exc,
5845 &known_errorHandler, &errorHandler, errors,
5846 &res, &respos)) {
5847 goto onError;
5848 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005849 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005850 else
5851 /* done with this character => adjust input position */
5852 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005853 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005854
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005855 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00005856 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005857 if (_PyBytes_Resize(&res, respos) < 0)
5858 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005859
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005860 Py_XDECREF(exc);
5861 Py_XDECREF(errorHandler);
5862 return res;
5863
Benjamin Peterson29060642009-01-31 22:14:21 +00005864 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005865 Py_XDECREF(res);
5866 Py_XDECREF(exc);
5867 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005868 return NULL;
5869}
5870
5871PyObject *PyUnicode_AsCharmapString(PyObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00005872 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005873{
5874 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005875 PyErr_BadArgument();
5876 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005877 }
5878 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005879 PyUnicode_GET_SIZE(unicode),
5880 mapping,
5881 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005882}
5883
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005884/* create or adjust a UnicodeTranslateError */
5885static void make_translate_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005886 const Py_UNICODE *unicode, Py_ssize_t size,
5887 Py_ssize_t startpos, Py_ssize_t endpos,
5888 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005889{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005890 if (*exceptionObject == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005891 *exceptionObject = PyUnicodeTranslateError_Create(
Benjamin Peterson29060642009-01-31 22:14:21 +00005892 unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005893 }
5894 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005895 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
5896 goto onError;
5897 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
5898 goto onError;
5899 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
5900 goto onError;
5901 return;
5902 onError:
5903 Py_DECREF(*exceptionObject);
5904 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005905 }
5906}
5907
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005908/* raises a UnicodeTranslateError */
5909static void raise_translate_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005910 const Py_UNICODE *unicode, Py_ssize_t size,
5911 Py_ssize_t startpos, Py_ssize_t endpos,
5912 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005913{
5914 make_translate_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005915 unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005916 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005917 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005918}
5919
5920/* error handling callback helper:
5921 build arguments, call the callback and check the arguments,
5922 put the result into newpos and return the replacement string, which
5923 has to be freed by the caller */
5924static PyObject *unicode_translate_call_errorhandler(const char *errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00005925 PyObject **errorHandler,
5926 const char *reason,
5927 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
5928 Py_ssize_t startpos, Py_ssize_t endpos,
5929 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005930{
Benjamin Peterson142957c2008-07-04 19:55:29 +00005931 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005932
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005933 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005934 PyObject *restuple;
5935 PyObject *resunicode;
5936
5937 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005938 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005939 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005940 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005941 }
5942
5943 make_translate_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005944 unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005945 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005946 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005947
5948 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00005949 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005950 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005951 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005952 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00005953 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00005954 Py_DECREF(restuple);
5955 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005956 }
5957 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00005958 &resunicode, &i_newpos)) {
5959 Py_DECREF(restuple);
5960 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005961 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00005962 if (i_newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005963 *newpos = size+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005964 else
5965 *newpos = i_newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005966 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005967 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
5968 Py_DECREF(restuple);
5969 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005970 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005971 Py_INCREF(resunicode);
5972 Py_DECREF(restuple);
5973 return resunicode;
5974}
5975
5976/* Lookup the character ch in the mapping and put the result in result,
5977 which must be decrefed by the caller.
5978 Return 0 on success, -1 on error */
5979static
5980int charmaptranslate_lookup(Py_UNICODE c, PyObject *mapping, PyObject **result)
5981{
Christian Heimes217cfd12007-12-02 14:31:20 +00005982 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005983 PyObject *x;
5984
5985 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005986 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005987 x = PyObject_GetItem(mapping, w);
5988 Py_DECREF(w);
5989 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005990 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5991 /* No mapping found means: use 1:1 mapping. */
5992 PyErr_Clear();
5993 *result = NULL;
5994 return 0;
5995 } else
5996 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005997 }
5998 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005999 *result = x;
6000 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006001 }
Christian Heimes217cfd12007-12-02 14:31:20 +00006002 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006003 long value = PyLong_AS_LONG(x);
6004 long max = PyUnicode_GetMax();
6005 if (value < 0 || value > max) {
6006 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00006007 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00006008 Py_DECREF(x);
6009 return -1;
6010 }
6011 *result = x;
6012 return 0;
6013 }
6014 else if (PyUnicode_Check(x)) {
6015 *result = x;
6016 return 0;
6017 }
6018 else {
6019 /* wrong return value */
6020 PyErr_SetString(PyExc_TypeError,
6021 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00006022 Py_DECREF(x);
6023 return -1;
6024 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006025}
6026/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00006027 if not reallocate and adjust various state variables.
6028 Return 0 on success, -1 on error */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006029static
Walter Dörwald4894c302003-10-24 14:25:28 +00006030int charmaptranslate_makespace(PyObject **outobj, Py_UNICODE **outp,
Benjamin Peterson29060642009-01-31 22:14:21 +00006031 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006032{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006033 Py_ssize_t oldsize = PyUnicode_GET_SIZE(*outobj);
Walter Dörwald4894c302003-10-24 14:25:28 +00006034 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006035 /* remember old output position */
6036 Py_ssize_t outpos = *outp-PyUnicode_AS_UNICODE(*outobj);
6037 /* exponentially overallocate to minimize reallocations */
6038 if (requiredsize < 2 * oldsize)
6039 requiredsize = 2 * oldsize;
6040 if (PyUnicode_Resize(outobj, requiredsize) < 0)
6041 return -1;
6042 *outp = PyUnicode_AS_UNICODE(*outobj) + outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006043 }
6044 return 0;
6045}
6046/* lookup the character, put the result in the output string and adjust
6047 various state variables. Return a new reference to the object that
6048 was put in the output buffer in *result, or Py_None, if the mapping was
6049 undefined (in which case no character was written).
6050 The called must decref result.
6051 Return 0 on success, -1 on error. */
6052static
Walter Dörwald4894c302003-10-24 14:25:28 +00006053int charmaptranslate_output(const Py_UNICODE *startinp, const Py_UNICODE *curinp,
Benjamin Peterson29060642009-01-31 22:14:21 +00006054 Py_ssize_t insize, PyObject *mapping, PyObject **outobj, Py_UNICODE **outp,
6055 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006056{
Walter Dörwald4894c302003-10-24 14:25:28 +00006057 if (charmaptranslate_lookup(*curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00006058 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006059 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006060 /* not found => default to 1:1 mapping */
6061 *(*outp)++ = *curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006062 }
6063 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00006064 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00006065 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006066 /* no overflow check, because we know that the space is enough */
6067 *(*outp)++ = (Py_UNICODE)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006068 }
6069 else if (PyUnicode_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006070 Py_ssize_t repsize = PyUnicode_GET_SIZE(*res);
6071 if (repsize==1) {
6072 /* no overflow check, because we know that the space is enough */
6073 *(*outp)++ = *PyUnicode_AS_UNICODE(*res);
6074 }
6075 else if (repsize!=0) {
6076 /* more than one character */
6077 Py_ssize_t requiredsize = (*outp-PyUnicode_AS_UNICODE(*outobj)) +
6078 (insize - (curinp-startinp)) +
6079 repsize - 1;
6080 if (charmaptranslate_makespace(outobj, outp, requiredsize))
6081 return -1;
6082 memcpy(*outp, PyUnicode_AS_UNICODE(*res), sizeof(Py_UNICODE)*repsize);
6083 *outp += repsize;
6084 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006085 }
6086 else
Benjamin Peterson29060642009-01-31 22:14:21 +00006087 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006088 return 0;
6089}
6090
6091PyObject *PyUnicode_TranslateCharmap(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00006092 Py_ssize_t size,
6093 PyObject *mapping,
6094 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006095{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006096 /* output object */
6097 PyObject *res = NULL;
6098 /* pointers to the beginning and end+1 of input */
6099 const Py_UNICODE *startp = p;
6100 const Py_UNICODE *endp = p + size;
6101 /* pointer into the output */
6102 Py_UNICODE *str;
6103 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006104 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006105 char *reason = "character maps to <undefined>";
6106 PyObject *errorHandler = NULL;
6107 PyObject *exc = NULL;
6108 /* the following variable is used for caching string comparisons
6109 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
6110 * 3=ignore, 4=xmlcharrefreplace */
6111 int known_errorHandler = -1;
6112
Guido van Rossumd57fd912000-03-10 22:53:23 +00006113 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006114 PyErr_BadArgument();
6115 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006116 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006117
6118 /* allocate enough for a simple 1:1 translation without
6119 replacements, if we need more, we'll resize */
6120 res = PyUnicode_FromUnicode(NULL, size);
6121 if (res == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006122 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006123 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006124 return res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006125 str = PyUnicode_AS_UNICODE(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006126
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006127 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006128 /* try to encode it */
6129 PyObject *x = NULL;
6130 if (charmaptranslate_output(startp, p, size, mapping, &res, &str, &x)) {
6131 Py_XDECREF(x);
6132 goto onError;
6133 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006134 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00006135 if (x!=Py_None) /* it worked => adjust input pointer */
6136 ++p;
6137 else { /* untranslatable character */
6138 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
6139 Py_ssize_t repsize;
6140 Py_ssize_t newpos;
6141 Py_UNICODE *uni2;
6142 /* startpos for collecting untranslatable chars */
6143 const Py_UNICODE *collstart = p;
6144 const Py_UNICODE *collend = p+1;
6145 const Py_UNICODE *coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006146
Benjamin Peterson29060642009-01-31 22:14:21 +00006147 /* find all untranslatable characters */
6148 while (collend < endp) {
6149 if (charmaptranslate_lookup(*collend, mapping, &x))
6150 goto onError;
6151 Py_XDECREF(x);
6152 if (x!=Py_None)
6153 break;
6154 ++collend;
6155 }
6156 /* cache callback name lookup
6157 * (if not done yet, i.e. it's the first error) */
6158 if (known_errorHandler==-1) {
6159 if ((errors==NULL) || (!strcmp(errors, "strict")))
6160 known_errorHandler = 1;
6161 else if (!strcmp(errors, "replace"))
6162 known_errorHandler = 2;
6163 else if (!strcmp(errors, "ignore"))
6164 known_errorHandler = 3;
6165 else if (!strcmp(errors, "xmlcharrefreplace"))
6166 known_errorHandler = 4;
6167 else
6168 known_errorHandler = 0;
6169 }
6170 switch (known_errorHandler) {
6171 case 1: /* strict */
6172 raise_translate_exception(&exc, startp, size, collstart-startp, collend-startp, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006173 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006174 case 2: /* replace */
6175 /* No need to check for space, this is a 1:1 replacement */
6176 for (coll = collstart; coll<collend; ++coll)
6177 *str++ = '?';
6178 /* fall through */
6179 case 3: /* ignore */
6180 p = collend;
6181 break;
6182 case 4: /* xmlcharrefreplace */
6183 /* generate replacement (temporarily (mis)uses p) */
6184 for (p = collstart; p < collend; ++p) {
6185 char buffer[2+29+1+1];
6186 char *cp;
6187 sprintf(buffer, "&#%d;", (int)*p);
6188 if (charmaptranslate_makespace(&res, &str,
6189 (str-PyUnicode_AS_UNICODE(res))+strlen(buffer)+(endp-collend)))
6190 goto onError;
6191 for (cp = buffer; *cp; ++cp)
6192 *str++ = *cp;
6193 }
6194 p = collend;
6195 break;
6196 default:
6197 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
6198 reason, startp, size, &exc,
6199 collstart-startp, collend-startp, &newpos);
6200 if (repunicode == NULL)
6201 goto onError;
6202 /* generate replacement */
6203 repsize = PyUnicode_GET_SIZE(repunicode);
6204 if (charmaptranslate_makespace(&res, &str,
6205 (str-PyUnicode_AS_UNICODE(res))+repsize+(endp-collend))) {
6206 Py_DECREF(repunicode);
6207 goto onError;
6208 }
6209 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2)
6210 *str++ = *uni2;
6211 p = startp + newpos;
6212 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006213 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006214 }
6215 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006216 /* Resize if we allocated to much */
6217 respos = str-PyUnicode_AS_UNICODE(res);
Walter Dörwald4894c302003-10-24 14:25:28 +00006218 if (respos<PyUnicode_GET_SIZE(res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006219 if (PyUnicode_Resize(&res, respos) < 0)
6220 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006221 }
6222 Py_XDECREF(exc);
6223 Py_XDECREF(errorHandler);
6224 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006225
Benjamin Peterson29060642009-01-31 22:14:21 +00006226 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006227 Py_XDECREF(res);
6228 Py_XDECREF(exc);
6229 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006230 return NULL;
6231}
6232
6233PyObject *PyUnicode_Translate(PyObject *str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006234 PyObject *mapping,
6235 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006236{
6237 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00006238
Guido van Rossumd57fd912000-03-10 22:53:23 +00006239 str = PyUnicode_FromObject(str);
6240 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006241 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006242 result = PyUnicode_TranslateCharmap(PyUnicode_AS_UNICODE(str),
Benjamin Peterson29060642009-01-31 22:14:21 +00006243 PyUnicode_GET_SIZE(str),
6244 mapping,
6245 errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006246 Py_DECREF(str);
6247 return result;
Tim Petersced69f82003-09-16 20:30:58 +00006248
Benjamin Peterson29060642009-01-31 22:14:21 +00006249 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006250 Py_XDECREF(str);
6251 return NULL;
6252}
Tim Petersced69f82003-09-16 20:30:58 +00006253
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00006254PyObject *
6255PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
6256 Py_ssize_t length)
6257{
6258 PyObject *result;
6259 Py_UNICODE *p; /* write pointer into result */
6260 Py_ssize_t i;
6261 /* Copy to a new string */
6262 result = (PyObject *)_PyUnicode_New(length);
6263 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
6264 if (result == NULL)
6265 return result;
6266 p = PyUnicode_AS_UNICODE(result);
6267 /* Iterate over code points */
6268 for (i = 0; i < length; i++) {
6269 Py_UNICODE ch =s[i];
6270 if (ch > 127) {
6271 int decimal = Py_UNICODE_TODECIMAL(ch);
6272 if (decimal >= 0)
6273 p[i] = '0' + decimal;
6274 }
6275 }
6276 return result;
6277}
Guido van Rossum9e896b32000-04-05 20:11:21 +00006278/* --- Decimal Encoder ---------------------------------------------------- */
6279
6280int PyUnicode_EncodeDecimal(Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00006281 Py_ssize_t length,
6282 char *output,
6283 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00006284{
6285 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006286 PyObject *errorHandler = NULL;
6287 PyObject *exc = NULL;
6288 const char *encoding = "decimal";
6289 const char *reason = "invalid decimal Unicode string";
6290 /* the following variable is used for caching string comparisons
6291 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6292 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00006293
6294 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006295 PyErr_BadArgument();
6296 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00006297 }
6298
6299 p = s;
6300 end = s + length;
6301 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006302 register Py_UNICODE ch = *p;
6303 int decimal;
6304 PyObject *repunicode;
6305 Py_ssize_t repsize;
6306 Py_ssize_t newpos;
6307 Py_UNICODE *uni2;
6308 Py_UNICODE *collstart;
6309 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00006310
Benjamin Peterson29060642009-01-31 22:14:21 +00006311 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006312 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00006313 ++p;
6314 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006315 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006316 decimal = Py_UNICODE_TODECIMAL(ch);
6317 if (decimal >= 0) {
6318 *output++ = '0' + decimal;
6319 ++p;
6320 continue;
6321 }
6322 if (0 < ch && ch < 256) {
6323 *output++ = (char)ch;
6324 ++p;
6325 continue;
6326 }
6327 /* All other characters are considered unencodable */
6328 collstart = p;
Victor Stinnerab1d16b2011-11-22 01:45:37 +01006329 for (collend = p+1; collend < end; collend++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006330 if ((0 < *collend && *collend < 256) ||
Victor Stinnerab1d16b2011-11-22 01:45:37 +01006331 Py_UNICODE_ISSPACE(*collend) ||
6332 0 <= Py_UNICODE_TODECIMAL(*collend))
Benjamin Peterson29060642009-01-31 22:14:21 +00006333 break;
6334 }
6335 /* cache callback name lookup
6336 * (if not done yet, i.e. it's the first error) */
6337 if (known_errorHandler==-1) {
6338 if ((errors==NULL) || (!strcmp(errors, "strict")))
6339 known_errorHandler = 1;
6340 else if (!strcmp(errors, "replace"))
6341 known_errorHandler = 2;
6342 else if (!strcmp(errors, "ignore"))
6343 known_errorHandler = 3;
6344 else if (!strcmp(errors, "xmlcharrefreplace"))
6345 known_errorHandler = 4;
6346 else
6347 known_errorHandler = 0;
6348 }
6349 switch (known_errorHandler) {
6350 case 1: /* strict */
6351 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
6352 goto onError;
6353 case 2: /* replace */
6354 for (p = collstart; p < collend; ++p)
6355 *output++ = '?';
6356 /* fall through */
6357 case 3: /* ignore */
6358 p = collend;
6359 break;
6360 case 4: /* xmlcharrefreplace */
6361 /* generate replacement (temporarily (mis)uses p) */
6362 for (p = collstart; p < collend; ++p)
6363 output += sprintf(output, "&#%d;", (int)*p);
6364 p = collend;
6365 break;
6366 default:
6367 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
6368 encoding, reason, s, length, &exc,
6369 collstart-s, collend-s, &newpos);
6370 if (repunicode == NULL)
6371 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006372 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006373 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006374 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
6375 Py_DECREF(repunicode);
6376 goto onError;
6377 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006378 /* generate replacement */
6379 repsize = PyUnicode_GET_SIZE(repunicode);
6380 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
6381 Py_UNICODE ch = *uni2;
6382 if (Py_UNICODE_ISSPACE(ch))
6383 *output++ = ' ';
6384 else {
6385 decimal = Py_UNICODE_TODECIMAL(ch);
6386 if (decimal >= 0)
6387 *output++ = '0' + decimal;
6388 else if (0 < ch && ch < 256)
6389 *output++ = (char)ch;
6390 else {
6391 Py_DECREF(repunicode);
6392 raise_encode_exception(&exc, encoding,
6393 s, length, collstart-s, collend-s, reason);
6394 goto onError;
6395 }
6396 }
6397 }
6398 p = s + newpos;
6399 Py_DECREF(repunicode);
6400 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00006401 }
6402 /* 0-terminate the output string */
6403 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006404 Py_XDECREF(exc);
6405 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00006406 return 0;
6407
Benjamin Peterson29060642009-01-31 22:14:21 +00006408 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006409 Py_XDECREF(exc);
6410 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00006411 return -1;
6412}
6413
Guido van Rossumd57fd912000-03-10 22:53:23 +00006414/* --- Helpers ------------------------------------------------------------ */
6415
Eric Smith8c663262007-08-25 02:26:07 +00006416#include "stringlib/unicodedefs.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00006417#include "stringlib/fastsearch.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006418
Thomas Wouters477c8d52006-05-27 19:21:47 +00006419#include "stringlib/count.h"
6420#include "stringlib/find.h"
6421#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006422#include "stringlib/split.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00006423
Eric Smith5807c412008-05-11 21:00:57 +00006424#define _Py_InsertThousandsGrouping _PyUnicode_InsertThousandsGrouping
Eric Smitha3b1ac82009-04-03 14:45:06 +00006425#define _Py_InsertThousandsGroupingLocale _PyUnicode_InsertThousandsGroupingLocale
Eric Smith5807c412008-05-11 21:00:57 +00006426#include "stringlib/localeutil.h"
6427
Thomas Wouters477c8d52006-05-27 19:21:47 +00006428/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006429#define ADJUST_INDICES(start, end, len) \
6430 if (end > len) \
6431 end = len; \
6432 else if (end < 0) { \
6433 end += len; \
6434 if (end < 0) \
6435 end = 0; \
6436 } \
6437 if (start < 0) { \
6438 start += len; \
6439 if (start < 0) \
6440 start = 0; \
6441 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00006442
Ezio Melotti93e7afc2011-08-22 14:08:38 +03006443/* _Py_UNICODE_NEXT is a private macro used to retrieve the character pointed
6444 * by 'ptr', possibly combining surrogate pairs on narrow builds.
6445 * 'ptr' and 'end' must be Py_UNICODE*, with 'ptr' pointing at the character
6446 * that should be returned and 'end' pointing to the end of the buffer.
6447 * ('end' is used on narrow builds to detect a lone surrogate at the
6448 * end of the buffer that should be returned unchanged.)
6449 * The ptr and end arguments should be side-effect free and ptr must an lvalue.
6450 * The type of the returned char is always Py_UCS4.
6451 *
6452 * Note: the macro advances ptr to next char, so it might have side-effects
6453 * (especially if used with other macros).
6454 */
6455
6456/* helper macros used by _Py_UNICODE_NEXT */
6457#define _Py_UNICODE_IS_HIGH_SURROGATE(ch) (0xD800 <= ch && ch <= 0xDBFF)
6458#define _Py_UNICODE_IS_LOW_SURROGATE(ch) (0xDC00 <= ch && ch <= 0xDFFF)
6459/* Join two surrogate characters and return a single Py_UCS4 value. */
6460#define _Py_UNICODE_JOIN_SURROGATES(high, low) \
6461 (((((Py_UCS4)(high) & 0x03FF) << 10) | \
6462 ((Py_UCS4)(low) & 0x03FF)) + 0x10000)
6463
6464#ifdef Py_UNICODE_WIDE
6465#define _Py_UNICODE_NEXT(ptr, end) *(ptr)++
6466#else
6467#define _Py_UNICODE_NEXT(ptr, end) \
6468 (((_Py_UNICODE_IS_HIGH_SURROGATE(*(ptr)) && (ptr) < (end)) && \
6469 _Py_UNICODE_IS_LOW_SURROGATE((ptr)[1])) ? \
6470 ((ptr) += 2,_Py_UNICODE_JOIN_SURROGATES((ptr)[-2], (ptr)[-1])) : \
6471 (Py_UCS4)*(ptr)++)
6472#endif
6473
Martin v. Löwis18e16552006-02-15 17:27:45 +00006474Py_ssize_t PyUnicode_Count(PyObject *str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00006475 PyObject *substr,
6476 Py_ssize_t start,
6477 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006478{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006479 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006480 PyUnicodeObject* str_obj;
6481 PyUnicodeObject* sub_obj;
Tim Petersced69f82003-09-16 20:30:58 +00006482
Thomas Wouters477c8d52006-05-27 19:21:47 +00006483 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
6484 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00006485 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006486 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
6487 if (!sub_obj) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006488 Py_DECREF(str_obj);
6489 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006490 }
Tim Petersced69f82003-09-16 20:30:58 +00006491
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006492 ADJUST_INDICES(start, end, str_obj->length);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006493 result = stringlib_count(
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006494 str_obj->str + start, end - start, sub_obj->str, sub_obj->length,
6495 PY_SSIZE_T_MAX
Thomas Wouters477c8d52006-05-27 19:21:47 +00006496 );
6497
6498 Py_DECREF(sub_obj);
6499 Py_DECREF(str_obj);
6500
Guido van Rossumd57fd912000-03-10 22:53:23 +00006501 return result;
6502}
6503
Martin v. Löwis18e16552006-02-15 17:27:45 +00006504Py_ssize_t PyUnicode_Find(PyObject *str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00006505 PyObject *sub,
6506 Py_ssize_t start,
6507 Py_ssize_t end,
6508 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006509{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006510 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00006511
Guido van Rossumd57fd912000-03-10 22:53:23 +00006512 str = PyUnicode_FromObject(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006513 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00006514 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006515 sub = PyUnicode_FromObject(sub);
6516 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006517 Py_DECREF(str);
6518 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006519 }
Tim Petersced69f82003-09-16 20:30:58 +00006520
Thomas Wouters477c8d52006-05-27 19:21:47 +00006521 if (direction > 0)
6522 result = stringlib_find_slice(
6523 PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
6524 PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
6525 start, end
6526 );
6527 else
6528 result = stringlib_rfind_slice(
6529 PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
6530 PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
6531 start, end
6532 );
6533
Guido van Rossumd57fd912000-03-10 22:53:23 +00006534 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006535 Py_DECREF(sub);
6536
Guido van Rossumd57fd912000-03-10 22:53:23 +00006537 return result;
6538}
6539
Tim Petersced69f82003-09-16 20:30:58 +00006540static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006541int tailmatch(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006542 PyUnicodeObject *substring,
6543 Py_ssize_t start,
6544 Py_ssize_t end,
6545 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006546{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006547 if (substring->length == 0)
6548 return 1;
6549
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006550 ADJUST_INDICES(start, end, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006551 end -= substring->length;
6552 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00006553 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006554
6555 if (direction > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006556 if (Py_UNICODE_MATCH(self, end, substring))
6557 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006558 } else {
6559 if (Py_UNICODE_MATCH(self, start, substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00006560 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006561 }
6562
6563 return 0;
6564}
6565
Martin v. Löwis18e16552006-02-15 17:27:45 +00006566Py_ssize_t PyUnicode_Tailmatch(PyObject *str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006567 PyObject *substr,
6568 Py_ssize_t start,
6569 Py_ssize_t end,
6570 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006571{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006572 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00006573
Guido van Rossumd57fd912000-03-10 22:53:23 +00006574 str = PyUnicode_FromObject(str);
6575 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006576 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006577 substr = PyUnicode_FromObject(substr);
6578 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006579 Py_DECREF(str);
6580 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006581 }
Tim Petersced69f82003-09-16 20:30:58 +00006582
Guido van Rossumd57fd912000-03-10 22:53:23 +00006583 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006584 (PyUnicodeObject *)substr,
6585 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006586 Py_DECREF(str);
6587 Py_DECREF(substr);
6588 return result;
6589}
6590
Guido van Rossumd57fd912000-03-10 22:53:23 +00006591/* Apply fixfct filter to the Unicode object self and return a
6592 reference to the modified object */
6593
Tim Petersced69f82003-09-16 20:30:58 +00006594static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006595PyObject *fixup(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006596 int (*fixfct)(PyUnicodeObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00006597{
6598
6599 PyUnicodeObject *u;
6600
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006601 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006602 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006603 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006604
6605 Py_UNICODE_COPY(u->str, self->str, self->length);
6606
Tim Peters7a29bd52001-09-12 03:03:31 +00006607 if (!fixfct(u) && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006608 /* fixfct should return TRUE if it modified the buffer. If
6609 FALSE, return a reference to the original buffer instead
6610 (to save space, not time) */
6611 Py_INCREF(self);
6612 Py_DECREF(u);
6613 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006614 }
6615 return (PyObject*) u;
6616}
6617
Tim Petersced69f82003-09-16 20:30:58 +00006618static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006619int fixupper(PyUnicodeObject *self)
6620{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006621 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006622 Py_UNICODE *s = self->str;
6623 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006624
Guido van Rossumd57fd912000-03-10 22:53:23 +00006625 while (len-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006626 register Py_UNICODE ch;
Tim Petersced69f82003-09-16 20:30:58 +00006627
Benjamin Peterson29060642009-01-31 22:14:21 +00006628 ch = Py_UNICODE_TOUPPER(*s);
6629 if (ch != *s) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006630 status = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006631 *s = ch;
6632 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006633 s++;
6634 }
6635
6636 return status;
6637}
6638
Tim Petersced69f82003-09-16 20:30:58 +00006639static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006640int fixlower(PyUnicodeObject *self)
6641{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006642 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006643 Py_UNICODE *s = self->str;
6644 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006645
Guido van Rossumd57fd912000-03-10 22:53:23 +00006646 while (len-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006647 register Py_UNICODE ch;
Tim Petersced69f82003-09-16 20:30:58 +00006648
Benjamin Peterson29060642009-01-31 22:14:21 +00006649 ch = Py_UNICODE_TOLOWER(*s);
6650 if (ch != *s) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006651 status = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006652 *s = ch;
6653 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006654 s++;
6655 }
6656
6657 return status;
6658}
6659
Tim Petersced69f82003-09-16 20:30:58 +00006660static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006661int fixswapcase(PyUnicodeObject *self)
6662{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006663 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006664 Py_UNICODE *s = self->str;
6665 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006666
Guido van Rossumd57fd912000-03-10 22:53:23 +00006667 while (len-- > 0) {
6668 if (Py_UNICODE_ISUPPER(*s)) {
6669 *s = Py_UNICODE_TOLOWER(*s);
6670 status = 1;
6671 } else if (Py_UNICODE_ISLOWER(*s)) {
6672 *s = Py_UNICODE_TOUPPER(*s);
6673 status = 1;
6674 }
6675 s++;
6676 }
6677
6678 return status;
6679}
6680
Tim Petersced69f82003-09-16 20:30:58 +00006681static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006682int fixcapitalize(PyUnicodeObject *self)
6683{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006684 Py_ssize_t len = self->length;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006685 Py_UNICODE *s = self->str;
6686 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006687
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006688 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006689 return 0;
Ezio Melottiee8d9982011-08-15 09:09:57 +03006690 if (!Py_UNICODE_ISUPPER(*s)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006691 *s = Py_UNICODE_TOUPPER(*s);
6692 status = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006693 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006694 s++;
6695 while (--len > 0) {
Ezio Melottiee8d9982011-08-15 09:09:57 +03006696 if (!Py_UNICODE_ISLOWER(*s)) {
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006697 *s = Py_UNICODE_TOLOWER(*s);
6698 status = 1;
6699 }
6700 s++;
6701 }
6702 return status;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006703}
6704
6705static
6706int fixtitle(PyUnicodeObject *self)
6707{
6708 register Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
6709 register Py_UNICODE *e;
6710 int previous_is_cased;
6711
6712 /* Shortcut for single character strings */
6713 if (PyUnicode_GET_SIZE(self) == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006714 Py_UNICODE ch = Py_UNICODE_TOTITLE(*p);
6715 if (*p != ch) {
6716 *p = ch;
6717 return 1;
6718 }
6719 else
6720 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006721 }
Tim Petersced69f82003-09-16 20:30:58 +00006722
Guido van Rossumd57fd912000-03-10 22:53:23 +00006723 e = p + PyUnicode_GET_SIZE(self);
6724 previous_is_cased = 0;
6725 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006726 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00006727
Benjamin Peterson29060642009-01-31 22:14:21 +00006728 if (previous_is_cased)
6729 *p = Py_UNICODE_TOLOWER(ch);
6730 else
6731 *p = Py_UNICODE_TOTITLE(ch);
Tim Petersced69f82003-09-16 20:30:58 +00006732
Benjamin Peterson29060642009-01-31 22:14:21 +00006733 if (Py_UNICODE_ISLOWER(ch) ||
6734 Py_UNICODE_ISUPPER(ch) ||
6735 Py_UNICODE_ISTITLE(ch))
6736 previous_is_cased = 1;
6737 else
6738 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006739 }
6740 return 1;
6741}
6742
Tim Peters8ce9f162004-08-27 01:49:32 +00006743PyObject *
6744PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006745{
Skip Montanaro6543b452004-09-16 03:28:13 +00006746 const Py_UNICODE blank = ' ';
6747 const Py_UNICODE *sep = &blank;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006748 Py_ssize_t seplen = 1;
Tim Peters05eba1f2004-08-27 21:32:02 +00006749 PyUnicodeObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00006750 Py_UNICODE *res_p; /* pointer to free byte in res's string area */
6751 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006752 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
6753 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00006754 PyObject *item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006755 Py_ssize_t sz, i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006756
Tim Peters05eba1f2004-08-27 21:32:02 +00006757 fseq = PySequence_Fast(seq, "");
6758 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006759 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00006760 }
6761
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006762 /* NOTE: the following code can't call back into Python code,
6763 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00006764 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006765
Tim Peters05eba1f2004-08-27 21:32:02 +00006766 seqlen = PySequence_Fast_GET_SIZE(fseq);
6767 /* If empty sequence, return u"". */
6768 if (seqlen == 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006769 res = _PyUnicode_New(0); /* empty sequence; return u"" */
6770 goto Done;
Tim Peters05eba1f2004-08-27 21:32:02 +00006771 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006772 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00006773 /* If singleton sequence with an exact Unicode, return that. */
6774 if (seqlen == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006775 item = items[0];
6776 if (PyUnicode_CheckExact(item)) {
6777 Py_INCREF(item);
6778 res = (PyUnicodeObject *)item;
6779 goto Done;
6780 }
Tim Peters8ce9f162004-08-27 01:49:32 +00006781 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006782 else {
6783 /* Set up sep and seplen */
6784 if (separator == NULL) {
6785 sep = &blank;
6786 seplen = 1;
Tim Peters05eba1f2004-08-27 21:32:02 +00006787 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006788 else {
6789 if (!PyUnicode_Check(separator)) {
6790 PyErr_Format(PyExc_TypeError,
6791 "separator: expected str instance,"
6792 " %.80s found",
6793 Py_TYPE(separator)->tp_name);
6794 goto onError;
6795 }
6796 sep = PyUnicode_AS_UNICODE(separator);
6797 seplen = PyUnicode_GET_SIZE(separator);
Tim Peters05eba1f2004-08-27 21:32:02 +00006798 }
6799 }
6800
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006801 /* There are at least two things to join, or else we have a subclass
6802 * of str in the sequence.
6803 * Do a pre-pass to figure out the total amount of space we'll
6804 * need (sz), and see whether all argument are strings.
6805 */
6806 sz = 0;
6807 for (i = 0; i < seqlen; i++) {
6808 const Py_ssize_t old_sz = sz;
6809 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00006810 if (!PyUnicode_Check(item)) {
6811 PyErr_Format(PyExc_TypeError,
6812 "sequence item %zd: expected str instance,"
6813 " %.80s found",
6814 i, Py_TYPE(item)->tp_name);
6815 goto onError;
6816 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006817 sz += PyUnicode_GET_SIZE(item);
6818 if (i != 0)
6819 sz += seplen;
6820 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
6821 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00006822 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006823 goto onError;
6824 }
6825 }
Tim Petersced69f82003-09-16 20:30:58 +00006826
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006827 res = _PyUnicode_New(sz);
6828 if (res == NULL)
6829 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00006830
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006831 /* Catenate everything. */
6832 res_p = PyUnicode_AS_UNICODE(res);
6833 for (i = 0; i < seqlen; ++i) {
6834 Py_ssize_t itemlen;
6835 item = items[i];
6836 itemlen = PyUnicode_GET_SIZE(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00006837 /* Copy item, and maybe the separator. */
6838 if (i) {
6839 Py_UNICODE_COPY(res_p, sep, seplen);
6840 res_p += seplen;
6841 }
6842 Py_UNICODE_COPY(res_p, PyUnicode_AS_UNICODE(item), itemlen);
6843 res_p += itemlen;
Tim Peters05eba1f2004-08-27 21:32:02 +00006844 }
Tim Peters8ce9f162004-08-27 01:49:32 +00006845
Benjamin Peterson29060642009-01-31 22:14:21 +00006846 Done:
Tim Peters05eba1f2004-08-27 21:32:02 +00006847 Py_DECREF(fseq);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006848 return (PyObject *)res;
6849
Benjamin Peterson29060642009-01-31 22:14:21 +00006850 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00006851 Py_DECREF(fseq);
Tim Peters8ce9f162004-08-27 01:49:32 +00006852 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006853 return NULL;
6854}
6855
Tim Petersced69f82003-09-16 20:30:58 +00006856static
6857PyUnicodeObject *pad(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006858 Py_ssize_t left,
6859 Py_ssize_t right,
6860 Py_UNICODE fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006861{
6862 PyUnicodeObject *u;
6863
6864 if (left < 0)
6865 left = 0;
6866 if (right < 0)
6867 right = 0;
6868
Tim Peters7a29bd52001-09-12 03:03:31 +00006869 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006870 Py_INCREF(self);
6871 return self;
6872 }
6873
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006874 if (left > PY_SSIZE_T_MAX - self->length ||
6875 right > PY_SSIZE_T_MAX - (left + self->length)) {
6876 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
6877 return NULL;
6878 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006879 u = _PyUnicode_New(left + self->length + right);
6880 if (u) {
6881 if (left)
6882 Py_UNICODE_FILL(u->str, fill, left);
6883 Py_UNICODE_COPY(u->str + left, self->str, self->length);
6884 if (right)
6885 Py_UNICODE_FILL(u->str + left + self->length, fill, right);
6886 }
6887
6888 return u;
6889}
6890
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006891PyObject *PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006892{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006893 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006894
6895 string = PyUnicode_FromObject(string);
6896 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006897 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006898
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006899 list = stringlib_splitlines(
6900 (PyObject*) string, PyUnicode_AS_UNICODE(string),
6901 PyUnicode_GET_SIZE(string), keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006902
6903 Py_DECREF(string);
6904 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006905}
6906
Tim Petersced69f82003-09-16 20:30:58 +00006907static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006908PyObject *split(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006909 PyUnicodeObject *substring,
6910 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006911{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006912 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006913 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006914
Guido van Rossumd57fd912000-03-10 22:53:23 +00006915 if (substring == NULL)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006916 return stringlib_split_whitespace(
6917 (PyObject*) self, self->str, self->length, maxcount
6918 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00006919
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006920 return stringlib_split(
6921 (PyObject*) self, self->str, self->length,
6922 substring->str, substring->length,
6923 maxcount
6924 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00006925}
6926
Tim Petersced69f82003-09-16 20:30:58 +00006927static
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006928PyObject *rsplit(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006929 PyUnicodeObject *substring,
6930 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006931{
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006932 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006933 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006934
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006935 if (substring == NULL)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006936 return stringlib_rsplit_whitespace(
6937 (PyObject*) self, self->str, self->length, maxcount
6938 );
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006939
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006940 return stringlib_rsplit(
6941 (PyObject*) self, self->str, self->length,
6942 substring->str, substring->length,
6943 maxcount
6944 );
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006945}
6946
6947static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006948PyObject *replace(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006949 PyUnicodeObject *str1,
6950 PyUnicodeObject *str2,
6951 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006952{
6953 PyUnicodeObject *u;
6954
6955 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006956 maxcount = PY_SSIZE_T_MAX;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006957 else if (maxcount == 0 || self->length == 0)
6958 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006959
Thomas Wouters477c8d52006-05-27 19:21:47 +00006960 if (str1->length == str2->length) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +00006961 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006962 /* same length */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006963 if (str1->length == 0)
6964 goto nothing;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006965 if (str1->length == 1) {
6966 /* replace characters */
6967 Py_UNICODE u1, u2;
6968 if (!findchar(self->str, self->length, str1->str[0]))
6969 goto nothing;
6970 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
6971 if (!u)
6972 return NULL;
6973 Py_UNICODE_COPY(u->str, self->str, self->length);
6974 u1 = str1->str[0];
6975 u2 = str2->str[0];
6976 for (i = 0; i < u->length; i++)
6977 if (u->str[i] == u1) {
6978 if (--maxcount < 0)
6979 break;
6980 u->str[i] = u2;
6981 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006982 } else {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006983 i = stringlib_find(
6984 self->str, self->length, str1->str, str1->length, 0
Guido van Rossumd57fd912000-03-10 22:53:23 +00006985 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00006986 if (i < 0)
6987 goto nothing;
6988 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
6989 if (!u)
6990 return NULL;
6991 Py_UNICODE_COPY(u->str, self->str, self->length);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006992
6993 /* change everything in-place, starting with this one */
6994 Py_UNICODE_COPY(u->str+i, str2->str, str2->length);
6995 i += str1->length;
6996
6997 while ( --maxcount > 0) {
6998 i = stringlib_find(self->str+i, self->length-i,
6999 str1->str, str1->length,
7000 i);
7001 if (i == -1)
7002 break;
7003 Py_UNICODE_COPY(u->str+i, str2->str, str2->length);
7004 i += str1->length;
7005 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007006 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007007 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00007008
Victor Stinnerab1d16b2011-11-22 01:45:37 +01007009 Py_ssize_t n, i, j;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007010 Py_ssize_t product, new_size, delta;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007011 Py_UNICODE *p;
7012
7013 /* replace strings */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007014 n = stringlib_count(self->str, self->length, str1->str, str1->length,
7015 maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007016 if (n == 0)
7017 goto nothing;
7018 /* new_size = self->length + n * (str2->length - str1->length)); */
7019 delta = (str2->length - str1->length);
7020 if (delta == 0) {
7021 new_size = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007022 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00007023 product = n * (str2->length - str1->length);
7024 if ((product / (str2->length - str1->length)) != n) {
7025 PyErr_SetString(PyExc_OverflowError,
7026 "replace string is too long");
7027 return NULL;
7028 }
7029 new_size = self->length + product;
7030 if (new_size < 0) {
7031 PyErr_SetString(PyExc_OverflowError,
7032 "replace string is too long");
7033 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007034 }
7035 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00007036 u = _PyUnicode_New(new_size);
7037 if (!u)
7038 return NULL;
7039 i = 0;
7040 p = u->str;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007041 if (str1->length > 0) {
7042 while (n-- > 0) {
7043 /* look for next match */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007044 j = stringlib_find(self->str+i, self->length-i,
7045 str1->str, str1->length,
7046 i);
7047 if (j == -1)
7048 break;
7049 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00007050 /* copy unchanged part [i:j] */
7051 Py_UNICODE_COPY(p, self->str+i, j-i);
7052 p += j - i;
7053 }
7054 /* copy substitution string */
7055 if (str2->length > 0) {
7056 Py_UNICODE_COPY(p, str2->str, str2->length);
7057 p += str2->length;
7058 }
7059 i = j + str1->length;
7060 }
7061 if (i < self->length)
7062 /* copy tail [i:] */
7063 Py_UNICODE_COPY(p, self->str+i, self->length-i);
7064 } else {
7065 /* interleave */
7066 while (n > 0) {
7067 Py_UNICODE_COPY(p, str2->str, str2->length);
7068 p += str2->length;
7069 if (--n <= 0)
7070 break;
7071 *p++ = self->str[i++];
7072 }
7073 Py_UNICODE_COPY(p, self->str+i, self->length-i);
7074 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007075 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007076 return (PyObject *) u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007077
Benjamin Peterson29060642009-01-31 22:14:21 +00007078 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00007079 /* nothing to replace; return original string (when possible) */
7080 if (PyUnicode_CheckExact(self)) {
7081 Py_INCREF(self);
7082 return (PyObject *) self;
7083 }
7084 return PyUnicode_FromUnicode(self->str, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007085}
7086
7087/* --- Unicode Object Methods --------------------------------------------- */
7088
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007089PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007090 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007091\n\
7092Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007093characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007094
7095static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007096unicode_title(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007097{
Guido van Rossumd57fd912000-03-10 22:53:23 +00007098 return fixup(self, fixtitle);
7099}
7100
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007101PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007102 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007103\n\
7104Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +00007105have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007106
7107static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007108unicode_capitalize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007109{
Guido van Rossumd57fd912000-03-10 22:53:23 +00007110 return fixup(self, fixcapitalize);
7111}
7112
7113#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007114PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007115 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007116\n\
7117Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007118normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007119
7120static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007121unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007122{
7123 PyObject *list;
7124 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007125 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007126
Guido van Rossumd57fd912000-03-10 22:53:23 +00007127 /* Split into words */
7128 list = split(self, NULL, -1);
7129 if (!list)
7130 return NULL;
7131
7132 /* Capitalize each word */
7133 for (i = 0; i < PyList_GET_SIZE(list); i++) {
7134 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00007135 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007136 if (item == NULL)
7137 goto onError;
7138 Py_DECREF(PyList_GET_ITEM(list, i));
7139 PyList_SET_ITEM(list, i, item);
7140 }
7141
7142 /* Join the words to form a new string */
7143 item = PyUnicode_Join(NULL, list);
7144
Benjamin Peterson29060642009-01-31 22:14:21 +00007145 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007146 Py_DECREF(list);
7147 return (PyObject *)item;
7148}
7149#endif
7150
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007151/* Argument converter. Coerces to a single unicode character */
7152
7153static int
7154convert_uc(PyObject *obj, void *addr)
7155{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007156 Py_UNICODE *fillcharloc = (Py_UNICODE *)addr;
7157 PyObject *uniobj;
7158 Py_UNICODE *unistr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007159
Benjamin Peterson14339b62009-01-31 16:36:08 +00007160 uniobj = PyUnicode_FromObject(obj);
7161 if (uniobj == NULL) {
7162 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00007163 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007164 return 0;
7165 }
7166 if (PyUnicode_GET_SIZE(uniobj) != 1) {
7167 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00007168 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007169 Py_DECREF(uniobj);
7170 return 0;
7171 }
7172 unistr = PyUnicode_AS_UNICODE(uniobj);
7173 *fillcharloc = unistr[0];
7174 Py_DECREF(uniobj);
7175 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007176}
7177
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007178PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007179 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007180\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007181Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007182done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007183
7184static PyObject *
7185unicode_center(PyUnicodeObject *self, PyObject *args)
7186{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007187 Py_ssize_t marg, left;
7188 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007189 Py_UNICODE fillchar = ' ';
Guido van Rossumd57fd912000-03-10 22:53:23 +00007190
Thomas Woutersde017742006-02-16 19:34:37 +00007191 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007192 return NULL;
7193
Tim Peters7a29bd52001-09-12 03:03:31 +00007194 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00007195 Py_INCREF(self);
7196 return (PyObject*) self;
7197 }
7198
7199 marg = width - self->length;
7200 left = marg / 2 + (marg & width & 1);
7201
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007202 return (PyObject*) pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007203}
7204
Marc-André Lemburge5034372000-08-08 08:04:29 +00007205#if 0
7206
7207/* This code should go into some future Unicode collation support
7208 module. The basic comparison should compare ordinals on a naive
Georg Brandlc6c31782009-06-08 13:41:29 +00007209 basis (this is what Java does and thus Jython too). */
Marc-André Lemburge5034372000-08-08 08:04:29 +00007210
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007211/* speedy UTF-16 code point order comparison */
7212/* gleaned from: */
7213/* http://www-4.ibm.com/software/developer/library/utf16.html?dwzone=unicode */
7214
Marc-André Lemburge12896e2000-07-07 17:51:08 +00007215static short utf16Fixup[32] =
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007216{
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007217 0, 0, 0, 0, 0, 0, 0, 0,
Tim Petersced69f82003-09-16 20:30:58 +00007218 0, 0, 0, 0, 0, 0, 0, 0,
7219 0, 0, 0, 0, 0, 0, 0, 0,
Marc-André Lemburge12896e2000-07-07 17:51:08 +00007220 0, 0, 0, 0x2000, -0x800, -0x800, -0x800, -0x800
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007221};
7222
Guido van Rossumd57fd912000-03-10 22:53:23 +00007223static int
7224unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
7225{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007226 Py_ssize_t len1, len2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007227
Guido van Rossumd57fd912000-03-10 22:53:23 +00007228 Py_UNICODE *s1 = str1->str;
7229 Py_UNICODE *s2 = str2->str;
7230
7231 len1 = str1->length;
7232 len2 = str2->length;
Tim Petersced69f82003-09-16 20:30:58 +00007233
Guido van Rossumd57fd912000-03-10 22:53:23 +00007234 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00007235 Py_UNICODE c1, c2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007236
7237 c1 = *s1++;
7238 c2 = *s2++;
Fredrik Lundh45714e92001-06-26 16:39:36 +00007239
Benjamin Peterson29060642009-01-31 22:14:21 +00007240 if (c1 > (1<<11) * 26)
7241 c1 += utf16Fixup[c1>>11];
7242 if (c2 > (1<<11) * 26)
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007243 c2 += utf16Fixup[c2>>11];
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007244 /* now c1 and c2 are in UTF-32-compatible order */
Fredrik Lundh45714e92001-06-26 16:39:36 +00007245
7246 if (c1 != c2)
7247 return (c1 < c2) ? -1 : 1;
Tim Petersced69f82003-09-16 20:30:58 +00007248
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007249 len1--; len2--;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007250 }
7251
7252 return (len1 < len2) ? -1 : (len1 != len2);
7253}
7254
Marc-André Lemburge5034372000-08-08 08:04:29 +00007255#else
7256
7257static int
7258unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
7259{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007260 register Py_ssize_t len1, len2;
Marc-André Lemburge5034372000-08-08 08:04:29 +00007261
7262 Py_UNICODE *s1 = str1->str;
7263 Py_UNICODE *s2 = str2->str;
7264
7265 len1 = str1->length;
7266 len2 = str2->length;
Tim Petersced69f82003-09-16 20:30:58 +00007267
Marc-André Lemburge5034372000-08-08 08:04:29 +00007268 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00007269 Py_UNICODE c1, c2;
Marc-André Lemburge5034372000-08-08 08:04:29 +00007270
Fredrik Lundh45714e92001-06-26 16:39:36 +00007271 c1 = *s1++;
7272 c2 = *s2++;
7273
7274 if (c1 != c2)
7275 return (c1 < c2) ? -1 : 1;
7276
Marc-André Lemburge5034372000-08-08 08:04:29 +00007277 len1--; len2--;
7278 }
7279
7280 return (len1 < len2) ? -1 : (len1 != len2);
7281}
7282
7283#endif
7284
Guido van Rossumd57fd912000-03-10 22:53:23 +00007285int PyUnicode_Compare(PyObject *left,
Benjamin Peterson29060642009-01-31 22:14:21 +00007286 PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007287{
Guido van Rossum09dc34f2007-05-04 04:17:33 +00007288 if (PyUnicode_Check(left) && PyUnicode_Check(right))
7289 return unicode_compare((PyUnicodeObject *)left,
7290 (PyUnicodeObject *)right);
Guido van Rossum09dc34f2007-05-04 04:17:33 +00007291 PyErr_Format(PyExc_TypeError,
7292 "Can't compare %.100s and %.100s",
7293 left->ob_type->tp_name,
7294 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007295 return -1;
7296}
7297
Martin v. Löwis5b222132007-06-10 09:51:05 +00007298int
7299PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
7300{
7301 int i;
7302 Py_UNICODE *id;
7303 assert(PyUnicode_Check(uni));
7304 id = PyUnicode_AS_UNICODE(uni);
7305 /* Compare Unicode string and source character set string */
7306 for (i = 0; id[i] && str[i]; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00007307 if (id[i] != str[i])
7308 return ((int)id[i] < (int)str[i]) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +00007309 /* This check keeps Python strings that end in '\0' from comparing equal
7310 to C strings identical up to that point. */
Benjamin Petersona23831f2010-04-25 21:54:00 +00007311 if (PyUnicode_GET_SIZE(uni) != i || id[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00007312 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00007313 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00007314 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00007315 return 0;
7316}
7317
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007318
Benjamin Peterson29060642009-01-31 22:14:21 +00007319#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +00007320 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007321
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007322PyObject *PyUnicode_RichCompare(PyObject *left,
7323 PyObject *right,
7324 int op)
7325{
7326 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007327
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007328 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
7329 PyObject *v;
7330 if (((PyUnicodeObject *) left)->length !=
7331 ((PyUnicodeObject *) right)->length) {
7332 if (op == Py_EQ) {
7333 Py_INCREF(Py_False);
7334 return Py_False;
7335 }
7336 if (op == Py_NE) {
7337 Py_INCREF(Py_True);
7338 return Py_True;
7339 }
7340 }
7341 if (left == right)
7342 result = 0;
7343 else
7344 result = unicode_compare((PyUnicodeObject *)left,
7345 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007346
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007347 /* Convert the return value to a Boolean */
7348 switch (op) {
7349 case Py_EQ:
7350 v = TEST_COND(result == 0);
7351 break;
7352 case Py_NE:
7353 v = TEST_COND(result != 0);
7354 break;
7355 case Py_LE:
7356 v = TEST_COND(result <= 0);
7357 break;
7358 case Py_GE:
7359 v = TEST_COND(result >= 0);
7360 break;
7361 case Py_LT:
7362 v = TEST_COND(result == -1);
7363 break;
7364 case Py_GT:
7365 v = TEST_COND(result == 1);
7366 break;
7367 default:
7368 PyErr_BadArgument();
7369 return NULL;
7370 }
7371 Py_INCREF(v);
7372 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007373 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007374
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007375 Py_INCREF(Py_NotImplemented);
7376 return Py_NotImplemented;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007377}
7378
Guido van Rossum403d68b2000-03-13 15:55:09 +00007379int PyUnicode_Contains(PyObject *container,
Benjamin Peterson29060642009-01-31 22:14:21 +00007380 PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +00007381{
Thomas Wouters477c8d52006-05-27 19:21:47 +00007382 PyObject *str, *sub;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007383 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007384
7385 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +00007386 sub = PyUnicode_FromObject(element);
7387 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007388 PyErr_Format(PyExc_TypeError,
7389 "'in <string>' requires string as left operand, not %s",
7390 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007391 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007392 }
7393
Thomas Wouters477c8d52006-05-27 19:21:47 +00007394 str = PyUnicode_FromObject(container);
7395 if (!str) {
7396 Py_DECREF(sub);
7397 return -1;
7398 }
7399
7400 result = stringlib_contains_obj(str, sub);
7401
7402 Py_DECREF(str);
7403 Py_DECREF(sub);
7404
Guido van Rossum403d68b2000-03-13 15:55:09 +00007405 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007406}
7407
Guido van Rossumd57fd912000-03-10 22:53:23 +00007408/* Concat to string or Unicode object giving a new Unicode object. */
7409
7410PyObject *PyUnicode_Concat(PyObject *left,
Benjamin Peterson29060642009-01-31 22:14:21 +00007411 PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007412{
7413 PyUnicodeObject *u = NULL, *v = NULL, *w;
7414
7415 /* Coerce the two arguments */
7416 u = (PyUnicodeObject *)PyUnicode_FromObject(left);
7417 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007418 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007419 v = (PyUnicodeObject *)PyUnicode_FromObject(right);
7420 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007421 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007422
7423 /* Shortcuts */
7424 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007425 Py_DECREF(v);
7426 return (PyObject *)u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007427 }
7428 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007429 Py_DECREF(u);
7430 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007431 }
7432
7433 /* Concat the two Unicode strings */
7434 w = _PyUnicode_New(u->length + v->length);
7435 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007436 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007437 Py_UNICODE_COPY(w->str, u->str, u->length);
7438 Py_UNICODE_COPY(w->str + u->length, v->str, v->length);
7439
7440 Py_DECREF(u);
7441 Py_DECREF(v);
7442 return (PyObject *)w;
7443
Benjamin Peterson29060642009-01-31 22:14:21 +00007444 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007445 Py_XDECREF(u);
7446 Py_XDECREF(v);
7447 return NULL;
7448}
7449
Walter Dörwald1ab83302007-05-18 17:15:44 +00007450void
7451PyUnicode_Append(PyObject **pleft, PyObject *right)
7452{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007453 PyObject *new;
7454 if (*pleft == NULL)
7455 return;
7456 if (right == NULL || !PyUnicode_Check(*pleft)) {
7457 Py_DECREF(*pleft);
7458 *pleft = NULL;
7459 return;
7460 }
7461 new = PyUnicode_Concat(*pleft, right);
7462 Py_DECREF(*pleft);
7463 *pleft = new;
Walter Dörwald1ab83302007-05-18 17:15:44 +00007464}
7465
7466void
7467PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
7468{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007469 PyUnicode_Append(pleft, right);
7470 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +00007471}
7472
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007473PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007474 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007475\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00007476Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007477string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007478interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007479
7480static PyObject *
7481unicode_count(PyUnicodeObject *self, PyObject *args)
7482{
7483 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007484 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007485 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007486 PyObject *result;
7487
Jesus Ceaac451502011-04-20 17:09:23 +02007488 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
7489 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +00007490 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007491
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007492 ADJUST_INDICES(start, end, self->length);
Christian Heimes217cfd12007-12-02 14:31:20 +00007493 result = PyLong_FromSsize_t(
Thomas Wouters477c8d52006-05-27 19:21:47 +00007494 stringlib_count(self->str + start, end - start,
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007495 substring->str, substring->length,
7496 PY_SSIZE_T_MAX)
Thomas Wouters477c8d52006-05-27 19:21:47 +00007497 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007498
7499 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007500
Guido van Rossumd57fd912000-03-10 22:53:23 +00007501 return result;
7502}
7503
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007504PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +00007505 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007506\n\
Victor Stinnere14e2122010-11-07 18:41:46 +00007507Encode S using the codec registered for encoding. Default encoding\n\
7508is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +00007509handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007510a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
7511'xmlcharrefreplace' as well as any other name registered with\n\
7512codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007513
7514static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +00007515unicode_encode(PyUnicodeObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007516{
Benjamin Peterson308d6372009-09-18 21:42:35 +00007517 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +00007518 char *encoding = NULL;
7519 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +00007520
Benjamin Peterson308d6372009-09-18 21:42:35 +00007521 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
7522 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007523 return NULL;
Georg Brandl3b9406b2010-12-03 07:54:09 +00007524 return PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007525}
7526
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007527PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007528 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007529\n\
7530Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007531If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007532
7533static PyObject*
7534unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
7535{
7536 Py_UNICODE *e;
7537 Py_UNICODE *p;
7538 Py_UNICODE *q;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007539 Py_UNICODE *qe;
7540 Py_ssize_t i, j, incr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007541 PyUnicodeObject *u;
7542 int tabsize = 8;
7543
7544 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00007545 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007546
Thomas Wouters7e474022000-07-16 12:04:32 +00007547 /* First pass: determine size of output string */
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007548 i = 0; /* chars up to and including most recent \n or \r */
7549 j = 0; /* chars since most recent \n or \r (use in tab calculations) */
7550 e = self->str + self->length; /* end of input */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007551 for (p = self->str; p < e; p++)
7552 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007553 if (tabsize > 0) {
7554 incr = tabsize - (j % tabsize); /* cannot overflow */
7555 if (j > PY_SSIZE_T_MAX - incr)
7556 goto overflow1;
7557 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007558 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007559 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007560 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007561 if (j > PY_SSIZE_T_MAX - 1)
7562 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007563 j++;
7564 if (*p == '\n' || *p == '\r') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007565 if (i > PY_SSIZE_T_MAX - j)
7566 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007567 i += j;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007568 j = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007569 }
7570 }
7571
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007572 if (i > PY_SSIZE_T_MAX - j)
Benjamin Peterson29060642009-01-31 22:14:21 +00007573 goto overflow1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007574
Guido van Rossumd57fd912000-03-10 22:53:23 +00007575 /* Second pass: create output string and fill it */
7576 u = _PyUnicode_New(i + j);
7577 if (!u)
7578 return NULL;
7579
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007580 j = 0; /* same as in first pass */
7581 q = u->str; /* next output char */
7582 qe = u->str + u->length; /* end of output */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007583
7584 for (p = self->str; p < e; p++)
7585 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007586 if (tabsize > 0) {
7587 i = tabsize - (j % tabsize);
7588 j += i;
7589 while (i--) {
7590 if (q >= qe)
7591 goto overflow2;
7592 *q++ = ' ';
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007593 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007594 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007595 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007596 else {
7597 if (q >= qe)
7598 goto overflow2;
7599 *q++ = *p;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007600 j++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007601 if (*p == '\n' || *p == '\r')
7602 j = 0;
7603 }
7604
7605 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007606
7607 overflow2:
7608 Py_DECREF(u);
7609 overflow1:
7610 PyErr_SetString(PyExc_OverflowError, "new string is too long");
7611 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007612}
7613
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007614PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007615 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007616\n\
7617Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08007618such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007619arguments start and end are interpreted as in slice notation.\n\
7620\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007621Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007622
7623static PyObject *
7624unicode_find(PyUnicodeObject *self, PyObject *args)
7625{
Jesus Ceaac451502011-04-20 17:09:23 +02007626 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00007627 Py_ssize_t start;
7628 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007629 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007630
Jesus Ceaac451502011-04-20 17:09:23 +02007631 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
7632 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007633 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007634
Thomas Wouters477c8d52006-05-27 19:21:47 +00007635 result = stringlib_find_slice(
7636 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
7637 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
7638 start, end
7639 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007640
7641 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007642
Christian Heimes217cfd12007-12-02 14:31:20 +00007643 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007644}
7645
7646static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00007647unicode_getitem(PyUnicodeObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007648{
7649 if (index < 0 || index >= self->length) {
7650 PyErr_SetString(PyExc_IndexError, "string index out of range");
7651 return NULL;
7652 }
7653
7654 return (PyObject*) PyUnicode_FromUnicode(&self->str[index], 1);
7655}
7656
Guido van Rossumc2504932007-09-18 19:42:40 +00007657/* Believe it or not, this produces the same value for ASCII strings
7658 as string_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00007659static Py_hash_t
Neil Schemenauerf8c37d12007-09-07 20:49:04 +00007660unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007661{
Guido van Rossumc2504932007-09-18 19:42:40 +00007662 Py_ssize_t len;
7663 Py_UNICODE *p;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00007664 Py_hash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +00007665
Benjamin Petersonf6622c82012-04-09 14:53:07 -04007666#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -05007667 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -04007668#endif
Guido van Rossumc2504932007-09-18 19:42:40 +00007669 if (self->hash != -1)
7670 return self->hash;
Christian Heimes90aa7642007-12-19 02:45:37 +00007671 len = Py_SIZE(self);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01007672 /*
7673 We make the hash of the empty string be 0, rather than using
7674 (prefix ^ suffix), since this slightly obfuscates the hash secret
7675 */
7676 if (len == 0) {
7677 self->hash = 0;
7678 return 0;
7679 }
Guido van Rossumc2504932007-09-18 19:42:40 +00007680 p = self->str;
Georg Brandl2daf6ae2012-02-20 19:54:16 +01007681 x = _Py_HashSecret.prefix;
7682 x ^= *p << 7;
Guido van Rossumc2504932007-09-18 19:42:40 +00007683 while (--len >= 0)
Gregory P. Smith63e6c322012-01-14 15:31:34 -08007684 x = (_PyHASH_MULTIPLIER*x) ^ *p++;
Christian Heimes90aa7642007-12-19 02:45:37 +00007685 x ^= Py_SIZE(self);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01007686 x ^= _Py_HashSecret.suffix;
Guido van Rossumc2504932007-09-18 19:42:40 +00007687 if (x == -1)
7688 x = -2;
7689 self->hash = x;
7690 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007691}
7692
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007693PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007694 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007695\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007696Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007697
7698static PyObject *
7699unicode_index(PyUnicodeObject *self, PyObject *args)
7700{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007701 Py_ssize_t result;
Jesus Ceaac451502011-04-20 17:09:23 +02007702 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00007703 Py_ssize_t start;
7704 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007705
Jesus Ceaac451502011-04-20 17:09:23 +02007706 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
7707 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007708 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007709
Thomas Wouters477c8d52006-05-27 19:21:47 +00007710 result = stringlib_find_slice(
7711 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
7712 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
7713 start, end
7714 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007715
7716 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007717
Guido van Rossumd57fd912000-03-10 22:53:23 +00007718 if (result < 0) {
7719 PyErr_SetString(PyExc_ValueError, "substring not found");
7720 return NULL;
7721 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00007722
Christian Heimes217cfd12007-12-02 14:31:20 +00007723 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007724}
7725
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007726PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007727 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007728\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007729Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007730at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007731
7732static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007733unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007734{
7735 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7736 register const Py_UNICODE *e;
7737 int cased;
7738
Guido van Rossumd57fd912000-03-10 22:53:23 +00007739 /* Shortcut for single character strings */
7740 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007741 return PyBool_FromLong(Py_UNICODE_ISLOWER(*p));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007742
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007743 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007744 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007745 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007746
Guido van Rossumd57fd912000-03-10 22:53:23 +00007747 e = p + PyUnicode_GET_SIZE(self);
7748 cased = 0;
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007749 while (p < e) {
7750 const Py_UCS4 ch = _Py_UNICODE_NEXT(p, e);
Tim Petersced69f82003-09-16 20:30:58 +00007751
Benjamin Peterson29060642009-01-31 22:14:21 +00007752 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
7753 return PyBool_FromLong(0);
7754 else if (!cased && Py_UNICODE_ISLOWER(ch))
7755 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007756 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007757 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007758}
7759
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007760PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007761 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007762\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007763Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007764at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007765
7766static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007767unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007768{
7769 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7770 register const Py_UNICODE *e;
7771 int cased;
7772
Guido van Rossumd57fd912000-03-10 22:53:23 +00007773 /* Shortcut for single character strings */
7774 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007775 return PyBool_FromLong(Py_UNICODE_ISUPPER(*p) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007776
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007777 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007778 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007779 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007780
Guido van Rossumd57fd912000-03-10 22:53:23 +00007781 e = p + PyUnicode_GET_SIZE(self);
7782 cased = 0;
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007783 while (p < e) {
7784 const Py_UCS4 ch = _Py_UNICODE_NEXT(p, e);
Tim Petersced69f82003-09-16 20:30:58 +00007785
Benjamin Peterson29060642009-01-31 22:14:21 +00007786 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
7787 return PyBool_FromLong(0);
7788 else if (!cased && Py_UNICODE_ISUPPER(ch))
7789 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007790 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007791 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007792}
7793
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007794PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007795 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007796\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007797Return True if S is a titlecased string and there is at least one\n\
7798character in S, i.e. upper- and titlecase characters may only\n\
7799follow uncased characters and lowercase characters only cased ones.\n\
7800Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007801
7802static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007803unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007804{
7805 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7806 register const Py_UNICODE *e;
7807 int cased, previous_is_cased;
7808
Guido van Rossumd57fd912000-03-10 22:53:23 +00007809 /* Shortcut for single character strings */
7810 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007811 return PyBool_FromLong((Py_UNICODE_ISTITLE(*p) != 0) ||
7812 (Py_UNICODE_ISUPPER(*p) != 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007813
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007814 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007815 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007816 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007817
Guido van Rossumd57fd912000-03-10 22:53:23 +00007818 e = p + PyUnicode_GET_SIZE(self);
7819 cased = 0;
7820 previous_is_cased = 0;
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007821 while (p < e) {
7822 const Py_UCS4 ch = _Py_UNICODE_NEXT(p, e);
Tim Petersced69f82003-09-16 20:30:58 +00007823
Benjamin Peterson29060642009-01-31 22:14:21 +00007824 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
7825 if (previous_is_cased)
7826 return PyBool_FromLong(0);
7827 previous_is_cased = 1;
7828 cased = 1;
7829 }
7830 else if (Py_UNICODE_ISLOWER(ch)) {
7831 if (!previous_is_cased)
7832 return PyBool_FromLong(0);
7833 previous_is_cased = 1;
7834 cased = 1;
7835 }
7836 else
7837 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007838 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007839 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007840}
7841
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007842PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007843 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007844\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007845Return True if all characters in S are whitespace\n\
7846and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007847
7848static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007849unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007850{
7851 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7852 register const Py_UNICODE *e;
7853
Guido van Rossumd57fd912000-03-10 22:53:23 +00007854 /* Shortcut for single character strings */
7855 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007856 Py_UNICODE_ISSPACE(*p))
7857 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007858
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007859 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007860 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007861 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007862
Guido van Rossumd57fd912000-03-10 22:53:23 +00007863 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007864 while (p < e) {
7865 const Py_UCS4 ch = _Py_UNICODE_NEXT(p, e);
7866 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +00007867 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007868 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007869 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007870}
7871
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007872PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007873 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007874\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007875Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007876and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007877
7878static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007879unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007880{
7881 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7882 register const Py_UNICODE *e;
7883
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007884 /* Shortcut for single character strings */
7885 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007886 Py_UNICODE_ISALPHA(*p))
7887 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007888
7889 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007890 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007891 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007892
7893 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007894 while (p < e) {
7895 if (!Py_UNICODE_ISALPHA(_Py_UNICODE_NEXT(p, e)))
Benjamin Peterson29060642009-01-31 22:14:21 +00007896 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007897 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007898 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007899}
7900
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007901PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007902 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007903\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007904Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007905and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007906
7907static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007908unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007909{
7910 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7911 register const Py_UNICODE *e;
7912
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007913 /* Shortcut for single character strings */
7914 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007915 Py_UNICODE_ISALNUM(*p))
7916 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007917
7918 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007919 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007920 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007921
7922 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007923 while (p < e) {
7924 const Py_UCS4 ch = _Py_UNICODE_NEXT(p, e);
7925 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +00007926 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007927 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007928 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007929}
7930
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007931PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007932 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007933\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007934Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007935False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007936
7937static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007938unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007939{
7940 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7941 register const Py_UNICODE *e;
7942
Guido van Rossumd57fd912000-03-10 22:53:23 +00007943 /* Shortcut for single character strings */
7944 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007945 Py_UNICODE_ISDECIMAL(*p))
7946 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007947
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007948 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007949 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007950 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007951
Guido van Rossumd57fd912000-03-10 22:53:23 +00007952 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007953 while (p < e) {
7954 if (!Py_UNICODE_ISDECIMAL(_Py_UNICODE_NEXT(p, e)))
Benjamin Peterson29060642009-01-31 22:14:21 +00007955 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007956 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007957 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007958}
7959
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007960PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007961 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007962\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007963Return True if all characters in S are digits\n\
7964and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007965
7966static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007967unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007968{
7969 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7970 register const Py_UNICODE *e;
7971
Guido van Rossumd57fd912000-03-10 22:53:23 +00007972 /* Shortcut for single character strings */
7973 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007974 Py_UNICODE_ISDIGIT(*p))
7975 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007976
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007977 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007978 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007979 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007980
Guido van Rossumd57fd912000-03-10 22:53:23 +00007981 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007982 while (p < e) {
7983 if (!Py_UNICODE_ISDIGIT(_Py_UNICODE_NEXT(p, e)))
Benjamin Peterson29060642009-01-31 22:14:21 +00007984 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007985 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007986 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007987}
7988
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007989PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007990 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007991\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007992Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007993False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007994
7995static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007996unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007997{
7998 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7999 register const Py_UNICODE *e;
8000
Guido van Rossumd57fd912000-03-10 22:53:23 +00008001 /* Shortcut for single character strings */
8002 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00008003 Py_UNICODE_ISNUMERIC(*p))
8004 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008005
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00008006 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00008007 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008008 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00008009
Guido van Rossumd57fd912000-03-10 22:53:23 +00008010 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03008011 while (p < e) {
8012 if (!Py_UNICODE_ISNUMERIC(_Py_UNICODE_NEXT(p, e)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008013 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008014 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00008015 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008016}
8017
Martin v. Löwis47383402007-08-15 07:32:56 +00008018int
8019PyUnicode_IsIdentifier(PyObject *self)
8020{
Benjamin Petersonf413b802011-08-12 22:17:18 -05008021 const Py_UNICODE *p = PyUnicode_AS_UNICODE((PyUnicodeObject*)self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03008022 const Py_UNICODE *e;
8023 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +00008024
8025 /* Special case for empty strings */
Ezio Melotti93e7afc2011-08-22 14:08:38 +03008026 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008027 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +00008028
8029 /* PEP 3131 says that the first character must be in
8030 XID_Start and subsequent characters in XID_Continue,
8031 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +00008032 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +00008033 letters, digits, underscore). However, given the current
8034 definition of XID_Start and XID_Continue, it is sufficient
8035 to check just for these, except that _ must be allowed
8036 as starting an identifier. */
Ezio Melotti93e7afc2011-08-22 14:08:38 +03008037 e = p + PyUnicode_GET_SIZE(self);
8038 first = _Py_UNICODE_NEXT(p, e);
Benjamin Petersonf413b802011-08-12 22:17:18 -05008039 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +00008040 return 0;
8041
Ezio Melotti93e7afc2011-08-22 14:08:38 +03008042 while (p < e)
8043 if (!_PyUnicode_IsXidContinue(_Py_UNICODE_NEXT(p, e)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008044 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +00008045 return 1;
8046}
8047
8048PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008049 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +00008050\n\
8051Return True if S is a valid identifier according\n\
8052to the language definition.");
8053
8054static PyObject*
8055unicode_isidentifier(PyObject *self)
8056{
8057 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
8058}
8059
Georg Brandl559e5d72008-06-11 18:37:52 +00008060PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008061 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +00008062\n\
8063Return True if all characters in S are considered\n\
8064printable in repr() or S is empty, False otherwise.");
8065
8066static PyObject*
8067unicode_isprintable(PyObject *self)
8068{
8069 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
8070 register const Py_UNICODE *e;
8071
8072 /* Shortcut for single character strings */
8073 if (PyUnicode_GET_SIZE(self) == 1 && Py_UNICODE_ISPRINTABLE(*p)) {
8074 Py_RETURN_TRUE;
8075 }
8076
8077 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03008078 while (p < e) {
8079 if (!Py_UNICODE_ISPRINTABLE(_Py_UNICODE_NEXT(p, e))) {
Georg Brandl559e5d72008-06-11 18:37:52 +00008080 Py_RETURN_FALSE;
8081 }
8082 }
8083 Py_RETURN_TRUE;
8084}
8085
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008086PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +00008087 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008088\n\
8089Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +00008090iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008091
8092static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008093unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008094{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008095 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008096}
8097
Martin v. Löwis18e16552006-02-15 17:27:45 +00008098static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +00008099unicode_length(PyUnicodeObject *self)
8100{
8101 return self->length;
8102}
8103
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008104PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008105 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008106\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008107Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008108done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008109
8110static PyObject *
8111unicode_ljust(PyUnicodeObject *self, PyObject *args)
8112{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008113 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008114 Py_UNICODE fillchar = ' ';
8115
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008116 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008117 return NULL;
8118
Tim Peters7a29bd52001-09-12 03:03:31 +00008119 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008120 Py_INCREF(self);
8121 return (PyObject*) self;
8122 }
8123
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008124 return (PyObject*) pad(self, 0, width - self->length, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008125}
8126
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008127PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008128 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008129\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008130Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008131
8132static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008133unicode_lower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008134{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008135 return fixup(self, fixlower);
8136}
8137
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008138#define LEFTSTRIP 0
8139#define RIGHTSTRIP 1
8140#define BOTHSTRIP 2
8141
8142/* Arrays indexed by above */
8143static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
8144
8145#define STRIPNAME(i) (stripformat[i]+3)
8146
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008147/* externally visible for str.strip(unicode) */
8148PyObject *
8149_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
8150{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008151 Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
8152 Py_ssize_t len = PyUnicode_GET_SIZE(self);
8153 Py_UNICODE *sep = PyUnicode_AS_UNICODE(sepobj);
8154 Py_ssize_t seplen = PyUnicode_GET_SIZE(sepobj);
8155 Py_ssize_t i, j;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008156
Benjamin Peterson29060642009-01-31 22:14:21 +00008157 BLOOM_MASK sepmask = make_bloom_mask(sep, seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008158
Benjamin Peterson14339b62009-01-31 16:36:08 +00008159 i = 0;
8160 if (striptype != RIGHTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008161 while (i < len && BLOOM_MEMBER(sepmask, s[i], sep, seplen)) {
8162 i++;
8163 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008164 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008165
Benjamin Peterson14339b62009-01-31 16:36:08 +00008166 j = len;
8167 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008168 do {
8169 j--;
8170 } while (j >= i && BLOOM_MEMBER(sepmask, s[j], sep, seplen));
8171 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008172 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008173
Benjamin Peterson14339b62009-01-31 16:36:08 +00008174 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008175 Py_INCREF(self);
8176 return (PyObject*)self;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008177 }
8178 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008179 return PyUnicode_FromUnicode(s+i, j-i);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008180}
8181
Guido van Rossumd57fd912000-03-10 22:53:23 +00008182
8183static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008184do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008185{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008186 Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
8187 Py_ssize_t len = PyUnicode_GET_SIZE(self), i, j;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008188
Benjamin Peterson14339b62009-01-31 16:36:08 +00008189 i = 0;
8190 if (striptype != RIGHTSTRIP) {
8191 while (i < len && Py_UNICODE_ISSPACE(s[i])) {
8192 i++;
8193 }
8194 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008195
Benjamin Peterson14339b62009-01-31 16:36:08 +00008196 j = len;
8197 if (striptype != LEFTSTRIP) {
8198 do {
8199 j--;
8200 } while (j >= i && Py_UNICODE_ISSPACE(s[j]));
8201 j++;
8202 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008203
Benjamin Peterson14339b62009-01-31 16:36:08 +00008204 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
8205 Py_INCREF(self);
8206 return (PyObject*)self;
8207 }
8208 else
8209 return PyUnicode_FromUnicode(s+i, j-i);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008210}
8211
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008212
8213static PyObject *
8214do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
8215{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008216 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008217
Benjamin Peterson14339b62009-01-31 16:36:08 +00008218 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
8219 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008220
Benjamin Peterson14339b62009-01-31 16:36:08 +00008221 if (sep != NULL && sep != Py_None) {
8222 if (PyUnicode_Check(sep))
8223 return _PyUnicode_XStrip(self, striptype, sep);
8224 else {
8225 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00008226 "%s arg must be None or str",
8227 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +00008228 return NULL;
8229 }
8230 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008231
Benjamin Peterson14339b62009-01-31 16:36:08 +00008232 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008233}
8234
8235
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008236PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008237 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008238\n\
8239Return a copy of the string S with leading and trailing\n\
8240whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008241If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008242
8243static PyObject *
8244unicode_strip(PyUnicodeObject *self, PyObject *args)
8245{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008246 if (PyTuple_GET_SIZE(args) == 0)
8247 return do_strip(self, BOTHSTRIP); /* Common case */
8248 else
8249 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008250}
8251
8252
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008253PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008254 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008255\n\
8256Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008257If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008258
8259static PyObject *
8260unicode_lstrip(PyUnicodeObject *self, PyObject *args)
8261{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008262 if (PyTuple_GET_SIZE(args) == 0)
8263 return do_strip(self, LEFTSTRIP); /* Common case */
8264 else
8265 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008266}
8267
8268
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008269PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008270 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008271\n\
8272Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008273If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008274
8275static PyObject *
8276unicode_rstrip(PyUnicodeObject *self, PyObject *args)
8277{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008278 if (PyTuple_GET_SIZE(args) == 0)
8279 return do_strip(self, RIGHTSTRIP); /* Common case */
8280 else
8281 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008282}
8283
8284
Guido van Rossumd57fd912000-03-10 22:53:23 +00008285static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +00008286unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008287{
8288 PyUnicodeObject *u;
8289 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008290 Py_ssize_t nchars;
Tim Peters8f422462000-09-09 06:13:41 +00008291 size_t nbytes;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008292
Georg Brandl222de0f2009-04-12 12:01:50 +00008293 if (len < 1) {
8294 Py_INCREF(unicode_empty);
8295 return (PyObject *)unicode_empty;
8296 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008297
Tim Peters7a29bd52001-09-12 03:03:31 +00008298 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008299 /* no repeat, return original string */
8300 Py_INCREF(str);
8301 return (PyObject*) str;
8302 }
Tim Peters8f422462000-09-09 06:13:41 +00008303
8304 /* ensure # of chars needed doesn't overflow int and # of bytes
8305 * needed doesn't overflow size_t
8306 */
8307 nchars = len * str->length;
Georg Brandl222de0f2009-04-12 12:01:50 +00008308 if (nchars / len != str->length) {
Tim Peters8f422462000-09-09 06:13:41 +00008309 PyErr_SetString(PyExc_OverflowError,
8310 "repeated string is too long");
8311 return NULL;
8312 }
8313 nbytes = (nchars + 1) * sizeof(Py_UNICODE);
8314 if (nbytes / sizeof(Py_UNICODE) != (size_t)(nchars + 1)) {
8315 PyErr_SetString(PyExc_OverflowError,
8316 "repeated string is too long");
8317 return NULL;
8318 }
8319 u = _PyUnicode_New(nchars);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008320 if (!u)
8321 return NULL;
8322
8323 p = u->str;
8324
Georg Brandl222de0f2009-04-12 12:01:50 +00008325 if (str->length == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00008326 Py_UNICODE_FILL(p, str->str[0], len);
8327 } else {
Georg Brandl222de0f2009-04-12 12:01:50 +00008328 Py_ssize_t done = str->length; /* number of characters copied this far */
8329 Py_UNICODE_COPY(p, str->str, str->length);
Benjamin Peterson29060642009-01-31 22:14:21 +00008330 while (done < nchars) {
Christian Heimescc47b052008-03-25 14:56:36 +00008331 Py_ssize_t n = (done <= nchars-done) ? done : nchars-done;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008332 Py_UNICODE_COPY(p+done, p, n);
8333 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00008334 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008335 }
8336
8337 return (PyObject*) u;
8338}
8339
8340PyObject *PyUnicode_Replace(PyObject *obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00008341 PyObject *subobj,
8342 PyObject *replobj,
8343 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008344{
8345 PyObject *self;
8346 PyObject *str1;
8347 PyObject *str2;
8348 PyObject *result;
8349
8350 self = PyUnicode_FromObject(obj);
8351 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008352 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008353 str1 = PyUnicode_FromObject(subobj);
8354 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008355 Py_DECREF(self);
8356 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008357 }
8358 str2 = PyUnicode_FromObject(replobj);
8359 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008360 Py_DECREF(self);
8361 Py_DECREF(str1);
8362 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008363 }
Tim Petersced69f82003-09-16 20:30:58 +00008364 result = replace((PyUnicodeObject *)self,
Benjamin Peterson29060642009-01-31 22:14:21 +00008365 (PyUnicodeObject *)str1,
8366 (PyUnicodeObject *)str2,
8367 maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008368 Py_DECREF(self);
8369 Py_DECREF(str1);
8370 Py_DECREF(str2);
8371 return result;
8372}
8373
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008374PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +00008375 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008376\n\
8377Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +00008378old replaced by new. If the optional argument count is\n\
8379given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008380
8381static PyObject*
8382unicode_replace(PyUnicodeObject *self, PyObject *args)
8383{
8384 PyUnicodeObject *str1;
8385 PyUnicodeObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008386 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008387 PyObject *result;
8388
Martin v. Löwis18e16552006-02-15 17:27:45 +00008389 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008390 return NULL;
8391 str1 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str1);
8392 if (str1 == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008393 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008394 str2 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str2);
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +00008395 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008396 Py_DECREF(str1);
8397 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +00008398 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008399
8400 result = replace(self, str1, str2, maxcount);
8401
8402 Py_DECREF(str1);
8403 Py_DECREF(str2);
8404 return result;
8405}
8406
8407static
8408PyObject *unicode_repr(PyObject *unicode)
8409{
Walter Dörwald79e913e2007-05-12 11:08:06 +00008410 PyObject *repr;
Walter Dörwald1ab83302007-05-18 17:15:44 +00008411 Py_UNICODE *p;
Walter Dörwald79e913e2007-05-12 11:08:06 +00008412 Py_UNICODE *s = PyUnicode_AS_UNICODE(unicode);
8413 Py_ssize_t size = PyUnicode_GET_SIZE(unicode);
8414
8415 /* XXX(nnorwitz): rather than over-allocating, it would be
8416 better to choose a different scheme. Perhaps scan the
8417 first N-chars of the string and allocate based on that size.
8418 */
8419 /* Initial allocation is based on the longest-possible unichr
8420 escape.
8421
8422 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
8423 unichr, so in this case it's the longest unichr escape. In
8424 narrow (UTF-16) builds this is five chars per source unichr
8425 since there are two unichrs in the surrogate pair, so in narrow
8426 (UTF-16) builds it's not the longest unichr escape.
8427
8428 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
8429 so in the narrow (UTF-16) build case it's the longest unichr
8430 escape.
8431 */
8432
Walter Dörwald1ab83302007-05-18 17:15:44 +00008433 repr = PyUnicode_FromUnicode(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00008434 2 /* quotes */
Walter Dörwald79e913e2007-05-12 11:08:06 +00008435#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00008436 + 10*size
Walter Dörwald79e913e2007-05-12 11:08:06 +00008437#else
Benjamin Peterson29060642009-01-31 22:14:21 +00008438 + 6*size
Walter Dörwald79e913e2007-05-12 11:08:06 +00008439#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00008440 + 1);
Walter Dörwald79e913e2007-05-12 11:08:06 +00008441 if (repr == NULL)
8442 return NULL;
8443
Walter Dörwald1ab83302007-05-18 17:15:44 +00008444 p = PyUnicode_AS_UNICODE(repr);
Walter Dörwald79e913e2007-05-12 11:08:06 +00008445
8446 /* Add quote */
8447 *p++ = (findchar(s, size, '\'') &&
8448 !findchar(s, size, '"')) ? '"' : '\'';
8449 while (size-- > 0) {
8450 Py_UNICODE ch = *s++;
8451
8452 /* Escape quotes and backslashes */
Walter Dörwald1ab83302007-05-18 17:15:44 +00008453 if ((ch == PyUnicode_AS_UNICODE(repr)[0]) || (ch == '\\')) {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008454 *p++ = '\\';
Walter Dörwald1ab83302007-05-18 17:15:44 +00008455 *p++ = ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00008456 continue;
8457 }
8458
Benjamin Peterson29060642009-01-31 22:14:21 +00008459 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +00008460 if (ch == '\t') {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008461 *p++ = '\\';
8462 *p++ = 't';
8463 }
8464 else if (ch == '\n') {
8465 *p++ = '\\';
8466 *p++ = 'n';
8467 }
8468 else if (ch == '\r') {
8469 *p++ = '\\';
8470 *p++ = 'r';
8471 }
8472
8473 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +00008474 else if (ch < ' ' || ch == 0x7F) {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008475 *p++ = '\\';
8476 *p++ = 'x';
8477 *p++ = hexdigits[(ch >> 4) & 0x000F];
8478 *p++ = hexdigits[ch & 0x000F];
8479 }
8480
Georg Brandl559e5d72008-06-11 18:37:52 +00008481 /* Copy ASCII characters as-is */
8482 else if (ch < 0x7F) {
8483 *p++ = ch;
8484 }
8485
Benjamin Peterson29060642009-01-31 22:14:21 +00008486 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +00008487 else {
8488 Py_UCS4 ucs = ch;
8489
8490#ifndef Py_UNICODE_WIDE
8491 Py_UNICODE ch2 = 0;
8492 /* Get code point from surrogate pair */
8493 if (size > 0) {
8494 ch2 = *s;
8495 if (ch >= 0xD800 && ch < 0xDC00 && ch2 >= 0xDC00
Benjamin Peterson29060642009-01-31 22:14:21 +00008496 && ch2 <= 0xDFFF) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008497 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF))
Benjamin Peterson29060642009-01-31 22:14:21 +00008498 + 0x00010000;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008499 s++;
Georg Brandl559e5d72008-06-11 18:37:52 +00008500 size--;
8501 }
8502 }
8503#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00008504 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +00008505 (categories Z* and C* except ASCII space)
8506 */
8507 if (!Py_UNICODE_ISPRINTABLE(ucs)) {
8508 /* Map 8-bit characters to '\xhh' */
8509 if (ucs <= 0xff) {
8510 *p++ = '\\';
8511 *p++ = 'x';
8512 *p++ = hexdigits[(ch >> 4) & 0x000F];
8513 *p++ = hexdigits[ch & 0x000F];
8514 }
8515 /* Map 21-bit characters to '\U00xxxxxx' */
8516 else if (ucs >= 0x10000) {
8517 *p++ = '\\';
8518 *p++ = 'U';
8519 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
8520 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
8521 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
8522 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
8523 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
8524 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
8525 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
8526 *p++ = hexdigits[ucs & 0x0000000F];
8527 }
8528 /* Map 16-bit characters to '\uxxxx' */
8529 else {
8530 *p++ = '\\';
8531 *p++ = 'u';
8532 *p++ = hexdigits[(ucs >> 12) & 0x000F];
8533 *p++ = hexdigits[(ucs >> 8) & 0x000F];
8534 *p++ = hexdigits[(ucs >> 4) & 0x000F];
8535 *p++ = hexdigits[ucs & 0x000F];
8536 }
8537 }
8538 /* Copy characters as-is */
8539 else {
8540 *p++ = ch;
8541#ifndef Py_UNICODE_WIDE
8542 if (ucs >= 0x10000)
8543 *p++ = ch2;
8544#endif
8545 }
8546 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00008547 }
8548 /* Add quote */
Walter Dörwald1ab83302007-05-18 17:15:44 +00008549 *p++ = PyUnicode_AS_UNICODE(repr)[0];
Walter Dörwald79e913e2007-05-12 11:08:06 +00008550
8551 *p = '\0';
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00008552 PyUnicode_Resize(&repr, p - PyUnicode_AS_UNICODE(repr));
Walter Dörwald79e913e2007-05-12 11:08:06 +00008553 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008554}
8555
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008556PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008557 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008558\n\
8559Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08008560such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008561arguments start and end are interpreted as in slice notation.\n\
8562\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008563Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008564
8565static PyObject *
8566unicode_rfind(PyUnicodeObject *self, PyObject *args)
8567{
Jesus Ceaac451502011-04-20 17:09:23 +02008568 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00008569 Py_ssize_t start;
8570 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008571 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008572
Jesus Ceaac451502011-04-20 17:09:23 +02008573 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
8574 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008575 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008576
Thomas Wouters477c8d52006-05-27 19:21:47 +00008577 result = stringlib_rfind_slice(
8578 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
8579 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
8580 start, end
8581 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008582
8583 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008584
Christian Heimes217cfd12007-12-02 14:31:20 +00008585 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008586}
8587
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008588PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008589 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008590\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008591Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008592
8593static PyObject *
8594unicode_rindex(PyUnicodeObject *self, PyObject *args)
8595{
Jesus Ceaac451502011-04-20 17:09:23 +02008596 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00008597 Py_ssize_t start;
8598 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008599 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008600
Jesus Ceaac451502011-04-20 17:09:23 +02008601 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
8602 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008603 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008604
Thomas Wouters477c8d52006-05-27 19:21:47 +00008605 result = stringlib_rfind_slice(
8606 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
8607 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
8608 start, end
8609 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008610
8611 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008612
Guido van Rossumd57fd912000-03-10 22:53:23 +00008613 if (result < 0) {
8614 PyErr_SetString(PyExc_ValueError, "substring not found");
8615 return NULL;
8616 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008617 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008618}
8619
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008620PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008621 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008622\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008623Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008624done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008625
8626static PyObject *
8627unicode_rjust(PyUnicodeObject *self, PyObject *args)
8628{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008629 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008630 Py_UNICODE fillchar = ' ';
8631
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008632 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008633 return NULL;
8634
Tim Peters7a29bd52001-09-12 03:03:31 +00008635 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008636 Py_INCREF(self);
8637 return (PyObject*) self;
8638 }
8639
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008640 return (PyObject*) pad(self, width - self->length, 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008641}
8642
Guido van Rossumd57fd912000-03-10 22:53:23 +00008643PyObject *PyUnicode_Split(PyObject *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00008644 PyObject *sep,
8645 Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008646{
8647 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008648
Guido van Rossumd57fd912000-03-10 22:53:23 +00008649 s = PyUnicode_FromObject(s);
8650 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008651 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00008652 if (sep != NULL) {
8653 sep = PyUnicode_FromObject(sep);
8654 if (sep == NULL) {
8655 Py_DECREF(s);
8656 return NULL;
8657 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008658 }
8659
8660 result = split((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
8661
8662 Py_DECREF(s);
8663 Py_XDECREF(sep);
8664 return result;
8665}
8666
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008667PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008668 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008669\n\
8670Return a list of the words in S, using sep as the\n\
8671delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00008672splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00008673whitespace string is a separator and empty strings are\n\
8674removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008675
8676static PyObject*
8677unicode_split(PyUnicodeObject *self, PyObject *args)
8678{
8679 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008680 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008681
Martin v. Löwis18e16552006-02-15 17:27:45 +00008682 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008683 return NULL;
8684
8685 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008686 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008687 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00008688 return split(self, (PyUnicodeObject *)substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008689 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008690 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008691}
8692
Thomas Wouters477c8d52006-05-27 19:21:47 +00008693PyObject *
8694PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
8695{
8696 PyObject* str_obj;
8697 PyObject* sep_obj;
8698 PyObject* out;
8699
8700 str_obj = PyUnicode_FromObject(str_in);
8701 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008702 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008703 sep_obj = PyUnicode_FromObject(sep_in);
8704 if (!sep_obj) {
8705 Py_DECREF(str_obj);
8706 return NULL;
8707 }
8708
8709 out = stringlib_partition(
8710 str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
8711 sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
8712 );
8713
8714 Py_DECREF(sep_obj);
8715 Py_DECREF(str_obj);
8716
8717 return out;
8718}
8719
8720
8721PyObject *
8722PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
8723{
8724 PyObject* str_obj;
8725 PyObject* sep_obj;
8726 PyObject* out;
8727
8728 str_obj = PyUnicode_FromObject(str_in);
8729 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008730 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008731 sep_obj = PyUnicode_FromObject(sep_in);
8732 if (!sep_obj) {
8733 Py_DECREF(str_obj);
8734 return NULL;
8735 }
8736
8737 out = stringlib_rpartition(
8738 str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
8739 sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
8740 );
8741
8742 Py_DECREF(sep_obj);
8743 Py_DECREF(str_obj);
8744
8745 return out;
8746}
8747
8748PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008749 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008750\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00008751Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008752the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008753found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00008754
8755static PyObject*
8756unicode_partition(PyUnicodeObject *self, PyObject *separator)
8757{
8758 return PyUnicode_Partition((PyObject *)self, separator);
8759}
8760
8761PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +00008762 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008763\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00008764Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008765the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008766separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00008767
8768static PyObject*
8769unicode_rpartition(PyUnicodeObject *self, PyObject *separator)
8770{
8771 return PyUnicode_RPartition((PyObject *)self, separator);
8772}
8773
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008774PyObject *PyUnicode_RSplit(PyObject *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00008775 PyObject *sep,
8776 Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008777{
8778 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008779
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008780 s = PyUnicode_FromObject(s);
8781 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008782 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00008783 if (sep != NULL) {
8784 sep = PyUnicode_FromObject(sep);
8785 if (sep == NULL) {
8786 Py_DECREF(s);
8787 return NULL;
8788 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008789 }
8790
8791 result = rsplit((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
8792
8793 Py_DECREF(s);
8794 Py_XDECREF(sep);
8795 return result;
8796}
8797
8798PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008799 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008800\n\
8801Return a list of the words in S, using sep as the\n\
8802delimiter string, starting at the end of the string and\n\
8803working to the front. If maxsplit is given, at most maxsplit\n\
8804splits are done. If sep is not specified, any whitespace string\n\
8805is a separator.");
8806
8807static PyObject*
8808unicode_rsplit(PyUnicodeObject *self, PyObject *args)
8809{
8810 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008811 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008812
Martin v. Löwis18e16552006-02-15 17:27:45 +00008813 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008814 return NULL;
8815
8816 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008817 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008818 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00008819 return rsplit(self, (PyUnicodeObject *)substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008820 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008821 return PyUnicode_RSplit((PyObject *)self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008822}
8823
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008824PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008825 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008826\n\
8827Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +00008828Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008829is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008830
8831static PyObject*
8832unicode_splitlines(PyUnicodeObject *self, PyObject *args)
8833{
Guido van Rossum86662912000-04-11 15:38:46 +00008834 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008835
Guido van Rossum86662912000-04-11 15:38:46 +00008836 if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008837 return NULL;
8838
Guido van Rossum86662912000-04-11 15:38:46 +00008839 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008840}
8841
8842static
Guido van Rossumf15a29f2007-05-04 00:41:39 +00008843PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008844{
Walter Dörwald346737f2007-05-31 10:44:43 +00008845 if (PyUnicode_CheckExact(self)) {
8846 Py_INCREF(self);
8847 return self;
8848 } else
8849 /* Subtype -- return genuine unicode string with the same value. */
8850 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(self),
8851 PyUnicode_GET_SIZE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +00008852}
8853
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008854PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008855 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008856\n\
8857Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008858and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008859
8860static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008861unicode_swapcase(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008862{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008863 return fixup(self, fixswapcase);
8864}
8865
Georg Brandlceee0772007-11-27 23:48:05 +00008866PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008867 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +00008868\n\
8869Return a translation table usable for str.translate().\n\
8870If there is only one argument, it must be a dictionary mapping Unicode\n\
8871ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008872Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +00008873If there are two arguments, they must be strings of equal length, and\n\
8874in the resulting dictionary, each character in x will be mapped to the\n\
8875character at the same position in y. If there is a third argument, it\n\
8876must be a string, whose characters will be mapped to None in the result.");
8877
8878static PyObject*
8879unicode_maketrans(PyUnicodeObject *null, PyObject *args)
8880{
8881 PyObject *x, *y = NULL, *z = NULL;
8882 PyObject *new = NULL, *key, *value;
8883 Py_ssize_t i = 0;
8884 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008885
Georg Brandlceee0772007-11-27 23:48:05 +00008886 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
8887 return NULL;
8888 new = PyDict_New();
8889 if (!new)
8890 return NULL;
8891 if (y != NULL) {
8892 /* x must be a string too, of equal length */
8893 Py_ssize_t ylen = PyUnicode_GET_SIZE(y);
8894 if (!PyUnicode_Check(x)) {
8895 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
8896 "be a string if there is a second argument");
8897 goto err;
8898 }
8899 if (PyUnicode_GET_SIZE(x) != ylen) {
8900 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
8901 "arguments must have equal length");
8902 goto err;
8903 }
8904 /* create entries for translating chars in x to those in y */
8905 for (i = 0; i < PyUnicode_GET_SIZE(x); i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +00008906 key = PyLong_FromLong(PyUnicode_AS_UNICODE(x)[i]);
Benjamin Peterson53aa1d72011-12-20 13:29:45 -06008907 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +00008908 goto err;
Benjamin Peterson53aa1d72011-12-20 13:29:45 -06008909 value = PyLong_FromLong(PyUnicode_AS_UNICODE(y)[i]);
8910 if (!value) {
8911 Py_DECREF(key);
8912 goto err;
8913 }
Georg Brandlceee0772007-11-27 23:48:05 +00008914 res = PyDict_SetItem(new, key, value);
8915 Py_DECREF(key);
8916 Py_DECREF(value);
8917 if (res < 0)
8918 goto err;
8919 }
8920 /* create entries for deleting chars in z */
8921 if (z != NULL) {
8922 for (i = 0; i < PyUnicode_GET_SIZE(z); i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +00008923 key = PyLong_FromLong(PyUnicode_AS_UNICODE(z)[i]);
Georg Brandlceee0772007-11-27 23:48:05 +00008924 if (!key)
8925 goto err;
8926 res = PyDict_SetItem(new, key, Py_None);
8927 Py_DECREF(key);
8928 if (res < 0)
8929 goto err;
8930 }
8931 }
8932 } else {
8933 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +00008934 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +00008935 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
8936 "to maketrans it must be a dict");
8937 goto err;
8938 }
8939 /* copy entries into the new dict, converting string keys to int keys */
8940 while (PyDict_Next(x, &i, &key, &value)) {
8941 if (PyUnicode_Check(key)) {
8942 /* convert string keys to integer keys */
8943 PyObject *newkey;
8944 if (PyUnicode_GET_SIZE(key) != 1) {
8945 PyErr_SetString(PyExc_ValueError, "string keys in translate "
8946 "table must be of length 1");
8947 goto err;
8948 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008949 newkey = PyLong_FromLong(PyUnicode_AS_UNICODE(key)[0]);
Georg Brandlceee0772007-11-27 23:48:05 +00008950 if (!newkey)
8951 goto err;
8952 res = PyDict_SetItem(new, newkey, value);
8953 Py_DECREF(newkey);
8954 if (res < 0)
8955 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +00008956 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +00008957 /* just keep integer keys */
8958 if (PyDict_SetItem(new, key, value) < 0)
8959 goto err;
8960 } else {
8961 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
8962 "be strings or integers");
8963 goto err;
8964 }
8965 }
8966 }
8967 return new;
8968 err:
8969 Py_DECREF(new);
8970 return NULL;
8971}
8972
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008973PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008974 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008975\n\
8976Return a copy of the string S, where all characters have been mapped\n\
8977through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008978Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +00008979Unmapped characters are left untouched. Characters mapped to None\n\
8980are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008981
8982static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008983unicode_translate(PyUnicodeObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008984{
Georg Brandlceee0772007-11-27 23:48:05 +00008985 return PyUnicode_TranslateCharmap(self->str, self->length, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008986}
8987
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008988PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008989 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008990\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008991Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008992
8993static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008994unicode_upper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008995{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008996 return fixup(self, fixupper);
8997}
8998
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008999PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009000 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009001\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +00009002Pad a numeric string S with zeros on the left, to fill a field\n\
9003of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009004
9005static PyObject *
9006unicode_zfill(PyUnicodeObject *self, PyObject *args)
9007{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009008 Py_ssize_t fill;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009009 PyUnicodeObject *u;
9010
Martin v. Löwis18e16552006-02-15 17:27:45 +00009011 Py_ssize_t width;
9012 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009013 return NULL;
9014
9015 if (self->length >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +00009016 if (PyUnicode_CheckExact(self)) {
9017 Py_INCREF(self);
9018 return (PyObject*) self;
9019 }
9020 else
9021 return PyUnicode_FromUnicode(
9022 PyUnicode_AS_UNICODE(self),
9023 PyUnicode_GET_SIZE(self)
Benjamin Peterson29060642009-01-31 22:14:21 +00009024 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00009025 }
9026
9027 fill = width - self->length;
9028
9029 u = pad(self, fill, 0, '0');
9030
Walter Dörwald068325e2002-04-15 13:36:47 +00009031 if (u == NULL)
9032 return NULL;
9033
Guido van Rossumd57fd912000-03-10 22:53:23 +00009034 if (u->str[fill] == '+' || u->str[fill] == '-') {
9035 /* move sign to beginning of string */
9036 u->str[0] = u->str[fill];
9037 u->str[fill] = '0';
9038 }
9039
9040 return (PyObject*) u;
9041}
Guido van Rossumd57fd912000-03-10 22:53:23 +00009042
9043#if 0
9044static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009045unicode_freelistsize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009046{
Christian Heimes2202f872008-02-06 14:31:34 +00009047 return PyLong_FromLong(numfree);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009048}
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009049
9050static PyObject *
9051unicode__decimal2ascii(PyObject *self)
9052{
9053 return PyUnicode_TransformDecimalToASCII(PyUnicode_AS_UNICODE(self),
9054 PyUnicode_GET_SIZE(self));
9055}
Guido van Rossumd57fd912000-03-10 22:53:23 +00009056#endif
9057
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009058PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009059 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009060\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00009061Return True if S starts with the specified prefix, False otherwise.\n\
9062With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009063With optional end, stop comparing S at that position.\n\
9064prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009065
9066static PyObject *
9067unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00009068 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009069{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009070 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009071 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009072 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009073 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009074 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009075
Jesus Ceaac451502011-04-20 17:09:23 +02009076 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +00009077 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009078 if (PyTuple_Check(subobj)) {
9079 Py_ssize_t i;
9080 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
9081 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +00009082 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009083 if (substring == NULL)
9084 return NULL;
9085 result = tailmatch(self, substring, start, end, -1);
9086 Py_DECREF(substring);
9087 if (result) {
9088 Py_RETURN_TRUE;
9089 }
9090 }
9091 /* nothing matched */
9092 Py_RETURN_FALSE;
9093 }
9094 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +03009095 if (substring == NULL) {
9096 if (PyErr_ExceptionMatches(PyExc_TypeError))
9097 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
9098 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +00009099 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03009100 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009101 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009102 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009103 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009104}
9105
9106
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009107PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009108 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009109\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00009110Return True if S ends with the specified suffix, False otherwise.\n\
9111With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009112With optional end, stop comparing S at that position.\n\
9113suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009114
9115static PyObject *
9116unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00009117 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009118{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009119 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009120 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009121 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009122 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009123 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009124
Jesus Ceaac451502011-04-20 17:09:23 +02009125 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +00009126 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009127 if (PyTuple_Check(subobj)) {
9128 Py_ssize_t i;
9129 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
9130 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +00009131 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009132 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009133 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009134 result = tailmatch(self, substring, start, end, +1);
9135 Py_DECREF(substring);
9136 if (result) {
9137 Py_RETURN_TRUE;
9138 }
9139 }
9140 Py_RETURN_FALSE;
9141 }
9142 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +03009143 if (substring == NULL) {
9144 if (PyErr_ExceptionMatches(PyExc_TypeError))
9145 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
9146 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +00009147 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03009148 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009149 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009150 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009151 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009152}
9153
Eric Smith8c663262007-08-25 02:26:07 +00009154#include "stringlib/string_format.h"
9155
9156PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009157 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +00009158\n\
Eric Smith51d2fd92010-11-06 19:27:37 +00009159Return a formatted version of S, using substitutions from args and kwargs.\n\
9160The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +00009161
Eric Smith27bbca62010-11-04 17:06:58 +00009162PyDoc_STRVAR(format_map__doc__,
9163 "S.format_map(mapping) -> str\n\
9164\n\
Eric Smith51d2fd92010-11-06 19:27:37 +00009165Return a formatted version of S, using substitutions from mapping.\n\
9166The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +00009167
Eric Smith4a7d76d2008-05-30 18:10:19 +00009168static PyObject *
9169unicode__format__(PyObject* self, PyObject* args)
9170{
9171 PyObject *format_spec;
9172
9173 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
9174 return NULL;
9175
9176 return _PyUnicode_FormatAdvanced(self,
9177 PyUnicode_AS_UNICODE(format_spec),
9178 PyUnicode_GET_SIZE(format_spec));
9179}
9180
Eric Smith8c663262007-08-25 02:26:07 +00009181PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009182 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +00009183\n\
Eric Smith51d2fd92010-11-06 19:27:37 +00009184Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +00009185
9186static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009187unicode__sizeof__(PyUnicodeObject *v)
9188{
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00009189 return PyLong_FromSsize_t(sizeof(PyUnicodeObject) +
9190 sizeof(Py_UNICODE) * (v->length + 1));
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009191}
9192
9193PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009194 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009195
9196static PyObject *
Guido van Rossum5d9113d2003-01-29 17:58:45 +00009197unicode_getnewargs(PyUnicodeObject *v)
9198{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009199 return Py_BuildValue("(u#)", v->str, v->length);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00009200}
9201
Guido van Rossumd57fd912000-03-10 22:53:23 +00009202static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +00009203 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009204 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
9205 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009206 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009207 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
9208 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
9209 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
9210 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
9211 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
9212 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
9213 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00009214 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009215 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
9216 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
9217 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00009218 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009219 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
9220 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
9221 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00009222 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00009223 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009224 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00009225 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009226 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
9227 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
9228 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
9229 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
9230 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
9231 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
9232 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
9233 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
9234 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
9235 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
9236 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
9237 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
9238 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
9239 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +00009240 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +00009241 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009242 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +00009243 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +00009244 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +00009245 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +00009246 {"maketrans", (PyCFunction) unicode_maketrans,
9247 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009248 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +00009249#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009250 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +00009251#endif
9252
9253#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009254 /* These methods are just used for debugging the implementation. */
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009255 {"freelistsize", (PyCFunction) unicode_freelistsize, METH_NOARGS},
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009256 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +00009257#endif
9258
Benjamin Peterson14339b62009-01-31 16:36:08 +00009259 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +00009260 {NULL, NULL}
9261};
9262
Neil Schemenauerce30bc92002-11-18 16:10:18 +00009263static PyObject *
9264unicode_mod(PyObject *v, PyObject *w)
9265{
Benjamin Peterson29060642009-01-31 22:14:21 +00009266 if (!PyUnicode_Check(v)) {
9267 Py_INCREF(Py_NotImplemented);
9268 return Py_NotImplemented;
9269 }
9270 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +00009271}
9272
9273static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009274 0, /*nb_add*/
9275 0, /*nb_subtract*/
9276 0, /*nb_multiply*/
9277 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +00009278};
9279
Guido van Rossumd57fd912000-03-10 22:53:23 +00009280static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009281 (lenfunc) unicode_length, /* sq_length */
9282 PyUnicode_Concat, /* sq_concat */
9283 (ssizeargfunc) unicode_repeat, /* sq_repeat */
9284 (ssizeargfunc) unicode_getitem, /* sq_item */
9285 0, /* sq_slice */
9286 0, /* sq_ass_item */
9287 0, /* sq_ass_slice */
9288 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009289};
9290
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009291static PyObject*
9292unicode_subscript(PyUnicodeObject* self, PyObject* item)
9293{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009294 if (PyIndex_Check(item)) {
9295 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009296 if (i == -1 && PyErr_Occurred())
9297 return NULL;
9298 if (i < 0)
Martin v. Löwisdea59e52006-01-05 10:00:36 +00009299 i += PyUnicode_GET_SIZE(self);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009300 return unicode_getitem(self, i);
9301 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00009302 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009303 Py_UNICODE* source_buf;
9304 Py_UNICODE* result_buf;
9305 PyObject* result;
9306
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00009307 if (PySlice_GetIndicesEx(item, PyUnicode_GET_SIZE(self),
Benjamin Peterson29060642009-01-31 22:14:21 +00009308 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009309 return NULL;
9310 }
9311
9312 if (slicelength <= 0) {
9313 return PyUnicode_FromUnicode(NULL, 0);
Thomas Woutersed03b412007-08-28 21:37:11 +00009314 } else if (start == 0 && step == 1 && slicelength == self->length &&
9315 PyUnicode_CheckExact(self)) {
9316 Py_INCREF(self);
9317 return (PyObject *)self;
9318 } else if (step == 1) {
9319 return PyUnicode_FromUnicode(self->str + start, slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009320 } else {
9321 source_buf = PyUnicode_AS_UNICODE((PyObject*)self);
Christian Heimesb186d002008-03-18 15:15:01 +00009322 result_buf = (Py_UNICODE *)PyObject_MALLOC(slicelength*
9323 sizeof(Py_UNICODE));
Benjamin Peterson14339b62009-01-31 16:36:08 +00009324
Benjamin Peterson29060642009-01-31 22:14:21 +00009325 if (result_buf == NULL)
9326 return PyErr_NoMemory();
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009327
9328 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
9329 result_buf[i] = source_buf[cur];
9330 }
Tim Petersced69f82003-09-16 20:30:58 +00009331
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009332 result = PyUnicode_FromUnicode(result_buf, slicelength);
Christian Heimesb186d002008-03-18 15:15:01 +00009333 PyObject_FREE(result_buf);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009334 return result;
9335 }
9336 } else {
9337 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
9338 return NULL;
9339 }
9340}
9341
9342static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009343 (lenfunc)unicode_length, /* mp_length */
9344 (binaryfunc)unicode_subscript, /* mp_subscript */
9345 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009346};
9347
Guido van Rossumd57fd912000-03-10 22:53:23 +00009348
Guido van Rossumd57fd912000-03-10 22:53:23 +00009349/* Helpers for PyUnicode_Format() */
9350
9351static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00009352getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009353{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009354 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009355 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009356 (*p_argidx)++;
9357 if (arglen < 0)
9358 return args;
9359 else
9360 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009361 }
9362 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009363 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009364 return NULL;
9365}
9366
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009367/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009368
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009369static PyObject *
9370formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009371{
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009372 char *p;
9373 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009374 double x;
Tim Petersced69f82003-09-16 20:30:58 +00009375
Guido van Rossumd57fd912000-03-10 22:53:23 +00009376 x = PyFloat_AsDouble(v);
9377 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009378 return NULL;
9379
Guido van Rossumd57fd912000-03-10 22:53:23 +00009380 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009381 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +00009382
Eric Smith0923d1d2009-04-16 20:16:10 +00009383 p = PyOS_double_to_string(x, type, prec,
9384 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009385 if (p == NULL)
9386 return NULL;
9387 result = PyUnicode_FromStringAndSize(p, strlen(p));
Eric Smith0923d1d2009-04-16 20:16:10 +00009388 PyMem_Free(p);
9389 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009390}
9391
Tim Peters38fd5b62000-09-21 05:43:11 +00009392static PyObject*
9393formatlong(PyObject *val, int flags, int prec, int type)
9394{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009395 char *buf;
9396 int len;
9397 PyObject *str; /* temporary string object. */
9398 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +00009399
Benjamin Peterson14339b62009-01-31 16:36:08 +00009400 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
9401 if (!str)
9402 return NULL;
9403 result = PyUnicode_FromStringAndSize(buf, len);
9404 Py_DECREF(str);
9405 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +00009406}
9407
Guido van Rossumd57fd912000-03-10 22:53:23 +00009408static int
9409formatchar(Py_UNICODE *buf,
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009410 size_t buflen,
9411 PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009412{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00009413 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009414 if (PyUnicode_Check(v)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009415 if (PyUnicode_GET_SIZE(v) == 1) {
9416 buf[0] = PyUnicode_AS_UNICODE(v)[0];
9417 buf[1] = '\0';
9418 return 1;
9419 }
9420#ifndef Py_UNICODE_WIDE
9421 if (PyUnicode_GET_SIZE(v) == 2) {
9422 /* Decode a valid surrogate pair */
9423 int c0 = PyUnicode_AS_UNICODE(v)[0];
9424 int c1 = PyUnicode_AS_UNICODE(v)[1];
9425 if (0xD800 <= c0 && c0 <= 0xDBFF &&
9426 0xDC00 <= c1 && c1 <= 0xDFFF) {
9427 buf[0] = c0;
9428 buf[1] = c1;
9429 buf[2] = '\0';
9430 return 2;
9431 }
9432 }
9433#endif
9434 goto onError;
9435 }
9436 else {
9437 /* Integer input truncated to a character */
9438 long x;
9439 x = PyLong_AsLong(v);
9440 if (x == -1 && PyErr_Occurred())
9441 goto onError;
9442
9443 if (x < 0 || x > 0x10ffff) {
9444 PyErr_SetString(PyExc_OverflowError,
9445 "%c arg not in range(0x110000)");
9446 return -1;
9447 }
9448
9449#ifndef Py_UNICODE_WIDE
9450 if (x > 0xffff) {
9451 x -= 0x10000;
9452 buf[0] = (Py_UNICODE)(0xD800 | (x >> 10));
9453 buf[1] = (Py_UNICODE)(0xDC00 | (x & 0x3FF));
9454 return 2;
9455 }
9456#endif
9457 buf[0] = (Py_UNICODE) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009458 buf[1] = '\0';
9459 return 1;
9460 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00009461
Benjamin Peterson29060642009-01-31 22:14:21 +00009462 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009463 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009464 "%c requires int or char");
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009465 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009466}
9467
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009468/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009469 FORMATBUFLEN is the length of the buffer in which chars are formatted.
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009470*/
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009471#define FORMATBUFLEN (size_t)10
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009472
Guido van Rossumd57fd912000-03-10 22:53:23 +00009473PyObject *PyUnicode_Format(PyObject *format,
Benjamin Peterson29060642009-01-31 22:14:21 +00009474 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009475{
9476 Py_UNICODE *fmt, *res;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009477 Py_ssize_t fmtcnt, rescnt, reslen, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009478 int args_owned = 0;
9479 PyUnicodeObject *result = NULL;
9480 PyObject *dict = NULL;
9481 PyObject *uformat;
Tim Petersced69f82003-09-16 20:30:58 +00009482
Guido van Rossumd57fd912000-03-10 22:53:23 +00009483 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009484 PyErr_BadInternalCall();
9485 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009486 }
9487 uformat = PyUnicode_FromObject(format);
Fred Drakee4315f52000-05-09 19:53:39 +00009488 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009489 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009490 fmt = PyUnicode_AS_UNICODE(uformat);
9491 fmtcnt = PyUnicode_GET_SIZE(uformat);
9492
9493 reslen = rescnt = fmtcnt + 100;
9494 result = _PyUnicode_New(reslen);
9495 if (result == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009496 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009497 res = PyUnicode_AS_UNICODE(result);
9498
9499 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009500 arglen = PyTuple_Size(args);
9501 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009502 }
9503 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009504 arglen = -1;
9505 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009506 }
Christian Heimes90aa7642007-12-19 02:45:37 +00009507 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +00009508 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +00009509 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009510
9511 while (--fmtcnt >= 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009512 if (*fmt != '%') {
9513 if (--rescnt < 0) {
9514 rescnt = fmtcnt + 100;
9515 reslen += rescnt;
9516 if (_PyUnicode_Resize(&result, reslen) < 0)
9517 goto onError;
9518 res = PyUnicode_AS_UNICODE(result) + reslen - rescnt;
9519 --rescnt;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009520 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009521 *res++ = *fmt++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009522 }
9523 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009524 /* Got a format specifier */
9525 int flags = 0;
9526 Py_ssize_t width = -1;
9527 int prec = -1;
9528 Py_UNICODE c = '\0';
9529 Py_UNICODE fill;
9530 int isnumok;
9531 PyObject *v = NULL;
9532 PyObject *temp = NULL;
9533 Py_UNICODE *pbuf;
9534 Py_UNICODE sign;
9535 Py_ssize_t len;
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009536 Py_UNICODE formatbuf[FORMATBUFLEN]; /* For formatchar() */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009537
Benjamin Peterson29060642009-01-31 22:14:21 +00009538 fmt++;
9539 if (*fmt == '(') {
9540 Py_UNICODE *keystart;
9541 Py_ssize_t keylen;
9542 PyObject *key;
9543 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +00009544
Benjamin Peterson29060642009-01-31 22:14:21 +00009545 if (dict == NULL) {
9546 PyErr_SetString(PyExc_TypeError,
9547 "format requires a mapping");
9548 goto onError;
9549 }
9550 ++fmt;
9551 --fmtcnt;
9552 keystart = fmt;
9553 /* Skip over balanced parentheses */
9554 while (pcount > 0 && --fmtcnt >= 0) {
9555 if (*fmt == ')')
9556 --pcount;
9557 else if (*fmt == '(')
9558 ++pcount;
9559 fmt++;
9560 }
9561 keylen = fmt - keystart - 1;
9562 if (fmtcnt < 0 || pcount > 0) {
9563 PyErr_SetString(PyExc_ValueError,
9564 "incomplete format key");
9565 goto onError;
9566 }
9567#if 0
9568 /* keys are converted to strings using UTF-8 and
9569 then looked up since Python uses strings to hold
9570 variables names etc. in its namespaces and we
9571 wouldn't want to break common idioms. */
9572 key = PyUnicode_EncodeUTF8(keystart,
9573 keylen,
9574 NULL);
9575#else
9576 key = PyUnicode_FromUnicode(keystart, keylen);
9577#endif
9578 if (key == NULL)
9579 goto onError;
9580 if (args_owned) {
9581 Py_DECREF(args);
9582 args_owned = 0;
9583 }
9584 args = PyObject_GetItem(dict, key);
9585 Py_DECREF(key);
9586 if (args == NULL) {
9587 goto onError;
9588 }
9589 args_owned = 1;
9590 arglen = -1;
9591 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009592 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009593 while (--fmtcnt >= 0) {
9594 switch (c = *fmt++) {
9595 case '-': flags |= F_LJUST; continue;
9596 case '+': flags |= F_SIGN; continue;
9597 case ' ': flags |= F_BLANK; continue;
9598 case '#': flags |= F_ALT; continue;
9599 case '0': flags |= F_ZERO; continue;
9600 }
9601 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009602 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009603 if (c == '*') {
9604 v = getnextarg(args, arglen, &argidx);
9605 if (v == NULL)
9606 goto onError;
9607 if (!PyLong_Check(v)) {
9608 PyErr_SetString(PyExc_TypeError,
9609 "* wants int");
9610 goto onError;
9611 }
9612 width = PyLong_AsLong(v);
9613 if (width == -1 && PyErr_Occurred())
9614 goto onError;
9615 if (width < 0) {
9616 flags |= F_LJUST;
9617 width = -width;
9618 }
9619 if (--fmtcnt >= 0)
9620 c = *fmt++;
9621 }
9622 else if (c >= '0' && c <= '9') {
9623 width = c - '0';
9624 while (--fmtcnt >= 0) {
9625 c = *fmt++;
9626 if (c < '0' || c > '9')
9627 break;
9628 if ((width*10) / 10 != width) {
9629 PyErr_SetString(PyExc_ValueError,
9630 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009631 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00009632 }
9633 width = width*10 + (c - '0');
9634 }
9635 }
9636 if (c == '.') {
9637 prec = 0;
9638 if (--fmtcnt >= 0)
9639 c = *fmt++;
9640 if (c == '*') {
9641 v = getnextarg(args, arglen, &argidx);
9642 if (v == NULL)
9643 goto onError;
9644 if (!PyLong_Check(v)) {
9645 PyErr_SetString(PyExc_TypeError,
9646 "* wants int");
9647 goto onError;
9648 }
9649 prec = PyLong_AsLong(v);
9650 if (prec == -1 && PyErr_Occurred())
9651 goto onError;
9652 if (prec < 0)
9653 prec = 0;
9654 if (--fmtcnt >= 0)
9655 c = *fmt++;
9656 }
9657 else if (c >= '0' && c <= '9') {
9658 prec = c - '0';
9659 while (--fmtcnt >= 0) {
Stefan Krah99212f62010-07-19 17:58:26 +00009660 c = *fmt++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009661 if (c < '0' || c > '9')
9662 break;
9663 if ((prec*10) / 10 != prec) {
9664 PyErr_SetString(PyExc_ValueError,
9665 "prec too big");
9666 goto onError;
9667 }
9668 prec = prec*10 + (c - '0');
9669 }
9670 }
9671 } /* prec */
9672 if (fmtcnt >= 0) {
9673 if (c == 'h' || c == 'l' || c == 'L') {
9674 if (--fmtcnt >= 0)
9675 c = *fmt++;
9676 }
9677 }
9678 if (fmtcnt < 0) {
9679 PyErr_SetString(PyExc_ValueError,
9680 "incomplete format");
9681 goto onError;
9682 }
9683 if (c != '%') {
9684 v = getnextarg(args, arglen, &argidx);
9685 if (v == NULL)
9686 goto onError;
9687 }
9688 sign = 0;
9689 fill = ' ';
9690 switch (c) {
9691
9692 case '%':
9693 pbuf = formatbuf;
9694 /* presume that buffer length is at least 1 */
9695 pbuf[0] = '%';
9696 len = 1;
9697 break;
9698
9699 case 's':
9700 case 'r':
9701 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +00009702 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +00009703 temp = v;
9704 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009705 }
9706 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009707 if (c == 's')
9708 temp = PyObject_Str(v);
9709 else if (c == 'r')
9710 temp = PyObject_Repr(v);
9711 else
9712 temp = PyObject_ASCII(v);
9713 if (temp == NULL)
9714 goto onError;
9715 if (PyUnicode_Check(temp))
9716 /* nothing to do */;
9717 else {
9718 Py_DECREF(temp);
9719 PyErr_SetString(PyExc_TypeError,
9720 "%s argument has non-string str()");
9721 goto onError;
9722 }
9723 }
9724 pbuf = PyUnicode_AS_UNICODE(temp);
9725 len = PyUnicode_GET_SIZE(temp);
9726 if (prec >= 0 && len > prec)
9727 len = prec;
9728 break;
9729
9730 case 'i':
9731 case 'd':
9732 case 'u':
9733 case 'o':
9734 case 'x':
9735 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +00009736 isnumok = 0;
9737 if (PyNumber_Check(v)) {
9738 PyObject *iobj=NULL;
9739
9740 if (PyLong_Check(v)) {
9741 iobj = v;
9742 Py_INCREF(iobj);
9743 }
9744 else {
9745 iobj = PyNumber_Long(v);
9746 }
9747 if (iobj!=NULL) {
9748 if (PyLong_Check(iobj)) {
9749 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -07009750 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +00009751 Py_DECREF(iobj);
9752 if (!temp)
9753 goto onError;
9754 pbuf = PyUnicode_AS_UNICODE(temp);
9755 len = PyUnicode_GET_SIZE(temp);
9756 sign = 1;
9757 }
9758 else {
9759 Py_DECREF(iobj);
9760 }
9761 }
9762 }
9763 if (!isnumok) {
9764 PyErr_Format(PyExc_TypeError,
9765 "%%%c format: a number is required, "
9766 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
9767 goto onError;
9768 }
9769 if (flags & F_ZERO)
9770 fill = '0';
9771 break;
9772
9773 case 'e':
9774 case 'E':
9775 case 'f':
9776 case 'F':
9777 case 'g':
9778 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009779 temp = formatfloat(v, flags, prec, c);
9780 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +00009781 goto onError;
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009782 pbuf = PyUnicode_AS_UNICODE(temp);
9783 len = PyUnicode_GET_SIZE(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +00009784 sign = 1;
9785 if (flags & F_ZERO)
9786 fill = '0';
9787 break;
9788
9789 case 'c':
9790 pbuf = formatbuf;
9791 len = formatchar(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), v);
9792 if (len < 0)
9793 goto onError;
9794 break;
9795
9796 default:
9797 PyErr_Format(PyExc_ValueError,
9798 "unsupported format character '%c' (0x%x) "
9799 "at index %zd",
9800 (31<=c && c<=126) ? (char)c : '?',
9801 (int)c,
9802 (Py_ssize_t)(fmt - 1 -
9803 PyUnicode_AS_UNICODE(uformat)));
9804 goto onError;
9805 }
9806 if (sign) {
9807 if (*pbuf == '-' || *pbuf == '+') {
9808 sign = *pbuf++;
9809 len--;
9810 }
9811 else if (flags & F_SIGN)
9812 sign = '+';
9813 else if (flags & F_BLANK)
9814 sign = ' ';
9815 else
9816 sign = 0;
9817 }
9818 if (width < len)
9819 width = len;
9820 if (rescnt - (sign != 0) < width) {
9821 reslen -= rescnt;
9822 rescnt = width + fmtcnt + 100;
9823 reslen += rescnt;
9824 if (reslen < 0) {
9825 Py_XDECREF(temp);
9826 PyErr_NoMemory();
9827 goto onError;
9828 }
9829 if (_PyUnicode_Resize(&result, reslen) < 0) {
9830 Py_XDECREF(temp);
9831 goto onError;
9832 }
9833 res = PyUnicode_AS_UNICODE(result)
9834 + reslen - rescnt;
9835 }
9836 if (sign) {
9837 if (fill != ' ')
9838 *res++ = sign;
9839 rescnt--;
9840 if (width > len)
9841 width--;
9842 }
9843 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
9844 assert(pbuf[0] == '0');
9845 assert(pbuf[1] == c);
9846 if (fill != ' ') {
9847 *res++ = *pbuf++;
9848 *res++ = *pbuf++;
9849 }
9850 rescnt -= 2;
9851 width -= 2;
9852 if (width < 0)
9853 width = 0;
9854 len -= 2;
9855 }
9856 if (width > len && !(flags & F_LJUST)) {
9857 do {
9858 --rescnt;
9859 *res++ = fill;
9860 } while (--width > len);
9861 }
9862 if (fill == ' ') {
9863 if (sign)
9864 *res++ = sign;
9865 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
9866 assert(pbuf[0] == '0');
9867 assert(pbuf[1] == c);
9868 *res++ = *pbuf++;
9869 *res++ = *pbuf++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009870 }
9871 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009872 Py_UNICODE_COPY(res, pbuf, len);
9873 res += len;
9874 rescnt -= len;
9875 while (--width >= len) {
9876 --rescnt;
9877 *res++ = ' ';
9878 }
9879 if (dict && (argidx < arglen) && c != '%') {
9880 PyErr_SetString(PyExc_TypeError,
9881 "not all arguments converted during string formatting");
Thomas Woutersa96affe2006-03-12 00:29:36 +00009882 Py_XDECREF(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +00009883 goto onError;
9884 }
9885 Py_XDECREF(temp);
9886 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009887 } /* until end */
9888 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009889 PyErr_SetString(PyExc_TypeError,
9890 "not all arguments converted during string formatting");
9891 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009892 }
9893
Thomas Woutersa96affe2006-03-12 00:29:36 +00009894 if (_PyUnicode_Resize(&result, reslen - rescnt) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009895 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009896 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009897 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009898 }
9899 Py_DECREF(uformat);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009900 return (PyObject *)result;
9901
Benjamin Peterson29060642009-01-31 22:14:21 +00009902 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009903 Py_XDECREF(result);
9904 Py_DECREF(uformat);
9905 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009906 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009907 }
9908 return NULL;
9909}
9910
Jeremy Hylton938ace62002-07-17 16:30:39 +00009911static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +00009912unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
9913
Tim Peters6d6c1a32001-08-02 04:15:00 +00009914static PyObject *
9915unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9916{
Benjamin Peterson29060642009-01-31 22:14:21 +00009917 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009918 static char *kwlist[] = {"object", "encoding", "errors", 0};
9919 char *encoding = NULL;
9920 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00009921
Benjamin Peterson14339b62009-01-31 16:36:08 +00009922 if (type != &PyUnicode_Type)
9923 return unicode_subtype_new(type, args, kwds);
9924 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +00009925 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009926 return NULL;
9927 if (x == NULL)
9928 return (PyObject *)_PyUnicode_New(0);
9929 if (encoding == NULL && errors == NULL)
9930 return PyObject_Str(x);
9931 else
Benjamin Peterson29060642009-01-31 22:14:21 +00009932 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +00009933}
9934
Guido van Rossume023fe02001-08-30 03:12:59 +00009935static PyObject *
9936unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9937{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009938 PyUnicodeObject *tmp, *pnew;
9939 Py_ssize_t n;
Guido van Rossume023fe02001-08-30 03:12:59 +00009940
Benjamin Peterson14339b62009-01-31 16:36:08 +00009941 assert(PyType_IsSubtype(type, &PyUnicode_Type));
9942 tmp = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
9943 if (tmp == NULL)
9944 return NULL;
9945 assert(PyUnicode_Check(tmp));
9946 pnew = (PyUnicodeObject *) type->tp_alloc(type, n = tmp->length);
9947 if (pnew == NULL) {
9948 Py_DECREF(tmp);
9949 return NULL;
9950 }
9951 pnew->str = (Py_UNICODE*) PyObject_MALLOC(sizeof(Py_UNICODE) * (n+1));
9952 if (pnew->str == NULL) {
9953 _Py_ForgetReference((PyObject *)pnew);
9954 PyObject_Del(pnew);
9955 Py_DECREF(tmp);
9956 return PyErr_NoMemory();
9957 }
9958 Py_UNICODE_COPY(pnew->str, tmp->str, n+1);
9959 pnew->length = n;
9960 pnew->hash = tmp->hash;
9961 Py_DECREF(tmp);
9962 return (PyObject *)pnew;
Guido van Rossume023fe02001-08-30 03:12:59 +00009963}
9964
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009965PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +00009966 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00009967\n\
Collin Winterd474ce82007-08-07 19:42:11 +00009968Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +00009969encoding defaults to the current default string encoding.\n\
9970errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00009971
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009972static PyObject *unicode_iter(PyObject *seq);
9973
Guido van Rossumd57fd912000-03-10 22:53:23 +00009974PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00009975 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +00009976 "str", /* tp_name */
9977 sizeof(PyUnicodeObject), /* tp_size */
9978 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009979 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009980 (destructor)unicode_dealloc, /* tp_dealloc */
9981 0, /* tp_print */
9982 0, /* tp_getattr */
9983 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00009984 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009985 unicode_repr, /* tp_repr */
9986 &unicode_as_number, /* tp_as_number */
9987 &unicode_as_sequence, /* tp_as_sequence */
9988 &unicode_as_mapping, /* tp_as_mapping */
9989 (hashfunc) unicode_hash, /* tp_hash*/
9990 0, /* tp_call*/
9991 (reprfunc) unicode_str, /* tp_str */
9992 PyObject_GenericGetAttr, /* tp_getattro */
9993 0, /* tp_setattro */
9994 0, /* tp_as_buffer */
9995 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +00009996 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009997 unicode_doc, /* tp_doc */
9998 0, /* tp_traverse */
9999 0, /* tp_clear */
10000 PyUnicode_RichCompare, /* tp_richcompare */
10001 0, /* tp_weaklistoffset */
10002 unicode_iter, /* tp_iter */
10003 0, /* tp_iternext */
10004 unicode_methods, /* tp_methods */
10005 0, /* tp_members */
10006 0, /* tp_getset */
10007 &PyBaseObject_Type, /* tp_base */
10008 0, /* tp_dict */
10009 0, /* tp_descr_get */
10010 0, /* tp_descr_set */
10011 0, /* tp_dictoffset */
10012 0, /* tp_init */
10013 0, /* tp_alloc */
10014 unicode_new, /* tp_new */
10015 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000010016};
10017
10018/* Initialize the Unicode implementation */
10019
Thomas Wouters78890102000-07-22 19:25:51 +000010020void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010021{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000010022 int i;
10023
Thomas Wouters477c8d52006-05-27 19:21:47 +000010024 /* XXX - move this array to unicodectype.c ? */
10025 Py_UNICODE linebreak[] = {
10026 0x000A, /* LINE FEED */
10027 0x000D, /* CARRIAGE RETURN */
10028 0x001C, /* FILE SEPARATOR */
10029 0x001D, /* GROUP SEPARATOR */
10030 0x001E, /* RECORD SEPARATOR */
10031 0x0085, /* NEXT LINE */
10032 0x2028, /* LINE SEPARATOR */
10033 0x2029, /* PARAGRAPH SEPARATOR */
10034 };
10035
Fred Drakee4315f52000-05-09 19:53:39 +000010036 /* Init the implementation */
Christian Heimes2202f872008-02-06 14:31:34 +000010037 free_list = NULL;
10038 numfree = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010039 unicode_empty = _PyUnicode_New(0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000010040 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +000010041 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000010042
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000010043 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000010044 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000010045 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010046 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000010047
10048 /* initialize the linebreak bloom filter */
10049 bloom_linebreak = make_bloom_mask(
10050 linebreak, sizeof(linebreak) / sizeof(linebreak[0])
10051 );
Thomas Wouters0e3f5912006-08-11 14:57:12 +000010052
10053 PyType_Ready(&EncodingMapType);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010054}
10055
10056/* Finalize the Unicode implementation */
10057
Christian Heimesa156e092008-02-16 07:38:31 +000010058int
10059PyUnicode_ClearFreeList(void)
10060{
10061 int freelist_size = numfree;
10062 PyUnicodeObject *u;
10063
10064 for (u = free_list; u != NULL;) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010065 PyUnicodeObject *v = u;
10066 u = *(PyUnicodeObject **)u;
10067 if (v->str)
10068 PyObject_DEL(v->str);
10069 Py_XDECREF(v->defenc);
10070 PyObject_Del(v);
10071 numfree--;
Christian Heimesa156e092008-02-16 07:38:31 +000010072 }
10073 free_list = NULL;
10074 assert(numfree == 0);
10075 return freelist_size;
10076}
10077
Guido van Rossumd57fd912000-03-10 22:53:23 +000010078void
Thomas Wouters78890102000-07-22 19:25:51 +000010079_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010080{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000010081 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010082
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000010083 Py_XDECREF(unicode_empty);
10084 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000010085
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000010086 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010087 if (unicode_latin1[i]) {
10088 Py_DECREF(unicode_latin1[i]);
10089 unicode_latin1[i] = NULL;
10090 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000010091 }
Christian Heimesa156e092008-02-16 07:38:31 +000010092 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000010093}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000010094
Walter Dörwald16807132007-05-25 13:52:07 +000010095void
10096PyUnicode_InternInPlace(PyObject **p)
10097{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010098 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
10099 PyObject *t;
10100 if (s == NULL || !PyUnicode_Check(s))
10101 Py_FatalError(
10102 "PyUnicode_InternInPlace: unicode strings only please!");
10103 /* If it's a subclass, we don't really know what putting
10104 it in the interned dict might do. */
10105 if (!PyUnicode_CheckExact(s))
10106 return;
10107 if (PyUnicode_CHECK_INTERNED(s))
10108 return;
10109 if (interned == NULL) {
10110 interned = PyDict_New();
10111 if (interned == NULL) {
10112 PyErr_Clear(); /* Don't leave an exception */
10113 return;
10114 }
10115 }
10116 /* It might be that the GetItem call fails even
10117 though the key is present in the dictionary,
10118 namely when this happens during a stack overflow. */
10119 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000010120 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010121 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000010122
Benjamin Peterson29060642009-01-31 22:14:21 +000010123 if (t) {
10124 Py_INCREF(t);
10125 Py_DECREF(*p);
10126 *p = t;
10127 return;
10128 }
Walter Dörwald16807132007-05-25 13:52:07 +000010129
Benjamin Peterson14339b62009-01-31 16:36:08 +000010130 PyThreadState_GET()->recursion_critical = 1;
10131 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
10132 PyErr_Clear();
10133 PyThreadState_GET()->recursion_critical = 0;
10134 return;
10135 }
10136 PyThreadState_GET()->recursion_critical = 0;
10137 /* The two references in interned are not counted by refcnt.
10138 The deallocator will take care of this */
10139 Py_REFCNT(s) -= 2;
10140 PyUnicode_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000010141}
10142
10143void
10144PyUnicode_InternImmortal(PyObject **p)
10145{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010146 PyUnicode_InternInPlace(p);
10147 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
10148 PyUnicode_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
10149 Py_INCREF(*p);
10150 }
Walter Dörwald16807132007-05-25 13:52:07 +000010151}
10152
10153PyObject *
10154PyUnicode_InternFromString(const char *cp)
10155{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010156 PyObject *s = PyUnicode_FromString(cp);
10157 if (s == NULL)
10158 return NULL;
10159 PyUnicode_InternInPlace(&s);
10160 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000010161}
10162
10163void _Py_ReleaseInternedUnicodeStrings(void)
10164{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010165 PyObject *keys;
10166 PyUnicodeObject *s;
10167 Py_ssize_t i, n;
10168 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000010169
Benjamin Peterson14339b62009-01-31 16:36:08 +000010170 if (interned == NULL || !PyDict_Check(interned))
10171 return;
10172 keys = PyDict_Keys(interned);
10173 if (keys == NULL || !PyList_Check(keys)) {
10174 PyErr_Clear();
10175 return;
10176 }
Walter Dörwald16807132007-05-25 13:52:07 +000010177
Benjamin Peterson14339b62009-01-31 16:36:08 +000010178 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
10179 detector, interned unicode strings are not forcibly deallocated;
10180 rather, we give them their stolen references back, and then clear
10181 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000010182
Benjamin Peterson14339b62009-01-31 16:36:08 +000010183 n = PyList_GET_SIZE(keys);
10184 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000010185 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010186 for (i = 0; i < n; i++) {
10187 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
10188 switch (s->state) {
10189 case SSTATE_NOT_INTERNED:
10190 /* XXX Shouldn't happen */
10191 break;
10192 case SSTATE_INTERNED_IMMORTAL:
10193 Py_REFCNT(s) += 1;
10194 immortal_size += s->length;
10195 break;
10196 case SSTATE_INTERNED_MORTAL:
10197 Py_REFCNT(s) += 2;
10198 mortal_size += s->length;
10199 break;
10200 default:
10201 Py_FatalError("Inconsistent interned string state.");
10202 }
10203 s->state = SSTATE_NOT_INTERNED;
10204 }
10205 fprintf(stderr, "total size of all interned strings: "
10206 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
10207 "mortal/immortal\n", mortal_size, immortal_size);
10208 Py_DECREF(keys);
10209 PyDict_Clear(interned);
10210 Py_DECREF(interned);
10211 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000010212}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010213
10214
10215/********************* Unicode Iterator **************************/
10216
10217typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010218 PyObject_HEAD
10219 Py_ssize_t it_index;
10220 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010221} unicodeiterobject;
10222
10223static void
10224unicodeiter_dealloc(unicodeiterobject *it)
10225{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010226 _PyObject_GC_UNTRACK(it);
10227 Py_XDECREF(it->it_seq);
10228 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010229}
10230
10231static int
10232unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
10233{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010234 Py_VISIT(it->it_seq);
10235 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010236}
10237
10238static PyObject *
10239unicodeiter_next(unicodeiterobject *it)
10240{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010241 PyUnicodeObject *seq;
10242 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010243
Benjamin Peterson14339b62009-01-31 16:36:08 +000010244 assert(it != NULL);
10245 seq = it->it_seq;
10246 if (seq == NULL)
10247 return NULL;
10248 assert(PyUnicode_Check(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010249
Benjamin Peterson14339b62009-01-31 16:36:08 +000010250 if (it->it_index < PyUnicode_GET_SIZE(seq)) {
10251 item = PyUnicode_FromUnicode(
Benjamin Peterson29060642009-01-31 22:14:21 +000010252 PyUnicode_AS_UNICODE(seq)+it->it_index, 1);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010253 if (item != NULL)
10254 ++it->it_index;
10255 return item;
10256 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010257
Benjamin Peterson14339b62009-01-31 16:36:08 +000010258 Py_DECREF(seq);
10259 it->it_seq = NULL;
10260 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010261}
10262
10263static PyObject *
10264unicodeiter_len(unicodeiterobject *it)
10265{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010266 Py_ssize_t len = 0;
10267 if (it->it_seq)
10268 len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index;
10269 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010270}
10271
10272PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
10273
10274static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010275 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000010276 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000010277 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010278};
10279
10280PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010281 PyVarObject_HEAD_INIT(&PyType_Type, 0)
10282 "str_iterator", /* tp_name */
10283 sizeof(unicodeiterobject), /* tp_basicsize */
10284 0, /* tp_itemsize */
10285 /* methods */
10286 (destructor)unicodeiter_dealloc, /* tp_dealloc */
10287 0, /* tp_print */
10288 0, /* tp_getattr */
10289 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000010290 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000010291 0, /* tp_repr */
10292 0, /* tp_as_number */
10293 0, /* tp_as_sequence */
10294 0, /* tp_as_mapping */
10295 0, /* tp_hash */
10296 0, /* tp_call */
10297 0, /* tp_str */
10298 PyObject_GenericGetAttr, /* tp_getattro */
10299 0, /* tp_setattro */
10300 0, /* tp_as_buffer */
10301 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
10302 0, /* tp_doc */
10303 (traverseproc)unicodeiter_traverse, /* tp_traverse */
10304 0, /* tp_clear */
10305 0, /* tp_richcompare */
10306 0, /* tp_weaklistoffset */
10307 PyObject_SelfIter, /* tp_iter */
10308 (iternextfunc)unicodeiter_next, /* tp_iternext */
10309 unicodeiter_methods, /* tp_methods */
10310 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010311};
10312
10313static PyObject *
10314unicode_iter(PyObject *seq)
10315{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010316 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010317
Benjamin Peterson14339b62009-01-31 16:36:08 +000010318 if (!PyUnicode_Check(seq)) {
10319 PyErr_BadInternalCall();
10320 return NULL;
10321 }
10322 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
10323 if (it == NULL)
10324 return NULL;
10325 it->it_index = 0;
10326 Py_INCREF(seq);
10327 it->it_seq = (PyUnicodeObject *)seq;
10328 _PyObject_GC_TRACK(it);
10329 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010330}
10331
Martin v. Löwis5b222132007-06-10 09:51:05 +000010332size_t
10333Py_UNICODE_strlen(const Py_UNICODE *u)
10334{
10335 int res = 0;
10336 while(*u++)
10337 res++;
10338 return res;
10339}
10340
10341Py_UNICODE*
10342Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
10343{
10344 Py_UNICODE *u = s1;
10345 while ((*u++ = *s2++));
10346 return s1;
10347}
10348
10349Py_UNICODE*
10350Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
10351{
10352 Py_UNICODE *u = s1;
10353 while ((*u++ = *s2++))
10354 if (n-- == 0)
10355 break;
10356 return s1;
10357}
10358
Victor Stinnerc4eb7652010-09-01 23:43:50 +000010359Py_UNICODE*
10360Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
10361{
10362 Py_UNICODE *u1 = s1;
10363 u1 += Py_UNICODE_strlen(u1);
10364 Py_UNICODE_strcpy(u1, s2);
10365 return s1;
10366}
10367
Martin v. Löwis5b222132007-06-10 09:51:05 +000010368int
10369Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
10370{
10371 while (*s1 && *s2 && *s1 == *s2)
10372 s1++, s2++;
10373 if (*s1 && *s2)
10374 return (*s1 < *s2) ? -1 : +1;
10375 if (*s1)
10376 return 1;
10377 if (*s2)
10378 return -1;
10379 return 0;
10380}
10381
Victor Stinneref8d95c2010-08-16 22:03:11 +000010382int
10383Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
10384{
10385 register Py_UNICODE u1, u2;
10386 for (; n != 0; n--) {
10387 u1 = *s1;
10388 u2 = *s2;
10389 if (u1 != u2)
10390 return (u1 < u2) ? -1 : +1;
10391 if (u1 == '\0')
10392 return 0;
10393 s1++;
10394 s2++;
10395 }
10396 return 0;
10397}
10398
Martin v. Löwis5b222132007-06-10 09:51:05 +000010399Py_UNICODE*
10400Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
10401{
10402 const Py_UNICODE *p;
10403 for (p = s; *p; p++)
10404 if (*p == c)
10405 return (Py_UNICODE*)p;
10406 return NULL;
10407}
10408
Victor Stinner331ea922010-08-10 16:37:20 +000010409Py_UNICODE*
10410Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
10411{
10412 const Py_UNICODE *p;
10413 p = s + Py_UNICODE_strlen(s);
10414 while (p != s) {
10415 p--;
10416 if (*p == c)
10417 return (Py_UNICODE*)p;
10418 }
10419 return NULL;
10420}
10421
Victor Stinner71133ff2010-09-01 23:43:53 +000010422Py_UNICODE*
Victor Stinner46408602010-09-03 16:18:00 +000010423PyUnicode_AsUnicodeCopy(PyObject *object)
Victor Stinner71133ff2010-09-01 23:43:53 +000010424{
10425 PyUnicodeObject *unicode = (PyUnicodeObject *)object;
10426 Py_UNICODE *copy;
10427 Py_ssize_t size;
10428
10429 /* Ensure we won't overflow the size. */
10430 if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
10431 PyErr_NoMemory();
10432 return NULL;
10433 }
10434 size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
10435 size *= sizeof(Py_UNICODE);
10436 copy = PyMem_Malloc(size);
10437 if (copy == NULL) {
10438 PyErr_NoMemory();
10439 return NULL;
10440 }
10441 memcpy(copy, PyUnicode_AS_UNICODE(unicode), size);
10442 return copy;
10443}
Martin v. Löwis5b222132007-06-10 09:51:05 +000010444
Georg Brandl66c221e2010-10-14 07:04:07 +000010445/* A _string module, to export formatter_parser and formatter_field_name_split
10446 to the string.Formatter class implemented in Python. */
10447
10448static PyMethodDef _string_methods[] = {
10449 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
10450 METH_O, PyDoc_STR("split the argument as a field name")},
10451 {"formatter_parser", (PyCFunction) formatter_parser,
10452 METH_O, PyDoc_STR("parse the argument as a format string")},
10453 {NULL, NULL}
10454};
10455
10456static struct PyModuleDef _string_module = {
10457 PyModuleDef_HEAD_INIT,
10458 "_string",
10459 PyDoc_STR("string helper module"),
10460 0,
10461 _string_methods,
10462 NULL,
10463 NULL,
10464 NULL,
10465 NULL
10466};
10467
10468PyMODINIT_FUNC
10469PyInit__string(void)
10470{
10471 return PyModule_Create(&_string_module);
10472}
10473
10474
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010475#ifdef __cplusplus
10476}
10477#endif