blob: 03807a45b9d1d03622489a51cd00a72eea2e6ac1 [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
1190 - If w is NULL: return the number of wide characters (including the nul
1191 character) required to convert the unicode object. Ignore size argument.
1192
1193 - Otherwise: return the number of wide characters (excluding the nul
1194 character) written into w. Write at most size wide characters (including
1195 the nul character). */
1196static 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 {
1243 nchar = 1; /* nul character at the end */
1244 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 {
1281 nchar = 1; /* nul character */
1282 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
1870PyUnicode_FSConverter(PyObject* arg, void* addr)
1871{
1872 PyObject *output = NULL;
1873 Py_ssize_t size;
1874 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00001875 if (arg == NULL) {
1876 Py_DECREF(*(PyObject**)addr);
1877 return 1;
1878 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00001879 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00001880 output = arg;
1881 Py_INCREF(output);
1882 }
1883 else {
1884 arg = PyUnicode_FromObject(arg);
1885 if (!arg)
1886 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00001887 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00001888 Py_DECREF(arg);
1889 if (!output)
1890 return 0;
1891 if (!PyBytes_Check(output)) {
1892 Py_DECREF(output);
1893 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
1894 return 0;
1895 }
1896 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00001897 size = PyBytes_GET_SIZE(output);
1898 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00001899 if (size != strlen(data)) {
1900 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
1901 Py_DECREF(output);
1902 return 0;
1903 }
1904 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00001905 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00001906}
1907
1908
Victor Stinner47fcb5b2010-08-13 23:59:58 +00001909int
1910PyUnicode_FSDecoder(PyObject* arg, void* addr)
1911{
1912 PyObject *output = NULL;
1913 Py_ssize_t size;
1914 void *data;
1915 if (arg == NULL) {
1916 Py_DECREF(*(PyObject**)addr);
1917 return 1;
1918 }
1919 if (PyUnicode_Check(arg)) {
1920 output = arg;
1921 Py_INCREF(output);
1922 }
1923 else {
1924 arg = PyBytes_FromObject(arg);
1925 if (!arg)
1926 return 0;
1927 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
1928 PyBytes_GET_SIZE(arg));
1929 Py_DECREF(arg);
1930 if (!output)
1931 return 0;
1932 if (!PyUnicode_Check(output)) {
1933 Py_DECREF(output);
1934 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
1935 return 0;
1936 }
1937 }
1938 size = PyUnicode_GET_SIZE(output);
1939 data = PyUnicode_AS_UNICODE(output);
1940 if (size != Py_UNICODE_strlen(data)) {
1941 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
1942 Py_DECREF(output);
1943 return 0;
1944 }
1945 *(PyObject**)addr = output;
1946 return Py_CLEANUP_SUPPORTED;
1947}
1948
1949
Martin v. Löwis5b222132007-06-10 09:51:05 +00001950char*
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001951_PyUnicode_AsStringAndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00001952{
Christian Heimesf3863112007-11-22 07:46:41 +00001953 PyObject *bytes;
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00001954 if (!PyUnicode_Check(unicode)) {
1955 PyErr_BadArgument();
1956 return NULL;
1957 }
Christian Heimesf3863112007-11-22 07:46:41 +00001958 bytes = _PyUnicode_AsDefaultEncodedString(unicode, NULL);
1959 if (bytes == NULL)
Martin v. Löwis5b222132007-06-10 09:51:05 +00001960 return NULL;
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001961 if (psize != NULL)
Christian Heimes72b710a2008-05-26 13:28:38 +00001962 *psize = PyBytes_GET_SIZE(bytes);
1963 return PyBytes_AS_STRING(bytes);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001964}
1965
1966char*
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001967_PyUnicode_AsString(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001968{
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001969 return _PyUnicode_AsStringAndSize(unicode, NULL);
Martin v. Löwis5b222132007-06-10 09:51:05 +00001970}
1971
Guido van Rossumd57fd912000-03-10 22:53:23 +00001972Py_UNICODE *PyUnicode_AsUnicode(PyObject *unicode)
1973{
1974 if (!PyUnicode_Check(unicode)) {
1975 PyErr_BadArgument();
1976 goto onError;
1977 }
1978 return PyUnicode_AS_UNICODE(unicode);
1979
Benjamin Peterson29060642009-01-31 22:14:21 +00001980 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001981 return NULL;
1982}
1983
Martin v. Löwis18e16552006-02-15 17:27:45 +00001984Py_ssize_t PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001985{
1986 if (!PyUnicode_Check(unicode)) {
1987 PyErr_BadArgument();
1988 goto onError;
1989 }
1990 return PyUnicode_GET_SIZE(unicode);
1991
Benjamin Peterson29060642009-01-31 22:14:21 +00001992 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001993 return -1;
1994}
1995
Thomas Wouters78890102000-07-22 19:25:51 +00001996const char *PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00001997{
Victor Stinner42cb4622010-09-01 19:39:01 +00001998 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00001999}
2000
Victor Stinner554f3f02010-06-16 23:33:54 +00002001/* create or adjust a UnicodeDecodeError */
2002static void
2003make_decode_exception(PyObject **exceptionObject,
2004 const char *encoding,
2005 const char *input, Py_ssize_t length,
2006 Py_ssize_t startpos, Py_ssize_t endpos,
2007 const char *reason)
2008{
2009 if (*exceptionObject == NULL) {
2010 *exceptionObject = PyUnicodeDecodeError_Create(
2011 encoding, input, length, startpos, endpos, reason);
2012 }
2013 else {
2014 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
2015 goto onError;
2016 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
2017 goto onError;
2018 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
2019 goto onError;
2020 }
2021 return;
2022
2023onError:
2024 Py_DECREF(*exceptionObject);
2025 *exceptionObject = NULL;
2026}
2027
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002028/* error handling callback helper:
2029 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00002030 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002031 and adjust various state variables.
2032 return 0 on success, -1 on error
2033*/
2034
2035static
2036int unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00002037 const char *encoding, const char *reason,
2038 const char **input, const char **inend, Py_ssize_t *startinpos,
2039 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
2040 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002041{
Benjamin Peterson142957c2008-07-04 19:55:29 +00002042 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002043
2044 PyObject *restuple = NULL;
2045 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002046 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002047 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002048 Py_ssize_t requiredsize;
2049 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002050 Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002051 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002052 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002053 int res = -1;
2054
2055 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002056 *errorHandler = PyCodec_LookupError(errors);
2057 if (*errorHandler == NULL)
2058 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002059 }
2060
Victor Stinner554f3f02010-06-16 23:33:54 +00002061 make_decode_exception(exceptionObject,
2062 encoding,
2063 *input, *inend - *input,
2064 *startinpos, *endinpos,
2065 reason);
2066 if (*exceptionObject == NULL)
2067 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002068
2069 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
2070 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002071 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002072 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00002073 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00002074 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002075 }
2076 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00002077 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002078
2079 /* Copy back the bytes variables, which might have been modified by the
2080 callback */
2081 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
2082 if (!inputobj)
2083 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00002084 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002085 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00002086 }
Christian Heimes72b710a2008-05-26 13:28:38 +00002087 *input = PyBytes_AS_STRING(inputobj);
2088 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002089 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00002090 /* we can DECREF safely, as the exception has another reference,
2091 so the object won't go away. */
2092 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002093
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002094 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00002095 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00002096 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002097 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
2098 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00002099 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002100
2101 /* need more space? (at least enough for what we
2102 have+the replacement+the rest of the string (starting
2103 at the new input position), so we won't have to check space
2104 when there are no errors in the rest of the string) */
2105 repptr = PyUnicode_AS_UNICODE(repunicode);
2106 repsize = PyUnicode_GET_SIZE(repunicode);
2107 requiredsize = *outpos + repsize + insize-newpos;
2108 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002109 if (requiredsize<2*outsize)
2110 requiredsize = 2*outsize;
2111 if (_PyUnicode_Resize(output, requiredsize) < 0)
2112 goto onError;
2113 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002114 }
2115 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002116 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002117 Py_UNICODE_COPY(*outptr, repptr, repsize);
2118 *outptr += repsize;
2119 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002120
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002121 /* we made it! */
2122 res = 0;
2123
Benjamin Peterson29060642009-01-31 22:14:21 +00002124 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002125 Py_XDECREF(restuple);
2126 return res;
2127}
2128
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002129/* --- UTF-7 Codec -------------------------------------------------------- */
2130
Antoine Pitrou244651a2009-05-04 18:56:13 +00002131/* See RFC2152 for details. We encode conservatively and decode liberally. */
2132
2133/* Three simple macros defining base-64. */
2134
2135/* Is c a base-64 character? */
2136
2137#define IS_BASE64(c) \
2138 (((c) >= 'A' && (c) <= 'Z') || \
2139 ((c) >= 'a' && (c) <= 'z') || \
2140 ((c) >= '0' && (c) <= '9') || \
2141 (c) == '+' || (c) == '/')
2142
2143/* given that c is a base-64 character, what is its base-64 value? */
2144
2145#define FROM_BASE64(c) \
2146 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
2147 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
2148 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
2149 (c) == '+' ? 62 : 63)
2150
2151/* What is the base-64 character of the bottom 6 bits of n? */
2152
2153#define TO_BASE64(n) \
2154 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
2155
2156/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
2157 * decoded as itself. We are permissive on decoding; the only ASCII
2158 * byte not decoding to itself is the + which begins a base64
2159 * string. */
2160
2161#define DECODE_DIRECT(c) \
2162 ((c) <= 127 && (c) != '+')
2163
2164/* The UTF-7 encoder treats ASCII characters differently according to
2165 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
2166 * the above). See RFC2152. This array identifies these different
2167 * sets:
2168 * 0 : "Set D"
2169 * alphanumeric and '(),-./:?
2170 * 1 : "Set O"
2171 * !"#$%&*;<=>@[]^_`{|}
2172 * 2 : "whitespace"
2173 * ht nl cr sp
2174 * 3 : special (must be base64 encoded)
2175 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
2176 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002177
Tim Petersced69f82003-09-16 20:30:58 +00002178static
Antoine Pitrou244651a2009-05-04 18:56:13 +00002179char utf7_category[128] = {
2180/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
2181 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
2182/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
2183 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2184/* sp ! " # $ % & ' ( ) * + , - . / */
2185 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
2186/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
2187 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
2188/* @ A B C D E F G H I J K L M N O */
2189 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2190/* P Q R S T U V W X Y Z [ \ ] ^ _ */
2191 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
2192/* ` a b c d e f g h i j k l m n o */
2193 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2194/* p q r s t u v w x y z { | } ~ del */
2195 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002196};
2197
Antoine Pitrou244651a2009-05-04 18:56:13 +00002198/* ENCODE_DIRECT: this character should be encoded as itself. The
2199 * answer depends on whether we are encoding set O as itself, and also
2200 * on whether we are encoding whitespace as itself. RFC2152 makes it
2201 * clear that the answers to these questions vary between
2202 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00002203
Antoine Pitrou244651a2009-05-04 18:56:13 +00002204#define ENCODE_DIRECT(c, directO, directWS) \
2205 ((c) < 128 && (c) > 0 && \
2206 ((utf7_category[(c)] == 0) || \
2207 (directWS && (utf7_category[(c)] == 2)) || \
2208 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002209
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002210PyObject *PyUnicode_DecodeUTF7(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002211 Py_ssize_t size,
2212 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002213{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002214 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
2215}
2216
Antoine Pitrou244651a2009-05-04 18:56:13 +00002217/* The decoder. The only state we preserve is our read position,
2218 * i.e. how many characters we have consumed. So if we end in the
2219 * middle of a shift sequence we have to back off the read position
2220 * and the output to the beginning of the sequence, otherwise we lose
2221 * all the shift state (seen bits, number of bits seen, high
2222 * surrogate). */
2223
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002224PyObject *PyUnicode_DecodeUTF7Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002225 Py_ssize_t size,
2226 const char *errors,
2227 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002228{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002229 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002230 Py_ssize_t startinpos;
2231 Py_ssize_t endinpos;
2232 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002233 const char *e;
2234 PyUnicodeObject *unicode;
2235 Py_UNICODE *p;
2236 const char *errmsg = "";
2237 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002238 Py_UNICODE *shiftOutStart;
2239 unsigned int base64bits = 0;
2240 unsigned long base64buffer = 0;
2241 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002242 PyObject *errorHandler = NULL;
2243 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002244
2245 unicode = _PyUnicode_New(size);
2246 if (!unicode)
2247 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002248 if (size == 0) {
2249 if (consumed)
2250 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002251 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002252 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002253
2254 p = unicode->str;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002255 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002256 e = s + size;
2257
2258 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002259 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00002260 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00002261 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002262
Antoine Pitrou244651a2009-05-04 18:56:13 +00002263 if (inShift) { /* in a base-64 section */
2264 if (IS_BASE64(ch)) { /* consume a base-64 character */
2265 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
2266 base64bits += 6;
2267 s++;
2268 if (base64bits >= 16) {
2269 /* we have enough bits for a UTF-16 value */
2270 Py_UNICODE outCh = (Py_UNICODE)
2271 (base64buffer >> (base64bits-16));
2272 base64bits -= 16;
2273 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
2274 if (surrogate) {
2275 /* expecting a second surrogate */
2276 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
2277#ifdef Py_UNICODE_WIDE
2278 *p++ = (((surrogate & 0x3FF)<<10)
2279 | (outCh & 0x3FF)) + 0x10000;
2280#else
2281 *p++ = surrogate;
2282 *p++ = outCh;
2283#endif
2284 surrogate = 0;
2285 }
2286 else {
2287 surrogate = 0;
2288 errmsg = "second surrogate missing";
2289 goto utf7Error;
2290 }
2291 }
2292 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
2293 /* first surrogate */
2294 surrogate = outCh;
2295 }
2296 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
2297 errmsg = "unexpected second surrogate";
2298 goto utf7Error;
2299 }
2300 else {
2301 *p++ = outCh;
2302 }
2303 }
2304 }
2305 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002306 inShift = 0;
2307 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002308 if (surrogate) {
2309 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00002310 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002311 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002312 if (base64bits > 0) { /* left-over bits */
2313 if (base64bits >= 6) {
2314 /* We've seen at least one base-64 character */
2315 errmsg = "partial character in shift sequence";
2316 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002317 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002318 else {
2319 /* Some bits remain; they should be zero */
2320 if (base64buffer != 0) {
2321 errmsg = "non-zero padding bits in shift sequence";
2322 goto utf7Error;
2323 }
2324 }
2325 }
2326 if (ch != '-') {
2327 /* '-' is absorbed; other terminating
2328 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002329 *p++ = ch;
2330 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002331 }
2332 }
2333 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002334 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002335 s++; /* consume '+' */
2336 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002337 s++;
2338 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00002339 }
2340 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002341 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002342 shiftOutStart = p;
2343 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002344 }
2345 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002346 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002347 *p++ = ch;
2348 s++;
2349 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002350 else {
2351 startinpos = s-starts;
2352 s++;
2353 errmsg = "unexpected special character";
2354 goto utf7Error;
2355 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002356 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002357utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002358 outpos = p-PyUnicode_AS_UNICODE(unicode);
2359 endinpos = s-starts;
2360 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00002361 errors, &errorHandler,
2362 "utf7", errmsg,
2363 &starts, &e, &startinpos, &endinpos, &exc, &s,
2364 &unicode, &outpos, &p))
2365 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002366 }
2367
Antoine Pitrou244651a2009-05-04 18:56:13 +00002368 /* end of string */
2369
2370 if (inShift && !consumed) { /* in shift sequence, no more to follow */
2371 /* if we're in an inconsistent state, that's an error */
2372 if (surrogate ||
2373 (base64bits >= 6) ||
2374 (base64bits > 0 && base64buffer != 0)) {
2375 outpos = p-PyUnicode_AS_UNICODE(unicode);
2376 endinpos = size;
2377 if (unicode_decode_call_errorhandler(
2378 errors, &errorHandler,
2379 "utf7", "unterminated shift sequence",
2380 &starts, &e, &startinpos, &endinpos, &exc, &s,
2381 &unicode, &outpos, &p))
2382 goto onError;
2383 if (s < e)
2384 goto restart;
2385 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002386 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002387
2388 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002389 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00002390 if (inShift) {
2391 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002392 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002393 }
2394 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002395 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002396 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002397 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002398
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00002399 if (_PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002400 goto onError;
2401
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002402 Py_XDECREF(errorHandler);
2403 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002404 return (PyObject *)unicode;
2405
Benjamin Peterson29060642009-01-31 22:14:21 +00002406 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002407 Py_XDECREF(errorHandler);
2408 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002409 Py_DECREF(unicode);
2410 return NULL;
2411}
2412
2413
2414PyObject *PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002415 Py_ssize_t size,
Antoine Pitrou244651a2009-05-04 18:56:13 +00002416 int base64SetO,
2417 int base64WhiteSpace,
Benjamin Peterson29060642009-01-31 22:14:21 +00002418 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002419{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002420 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002421 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00002422 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002423 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002424 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002425 unsigned int base64bits = 0;
2426 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002427 char * out;
2428 char * start;
2429
2430 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00002431 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002432
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00002433 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00002434 return PyErr_NoMemory();
2435
Antoine Pitrou244651a2009-05-04 18:56:13 +00002436 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002437 if (v == NULL)
2438 return NULL;
2439
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002440 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002441 for (;i < size; ++i) {
2442 Py_UNICODE ch = s[i];
2443
Antoine Pitrou244651a2009-05-04 18:56:13 +00002444 if (inShift) {
2445 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
2446 /* shifting out */
2447 if (base64bits) { /* output remaining bits */
2448 *out++ = TO_BASE64(base64buffer << (6-base64bits));
2449 base64buffer = 0;
2450 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002451 }
2452 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002453 /* Characters not in the BASE64 set implicitly unshift the sequence
2454 so no '-' is required, except if the character is itself a '-' */
2455 if (IS_BASE64(ch) || ch == '-') {
2456 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002457 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002458 *out++ = (char) ch;
2459 }
2460 else {
2461 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00002462 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002463 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002464 else { /* not in a shift sequence */
2465 if (ch == '+') {
2466 *out++ = '+';
2467 *out++ = '-';
2468 }
2469 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
2470 *out++ = (char) ch;
2471 }
2472 else {
2473 *out++ = '+';
2474 inShift = 1;
2475 goto encode_char;
2476 }
2477 }
2478 continue;
2479encode_char:
2480#ifdef Py_UNICODE_WIDE
2481 if (ch >= 0x10000) {
2482 /* code first surrogate */
2483 base64bits += 16;
2484 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
2485 while (base64bits >= 6) {
2486 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
2487 base64bits -= 6;
2488 }
2489 /* prepare second surrogate */
2490 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
2491 }
2492#endif
2493 base64bits += 16;
2494 base64buffer = (base64buffer << 16) | ch;
2495 while (base64bits >= 6) {
2496 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
2497 base64bits -= 6;
2498 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00002499 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002500 if (base64bits)
2501 *out++= TO_BASE64(base64buffer << (6-base64bits) );
2502 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002503 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002504 if (_PyBytes_Resize(&v, out - start) < 0)
2505 return NULL;
2506 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002507}
2508
Antoine Pitrou244651a2009-05-04 18:56:13 +00002509#undef IS_BASE64
2510#undef FROM_BASE64
2511#undef TO_BASE64
2512#undef DECODE_DIRECT
2513#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002514
Guido van Rossumd57fd912000-03-10 22:53:23 +00002515/* --- UTF-8 Codec -------------------------------------------------------- */
2516
Tim Petersced69f82003-09-16 20:30:58 +00002517static
Guido van Rossumd57fd912000-03-10 22:53:23 +00002518char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00002519 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
2520 illegal prefix. See RFC 3629 for details */
2521 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
2522 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002523 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00002524 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2525 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2526 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2527 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00002528 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
2529 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 +00002530 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2531 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00002532 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
2533 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
2534 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
2535 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
2536 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 +00002537};
2538
Guido van Rossumd57fd912000-03-10 22:53:23 +00002539PyObject *PyUnicode_DecodeUTF8(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002540 Py_ssize_t size,
2541 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002542{
Walter Dörwald69652032004-09-07 20:24:22 +00002543 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
2544}
2545
Antoine Pitrouab868312009-01-10 15:40:25 +00002546/* Mask to check or force alignment of a pointer to C 'long' boundaries */
2547#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
2548
2549/* Mask to quickly check whether a C 'long' contains a
2550 non-ASCII, UTF8-encoded char. */
2551#if (SIZEOF_LONG == 8)
2552# define ASCII_CHAR_MASK 0x8080808080808080L
2553#elif (SIZEOF_LONG == 4)
2554# define ASCII_CHAR_MASK 0x80808080L
2555#else
2556# error C 'long' size should be either 4 or 8!
2557#endif
2558
Walter Dörwald69652032004-09-07 20:24:22 +00002559PyObject *PyUnicode_DecodeUTF8Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002560 Py_ssize_t size,
2561 const char *errors,
2562 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00002563{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002564 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002565 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00002566 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002567 Py_ssize_t startinpos;
2568 Py_ssize_t endinpos;
2569 Py_ssize_t outpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00002570 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002571 PyUnicodeObject *unicode;
2572 Py_UNICODE *p;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002573 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002574 PyObject *errorHandler = NULL;
2575 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002576
2577 /* Note: size will always be longer than the resulting Unicode
2578 character count */
2579 unicode = _PyUnicode_New(size);
2580 if (!unicode)
2581 return NULL;
Walter Dörwald69652032004-09-07 20:24:22 +00002582 if (size == 0) {
2583 if (consumed)
2584 *consumed = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002585 return (PyObject *)unicode;
Walter Dörwald69652032004-09-07 20:24:22 +00002586 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002587
2588 /* Unpack UTF-8 encoded data */
2589 p = unicode->str;
2590 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00002591 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002592
2593 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002594 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002595
2596 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00002597 /* Fast path for runs of ASCII characters. Given that common UTF-8
2598 input will consist of an overwhelming majority of ASCII
2599 characters, we try to optimize for this case by checking
2600 as many characters as a C 'long' can contain.
2601 First, check if we can do an aligned read, as most CPUs have
2602 a penalty for unaligned reads.
2603 */
2604 if (!((size_t) s & LONG_PTR_MASK)) {
2605 /* Help register allocation */
2606 register const char *_s = s;
2607 register Py_UNICODE *_p = p;
2608 while (_s < aligned_end) {
2609 /* Read a whole long at a time (either 4 or 8 bytes),
2610 and do a fast unrolled copy if it only contains ASCII
2611 characters. */
2612 unsigned long data = *(unsigned long *) _s;
2613 if (data & ASCII_CHAR_MASK)
2614 break;
2615 _p[0] = (unsigned char) _s[0];
2616 _p[1] = (unsigned char) _s[1];
2617 _p[2] = (unsigned char) _s[2];
2618 _p[3] = (unsigned char) _s[3];
2619#if (SIZEOF_LONG == 8)
2620 _p[4] = (unsigned char) _s[4];
2621 _p[5] = (unsigned char) _s[5];
2622 _p[6] = (unsigned char) _s[6];
2623 _p[7] = (unsigned char) _s[7];
2624#endif
2625 _s += SIZEOF_LONG;
2626 _p += SIZEOF_LONG;
2627 }
2628 s = _s;
2629 p = _p;
2630 if (s == e)
2631 break;
2632 ch = (unsigned char)*s;
2633 }
2634 }
2635
2636 if (ch < 0x80) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002637 *p++ = (Py_UNICODE)ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002638 s++;
2639 continue;
2640 }
2641
2642 n = utf8_code_length[ch];
2643
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002644 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002645 if (consumed)
2646 break;
2647 else {
2648 errmsg = "unexpected end of data";
2649 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002650 endinpos = startinpos+1;
2651 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
2652 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00002653 goto utf8Error;
2654 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002655 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002656
2657 switch (n) {
2658
2659 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00002660 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002661 startinpos = s-starts;
2662 endinpos = startinpos+1;
2663 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002664
2665 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002666 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00002667 startinpos = s-starts;
2668 endinpos = startinpos+1;
2669 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002670
2671 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002672 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00002673 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002674 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002675 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00002676 goto utf8Error;
2677 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002678 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00002679 assert ((ch > 0x007F) && (ch <= 0x07FF));
2680 *p++ = (Py_UNICODE)ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002681 break;
2682
2683 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00002684 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
2685 will result in surrogates in range d800-dfff. Surrogates are
2686 not valid UTF-8 so they are rejected.
2687 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
2688 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00002689 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00002690 (s[2] & 0xc0) != 0x80 ||
2691 ((unsigned char)s[0] == 0xE0 &&
2692 (unsigned char)s[1] < 0xA0) ||
2693 ((unsigned char)s[0] == 0xED &&
2694 (unsigned char)s[1] > 0x9F)) {
2695 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002696 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002697 endinpos = startinpos + 1;
2698
2699 /* if s[1] first two bits are 1 and 0, then the invalid
2700 continuation byte is s[2], so increment endinpos by 1,
2701 if not, s[1] is invalid and endinpos doesn't need to
2702 be incremented. */
2703 if ((s[1] & 0xC0) == 0x80)
2704 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00002705 goto utf8Error;
2706 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002707 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00002708 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
2709 *p++ = (Py_UNICODE)ch;
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002710 break;
2711
2712 case 4:
2713 if ((s[1] & 0xc0) != 0x80 ||
2714 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00002715 (s[3] & 0xc0) != 0x80 ||
2716 ((unsigned char)s[0] == 0xF0 &&
2717 (unsigned char)s[1] < 0x90) ||
2718 ((unsigned char)s[0] == 0xF4 &&
2719 (unsigned char)s[1] > 0x8F)) {
2720 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002721 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002722 endinpos = startinpos + 1;
2723 if ((s[1] & 0xC0) == 0x80) {
2724 endinpos++;
2725 if ((s[2] & 0xC0) == 0x80)
2726 endinpos++;
2727 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002728 goto utf8Error;
2729 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002730 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00002731 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
2732 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
2733
Fredrik Lundh8f455852001-06-27 18:59:43 +00002734#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00002735 *p++ = (Py_UNICODE)ch;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002736#else
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002737 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00002738
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002739 /* translate from 10000..10FFFF to 0..FFFF */
2740 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00002741
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002742 /* high surrogate = top 10 bits added to D800 */
2743 *p++ = (Py_UNICODE)(0xD800 + (ch >> 10));
Tim Petersced69f82003-09-16 20:30:58 +00002744
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002745 /* low surrogate = bottom 10 bits added to DC00 */
Fredrik Lundh45714e92001-06-26 16:39:36 +00002746 *p++ = (Py_UNICODE)(0xDC00 + (ch & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002747#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00002748 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002749 }
2750 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00002751 continue;
Tim Petersced69f82003-09-16 20:30:58 +00002752
Benjamin Peterson29060642009-01-31 22:14:21 +00002753 utf8Error:
2754 outpos = p-PyUnicode_AS_UNICODE(unicode);
2755 if (unicode_decode_call_errorhandler(
2756 errors, &errorHandler,
2757 "utf8", errmsg,
2758 &starts, &e, &startinpos, &endinpos, &exc, &s,
2759 &unicode, &outpos, &p))
2760 goto onError;
2761 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002762 }
Walter Dörwald69652032004-09-07 20:24:22 +00002763 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00002764 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002765
2766 /* Adjust length */
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00002767 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002768 goto onError;
2769
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002770 Py_XDECREF(errorHandler);
2771 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002772 return (PyObject *)unicode;
2773
Benjamin Peterson29060642009-01-31 22:14:21 +00002774 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002775 Py_XDECREF(errorHandler);
2776 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002777 Py_DECREF(unicode);
2778 return NULL;
2779}
2780
Antoine Pitrouab868312009-01-10 15:40:25 +00002781#undef ASCII_CHAR_MASK
2782
Victor Stinnerf933e1a2010-10-20 22:58:25 +00002783#ifdef __APPLE__
2784
2785/* Simplified UTF-8 decoder using surrogateescape error handler,
2786 used to decode the command line arguments on Mac OS X. */
2787
2788wchar_t*
2789_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
2790{
2791 int n;
2792 const char *e;
2793 wchar_t *unicode, *p;
2794
2795 /* Note: size will always be longer than the resulting Unicode
2796 character count */
2797 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
2798 PyErr_NoMemory();
2799 return NULL;
2800 }
2801 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
2802 if (!unicode)
2803 return NULL;
2804
2805 /* Unpack UTF-8 encoded data */
2806 p = unicode;
2807 e = s + size;
2808 while (s < e) {
2809 Py_UCS4 ch = (unsigned char)*s;
2810
2811 if (ch < 0x80) {
2812 *p++ = (wchar_t)ch;
2813 s++;
2814 continue;
2815 }
2816
2817 n = utf8_code_length[ch];
2818 if (s + n > e) {
2819 goto surrogateescape;
2820 }
2821
2822 switch (n) {
2823 case 0:
2824 case 1:
2825 goto surrogateescape;
2826
2827 case 2:
2828 if ((s[1] & 0xc0) != 0x80)
2829 goto surrogateescape;
2830 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
2831 assert ((ch > 0x007F) && (ch <= 0x07FF));
2832 *p++ = (wchar_t)ch;
2833 break;
2834
2835 case 3:
2836 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
2837 will result in surrogates in range d800-dfff. Surrogates are
2838 not valid UTF-8 so they are rejected.
2839 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
2840 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
2841 if ((s[1] & 0xc0) != 0x80 ||
2842 (s[2] & 0xc0) != 0x80 ||
2843 ((unsigned char)s[0] == 0xE0 &&
2844 (unsigned char)s[1] < 0xA0) ||
2845 ((unsigned char)s[0] == 0xED &&
2846 (unsigned char)s[1] > 0x9F)) {
2847
2848 goto surrogateescape;
2849 }
2850 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
2851 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
2852 *p++ = (Py_UNICODE)ch;
2853 break;
2854
2855 case 4:
2856 if ((s[1] & 0xc0) != 0x80 ||
2857 (s[2] & 0xc0) != 0x80 ||
2858 (s[3] & 0xc0) != 0x80 ||
2859 ((unsigned char)s[0] == 0xF0 &&
2860 (unsigned char)s[1] < 0x90) ||
2861 ((unsigned char)s[0] == 0xF4 &&
2862 (unsigned char)s[1] > 0x8F)) {
2863 goto surrogateescape;
2864 }
2865 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
2866 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
2867 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
2868
2869#if SIZEOF_WCHAR_T == 4
2870 *p++ = (wchar_t)ch;
2871#else
2872 /* compute and append the two surrogates: */
2873
2874 /* translate from 10000..10FFFF to 0..FFFF */
2875 ch -= 0x10000;
2876
2877 /* high surrogate = top 10 bits added to D800 */
2878 *p++ = (wchar_t)(0xD800 + (ch >> 10));
2879
2880 /* low surrogate = bottom 10 bits added to DC00 */
2881 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
2882#endif
2883 break;
2884 }
2885 s += n;
2886 continue;
2887
2888 surrogateescape:
2889 *p++ = 0xDC00 + ch;
2890 s++;
2891 }
2892 *p = L'\0';
2893 return unicode;
2894}
2895
2896#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00002897
Tim Peters602f7402002-04-27 18:03:26 +00002898/* Allocation strategy: if the string is short, convert into a stack buffer
2899 and allocate exactly as much space needed at the end. Else allocate the
2900 maximum possible needed (4 result bytes per Unicode character), and return
2901 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002902*/
Tim Peters7e3d9612002-04-21 03:26:37 +00002903PyObject *
2904PyUnicode_EncodeUTF8(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002905 Py_ssize_t size,
2906 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002907{
Tim Peters602f7402002-04-27 18:03:26 +00002908#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00002909
Guido van Rossum98297ee2007-11-06 21:34:58 +00002910 Py_ssize_t i; /* index into s of next input byte */
2911 PyObject *result; /* result string object */
2912 char *p; /* next free byte in output buffer */
2913 Py_ssize_t nallocated; /* number of result bytes allocated */
2914 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00002915 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002916 PyObject *errorHandler = NULL;
2917 PyObject *exc = NULL;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00002918
Tim Peters602f7402002-04-27 18:03:26 +00002919 assert(s != NULL);
2920 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002921
Tim Peters602f7402002-04-27 18:03:26 +00002922 if (size <= MAX_SHORT_UNICHARS) {
2923 /* Write into the stack buffer; nallocated can't overflow.
2924 * At the end, we'll allocate exactly as much heap space as it
2925 * turns out we need.
2926 */
2927 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002928 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00002929 p = stackbuf;
2930 }
2931 else {
2932 /* Overallocate on the heap, and give the excess back at the end. */
2933 nallocated = size * 4;
2934 if (nallocated / 4 != size) /* overflow! */
2935 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00002936 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002937 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00002938 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00002939 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00002940 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002941
Tim Peters602f7402002-04-27 18:03:26 +00002942 for (i = 0; i < size;) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002943 Py_UCS4 ch = s[i++];
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002944
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002945 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00002946 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002947 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002948
Guido van Rossumd57fd912000-03-10 22:53:23 +00002949 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00002950 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00002951 *p++ = (char)(0xc0 | (ch >> 6));
2952 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00002953 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002954#ifndef Py_UNICODE_WIDE
Victor Stinner31be90b2010-04-22 19:38:16 +00002955 /* Special case: check for high and low surrogate */
2956 if (ch <= 0xDBFF && i != size && 0xDC00 <= s[i] && s[i] <= 0xDFFF) {
2957 Py_UCS4 ch2 = s[i];
2958 /* Combine the two surrogates to form a UCS4 value */
2959 ch = ((ch - 0xD800) << 10 | (ch2 - 0xDC00)) + 0x10000;
2960 i++;
2961
2962 /* Encode UCS4 Unicode ordinals */
2963 *p++ = (char)(0xf0 | (ch >> 18));
2964 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
Tim Peters602f7402002-04-27 18:03:26 +00002965 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2966 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00002967 } else {
Victor Stinner445a6232010-04-22 20:01:57 +00002968#endif
Victor Stinner31be90b2010-04-22 19:38:16 +00002969 Py_ssize_t newpos;
2970 PyObject *rep;
2971 Py_ssize_t repsize, k;
2972 rep = unicode_encode_call_errorhandler
2973 (errors, &errorHandler, "utf-8", "surrogates not allowed",
2974 s, size, &exc, i-1, i, &newpos);
2975 if (!rep)
2976 goto error;
2977
2978 if (PyBytes_Check(rep))
2979 repsize = PyBytes_GET_SIZE(rep);
2980 else
2981 repsize = PyUnicode_GET_SIZE(rep);
2982
2983 if (repsize > 4) {
2984 Py_ssize_t offset;
2985
2986 if (result == NULL)
2987 offset = p - stackbuf;
2988 else
2989 offset = p - PyBytes_AS_STRING(result);
2990
2991 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
2992 /* integer overflow */
2993 PyErr_NoMemory();
2994 goto error;
2995 }
2996 nallocated += repsize - 4;
2997 if (result != NULL) {
2998 if (_PyBytes_Resize(&result, nallocated) < 0)
2999 goto error;
3000 } else {
3001 result = PyBytes_FromStringAndSize(NULL, nallocated);
3002 if (result == NULL)
3003 goto error;
3004 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
3005 }
3006 p = PyBytes_AS_STRING(result) + offset;
3007 }
3008
3009 if (PyBytes_Check(rep)) {
3010 char *prep = PyBytes_AS_STRING(rep);
3011 for(k = repsize; k > 0; k--)
3012 *p++ = *prep++;
3013 } else /* rep is unicode */ {
3014 Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
3015 Py_UNICODE c;
3016
3017 for(k=0; k<repsize; k++) {
3018 c = prep[k];
3019 if (0x80 <= c) {
3020 raise_encode_exception(&exc, "utf-8", s, size,
3021 i-1, i, "surrogates not allowed");
3022 goto error;
3023 }
3024 *p++ = (char)prep[k];
3025 }
3026 }
3027 Py_DECREF(rep);
Victor Stinner445a6232010-04-22 20:01:57 +00003028#ifndef Py_UNICODE_WIDE
Victor Stinner31be90b2010-04-22 19:38:16 +00003029 }
Victor Stinner445a6232010-04-22 20:01:57 +00003030#endif
Victor Stinner31be90b2010-04-22 19:38:16 +00003031 } else if (ch < 0x10000) {
3032 *p++ = (char)(0xe0 | (ch >> 12));
3033 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
3034 *p++ = (char)(0x80 | (ch & 0x3f));
3035 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00003036 /* Encode UCS4 Unicode ordinals */
3037 *p++ = (char)(0xf0 | (ch >> 18));
3038 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
3039 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
3040 *p++ = (char)(0x80 | (ch & 0x3f));
3041 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003042 }
Tim Peters0eca65c2002-04-21 17:28:06 +00003043
Guido van Rossum98297ee2007-11-06 21:34:58 +00003044 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00003045 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003046 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00003047 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00003048 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00003049 }
3050 else {
Christian Heimesf3863112007-11-22 07:46:41 +00003051 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00003052 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00003053 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00003054 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00003055 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00003056 Py_XDECREF(errorHandler);
3057 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003058 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00003059 error:
3060 Py_XDECREF(errorHandler);
3061 Py_XDECREF(exc);
3062 Py_XDECREF(result);
3063 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00003064
Tim Peters602f7402002-04-27 18:03:26 +00003065#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00003066}
3067
Guido van Rossumd57fd912000-03-10 22:53:23 +00003068PyObject *PyUnicode_AsUTF8String(PyObject *unicode)
3069{
Guido van Rossumd57fd912000-03-10 22:53:23 +00003070 if (!PyUnicode_Check(unicode)) {
3071 PyErr_BadArgument();
3072 return NULL;
3073 }
Barry Warsaw2dd4abf2000-08-18 06:58:15 +00003074 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003075 PyUnicode_GET_SIZE(unicode),
3076 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003077}
3078
Walter Dörwald41980ca2007-08-16 21:55:45 +00003079/* --- UTF-32 Codec ------------------------------------------------------- */
3080
3081PyObject *
3082PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003083 Py_ssize_t size,
3084 const char *errors,
3085 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00003086{
3087 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
3088}
3089
3090PyObject *
3091PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003092 Py_ssize_t size,
3093 const char *errors,
3094 int *byteorder,
3095 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00003096{
3097 const char *starts = s;
3098 Py_ssize_t startinpos;
3099 Py_ssize_t endinpos;
3100 Py_ssize_t outpos;
3101 PyUnicodeObject *unicode;
3102 Py_UNICODE *p;
3103#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00003104 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00003105 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003106#else
3107 const int pairs = 0;
3108#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00003109 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003110 int bo = 0; /* assume native ordering by default */
3111 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00003112 /* Offsets from q for retrieving bytes in the right order. */
3113#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3114 int iorder[] = {0, 1, 2, 3};
3115#else
3116 int iorder[] = {3, 2, 1, 0};
3117#endif
3118 PyObject *errorHandler = NULL;
3119 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00003120
Walter Dörwald41980ca2007-08-16 21:55:45 +00003121 q = (unsigned char *)s;
3122 e = q + size;
3123
3124 if (byteorder)
3125 bo = *byteorder;
3126
3127 /* Check for BOM marks (U+FEFF) in the input and adjust current
3128 byte order setting accordingly. In native mode, the leading BOM
3129 mark is skipped, in all other modes, it is copied to the output
3130 stream as-is (giving a ZWNBSP character). */
3131 if (bo == 0) {
3132 if (size >= 4) {
3133 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00003134 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00003135#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00003136 if (bom == 0x0000FEFF) {
3137 q += 4;
3138 bo = -1;
3139 }
3140 else if (bom == 0xFFFE0000) {
3141 q += 4;
3142 bo = 1;
3143 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003144#else
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#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003154 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003155 }
3156
3157 if (bo == -1) {
3158 /* force LE */
3159 iorder[0] = 0;
3160 iorder[1] = 1;
3161 iorder[2] = 2;
3162 iorder[3] = 3;
3163 }
3164 else if (bo == 1) {
3165 /* force BE */
3166 iorder[0] = 3;
3167 iorder[1] = 2;
3168 iorder[2] = 1;
3169 iorder[3] = 0;
3170 }
3171
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00003172 /* On narrow builds we split characters outside the BMP into two
3173 codepoints => count how much extra space we need. */
3174#ifndef Py_UNICODE_WIDE
3175 for (qq = q; qq < e; qq += 4)
3176 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
3177 pairs++;
3178#endif
3179
3180 /* This might be one to much, because of a BOM */
3181 unicode = _PyUnicode_New((size+3)/4+pairs);
3182 if (!unicode)
3183 return NULL;
3184 if (size == 0)
3185 return (PyObject *)unicode;
3186
3187 /* Unpack UTF-32 encoded data */
3188 p = unicode->str;
3189
Walter Dörwald41980ca2007-08-16 21:55:45 +00003190 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003191 Py_UCS4 ch;
3192 /* remaining bytes at the end? (size should be divisible by 4) */
3193 if (e-q<4) {
3194 if (consumed)
3195 break;
3196 errmsg = "truncated data";
3197 startinpos = ((const char *)q)-starts;
3198 endinpos = ((const char *)e)-starts;
3199 goto utf32Error;
3200 /* The remaining input chars are ignored if the callback
3201 chooses to skip the input */
3202 }
3203 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
3204 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00003205
Benjamin Peterson29060642009-01-31 22:14:21 +00003206 if (ch >= 0x110000)
3207 {
3208 errmsg = "codepoint not in range(0x110000)";
3209 startinpos = ((const char *)q)-starts;
3210 endinpos = startinpos+4;
3211 goto utf32Error;
3212 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003213#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003214 if (ch >= 0x10000)
3215 {
3216 *p++ = 0xD800 | ((ch-0x10000) >> 10);
3217 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
3218 }
3219 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00003220#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003221 *p++ = ch;
3222 q += 4;
3223 continue;
3224 utf32Error:
3225 outpos = p-PyUnicode_AS_UNICODE(unicode);
3226 if (unicode_decode_call_errorhandler(
3227 errors, &errorHandler,
3228 "utf32", errmsg,
3229 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
3230 &unicode, &outpos, &p))
3231 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003232 }
3233
3234 if (byteorder)
3235 *byteorder = bo;
3236
3237 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00003238 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003239
3240 /* Adjust length */
3241 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
3242 goto onError;
3243
3244 Py_XDECREF(errorHandler);
3245 Py_XDECREF(exc);
3246 return (PyObject *)unicode;
3247
Benjamin Peterson29060642009-01-31 22:14:21 +00003248 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00003249 Py_DECREF(unicode);
3250 Py_XDECREF(errorHandler);
3251 Py_XDECREF(exc);
3252 return NULL;
3253}
3254
3255PyObject *
3256PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003257 Py_ssize_t size,
3258 const char *errors,
3259 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00003260{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003261 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003262 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003263 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003264#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003265 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003266#else
3267 const int pairs = 0;
3268#endif
3269 /* Offsets from p for storing byte pairs in the right order. */
3270#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3271 int iorder[] = {0, 1, 2, 3};
3272#else
3273 int iorder[] = {3, 2, 1, 0};
3274#endif
3275
Benjamin Peterson29060642009-01-31 22:14:21 +00003276#define STORECHAR(CH) \
3277 do { \
3278 p[iorder[3]] = ((CH) >> 24) & 0xff; \
3279 p[iorder[2]] = ((CH) >> 16) & 0xff; \
3280 p[iorder[1]] = ((CH) >> 8) & 0xff; \
3281 p[iorder[0]] = (CH) & 0xff; \
3282 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00003283 } while(0)
3284
3285 /* In narrow builds we can output surrogate pairs as one codepoint,
3286 so we need less space. */
3287#ifndef Py_UNICODE_WIDE
3288 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00003289 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
3290 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
3291 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003292#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003293 nsize = (size - pairs + (byteorder == 0));
3294 bytesize = nsize * 4;
3295 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003296 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003297 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003298 if (v == NULL)
3299 return NULL;
3300
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003301 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003302 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003303 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003304 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00003305 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003306
3307 if (byteorder == -1) {
3308 /* force LE */
3309 iorder[0] = 0;
3310 iorder[1] = 1;
3311 iorder[2] = 2;
3312 iorder[3] = 3;
3313 }
3314 else if (byteorder == 1) {
3315 /* force BE */
3316 iorder[0] = 3;
3317 iorder[1] = 2;
3318 iorder[2] = 1;
3319 iorder[3] = 0;
3320 }
3321
3322 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003323 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003324#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003325 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
3326 Py_UCS4 ch2 = *s;
3327 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
3328 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
3329 s++;
3330 size--;
3331 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00003332 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003333#endif
3334 STORECHAR(ch);
3335 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003336
3337 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003338 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003339#undef STORECHAR
3340}
3341
3342PyObject *PyUnicode_AsUTF32String(PyObject *unicode)
3343{
3344 if (!PyUnicode_Check(unicode)) {
3345 PyErr_BadArgument();
3346 return NULL;
3347 }
3348 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003349 PyUnicode_GET_SIZE(unicode),
3350 NULL,
3351 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003352}
3353
Guido van Rossumd57fd912000-03-10 22:53:23 +00003354/* --- UTF-16 Codec ------------------------------------------------------- */
3355
Tim Peters772747b2001-08-09 22:21:55 +00003356PyObject *
3357PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003358 Py_ssize_t size,
3359 const char *errors,
3360 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003361{
Walter Dörwald69652032004-09-07 20:24:22 +00003362 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
3363}
3364
Antoine Pitrouab868312009-01-10 15:40:25 +00003365/* Two masks for fast checking of whether a C 'long' may contain
3366 UTF16-encoded surrogate characters. This is an efficient heuristic,
3367 assuming that non-surrogate characters with a code point >= 0x8000 are
3368 rare in most input.
3369 FAST_CHAR_MASK is used when the input is in native byte ordering,
3370 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00003371*/
Antoine Pitrouab868312009-01-10 15:40:25 +00003372#if (SIZEOF_LONG == 8)
3373# define FAST_CHAR_MASK 0x8000800080008000L
3374# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
3375#elif (SIZEOF_LONG == 4)
3376# define FAST_CHAR_MASK 0x80008000L
3377# define SWAPPED_FAST_CHAR_MASK 0x00800080L
3378#else
3379# error C 'long' size should be either 4 or 8!
3380#endif
3381
Walter Dörwald69652032004-09-07 20:24:22 +00003382PyObject *
3383PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003384 Py_ssize_t size,
3385 const char *errors,
3386 int *byteorder,
3387 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00003388{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003389 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003390 Py_ssize_t startinpos;
3391 Py_ssize_t endinpos;
3392 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003393 PyUnicodeObject *unicode;
3394 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00003395 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00003396 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00003397 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003398 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00003399 /* Offsets from q for retrieving byte pairs in the right order. */
3400#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3401 int ihi = 1, ilo = 0;
3402#else
3403 int ihi = 0, ilo = 1;
3404#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003405 PyObject *errorHandler = NULL;
3406 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003407
3408 /* Note: size will always be longer than the resulting Unicode
3409 character count */
3410 unicode = _PyUnicode_New(size);
3411 if (!unicode)
3412 return NULL;
3413 if (size == 0)
3414 return (PyObject *)unicode;
3415
3416 /* Unpack UTF-16 encoded data */
3417 p = unicode->str;
Tim Peters772747b2001-08-09 22:21:55 +00003418 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00003419 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003420
3421 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00003422 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003423
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003424 /* Check for BOM marks (U+FEFF) in the input and adjust current
3425 byte order setting accordingly. In native mode, the leading BOM
3426 mark is skipped, in all other modes, it is copied to the output
3427 stream as-is (giving a ZWNBSP character). */
3428 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00003429 if (size >= 2) {
3430 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003431#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00003432 if (bom == 0xFEFF) {
3433 q += 2;
3434 bo = -1;
3435 }
3436 else if (bom == 0xFFFE) {
3437 q += 2;
3438 bo = 1;
3439 }
Tim Petersced69f82003-09-16 20:30:58 +00003440#else
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 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003449#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003450 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003451 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003452
Tim Peters772747b2001-08-09 22:21:55 +00003453 if (bo == -1) {
3454 /* force LE */
3455 ihi = 1;
3456 ilo = 0;
3457 }
3458 else if (bo == 1) {
3459 /* force BE */
3460 ihi = 0;
3461 ilo = 1;
3462 }
Antoine Pitrouab868312009-01-10 15:40:25 +00003463#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3464 native_ordering = ilo < ihi;
3465#else
3466 native_ordering = ilo > ihi;
3467#endif
Tim Peters772747b2001-08-09 22:21:55 +00003468
Antoine Pitrouab868312009-01-10 15:40:25 +00003469 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00003470 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003471 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00003472 /* First check for possible aligned read of a C 'long'. Unaligned
3473 reads are more expensive, better to defer to another iteration. */
3474 if (!((size_t) q & LONG_PTR_MASK)) {
3475 /* Fast path for runs of non-surrogate chars. */
3476 register const unsigned char *_q = q;
3477 Py_UNICODE *_p = p;
3478 if (native_ordering) {
3479 /* Native ordering is simple: as long as the input cannot
3480 possibly contain a surrogate char, do an unrolled copy
3481 of several 16-bit code points to the target object.
3482 The non-surrogate check is done on several input bytes
3483 at a time (as many as a C 'long' can contain). */
3484 while (_q < aligned_end) {
3485 unsigned long data = * (unsigned long *) _q;
3486 if (data & FAST_CHAR_MASK)
3487 break;
3488 _p[0] = ((unsigned short *) _q)[0];
3489 _p[1] = ((unsigned short *) _q)[1];
3490#if (SIZEOF_LONG == 8)
3491 _p[2] = ((unsigned short *) _q)[2];
3492 _p[3] = ((unsigned short *) _q)[3];
3493#endif
3494 _q += SIZEOF_LONG;
3495 _p += SIZEOF_LONG / 2;
3496 }
3497 }
3498 else {
3499 /* Byteswapped ordering is similar, but we must decompose
3500 the copy bytewise, and take care of zero'ing out the
3501 upper bytes if the target object is in 32-bit units
3502 (that is, in UCS-4 builds). */
3503 while (_q < aligned_end) {
3504 unsigned long data = * (unsigned long *) _q;
3505 if (data & SWAPPED_FAST_CHAR_MASK)
3506 break;
3507 /* Zero upper bytes in UCS-4 builds */
3508#if (Py_UNICODE_SIZE > 2)
3509 _p[0] = 0;
3510 _p[1] = 0;
3511#if (SIZEOF_LONG == 8)
3512 _p[2] = 0;
3513 _p[3] = 0;
3514#endif
3515#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00003516 /* Issue #4916; UCS-4 builds on big endian machines must
3517 fill the two last bytes of each 4-byte unit. */
3518#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
3519# define OFF 2
3520#else
3521# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00003522#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00003523 ((unsigned char *) _p)[OFF + 1] = _q[0];
3524 ((unsigned char *) _p)[OFF + 0] = _q[1];
3525 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
3526 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
3527#if (SIZEOF_LONG == 8)
3528 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
3529 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
3530 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
3531 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
3532#endif
3533#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00003534 _q += SIZEOF_LONG;
3535 _p += SIZEOF_LONG / 2;
3536 }
3537 }
3538 p = _p;
3539 q = _q;
3540 if (q >= e)
3541 break;
3542 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003543 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003544
Benjamin Peterson14339b62009-01-31 16:36:08 +00003545 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00003546
3547 if (ch < 0xD800 || ch > 0xDFFF) {
3548 *p++ = ch;
3549 continue;
3550 }
3551
3552 /* UTF-16 code pair: */
3553 if (q > e) {
3554 errmsg = "unexpected end of data";
3555 startinpos = (((const char *)q) - 2) - starts;
3556 endinpos = ((const char *)e) + 1 - starts;
3557 goto utf16Error;
3558 }
3559 if (0xD800 <= ch && ch <= 0xDBFF) {
3560 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
3561 q += 2;
3562 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00003563#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003564 *p++ = ch;
3565 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003566#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003567 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003568#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003569 continue;
3570 }
3571 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003572 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00003573 startinpos = (((const char *)q)-4)-starts;
3574 endinpos = startinpos+2;
3575 goto utf16Error;
3576 }
3577
Benjamin Peterson14339b62009-01-31 16:36:08 +00003578 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003579 errmsg = "illegal encoding";
3580 startinpos = (((const char *)q)-2)-starts;
3581 endinpos = startinpos+2;
3582 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003583
Benjamin Peterson29060642009-01-31 22:14:21 +00003584 utf16Error:
3585 outpos = p - PyUnicode_AS_UNICODE(unicode);
3586 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00003587 errors,
3588 &errorHandler,
3589 "utf16", errmsg,
3590 &starts,
3591 (const char **)&e,
3592 &startinpos,
3593 &endinpos,
3594 &exc,
3595 (const char **)&q,
3596 &unicode,
3597 &outpos,
3598 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00003599 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003600 }
Antoine Pitrouab868312009-01-10 15:40:25 +00003601 /* remaining byte at the end? (size should be even) */
3602 if (e == q) {
3603 if (!consumed) {
3604 errmsg = "truncated data";
3605 startinpos = ((const char *)q) - starts;
3606 endinpos = ((const char *)e) + 1 - starts;
3607 outpos = p - PyUnicode_AS_UNICODE(unicode);
3608 if (unicode_decode_call_errorhandler(
3609 errors,
3610 &errorHandler,
3611 "utf16", errmsg,
3612 &starts,
3613 (const char **)&e,
3614 &startinpos,
3615 &endinpos,
3616 &exc,
3617 (const char **)&q,
3618 &unicode,
3619 &outpos,
3620 &p))
3621 goto onError;
3622 /* The remaining input chars are ignored if the callback
3623 chooses to skip the input */
3624 }
3625 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003626
3627 if (byteorder)
3628 *byteorder = bo;
3629
Walter Dörwald69652032004-09-07 20:24:22 +00003630 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00003631 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00003632
Guido van Rossumd57fd912000-03-10 22:53:23 +00003633 /* Adjust length */
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00003634 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003635 goto onError;
3636
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003637 Py_XDECREF(errorHandler);
3638 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003639 return (PyObject *)unicode;
3640
Benjamin Peterson29060642009-01-31 22:14:21 +00003641 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003642 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003643 Py_XDECREF(errorHandler);
3644 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003645 return NULL;
3646}
3647
Antoine Pitrouab868312009-01-10 15:40:25 +00003648#undef FAST_CHAR_MASK
3649#undef SWAPPED_FAST_CHAR_MASK
3650
Tim Peters772747b2001-08-09 22:21:55 +00003651PyObject *
3652PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003653 Py_ssize_t size,
3654 const char *errors,
3655 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003656{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003657 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00003658 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003659 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003660#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003661 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003662#else
3663 const int pairs = 0;
3664#endif
Tim Peters772747b2001-08-09 22:21:55 +00003665 /* Offsets from p for storing byte pairs in the right order. */
3666#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3667 int ihi = 1, ilo = 0;
3668#else
3669 int ihi = 0, ilo = 1;
3670#endif
3671
Benjamin Peterson29060642009-01-31 22:14:21 +00003672#define STORECHAR(CH) \
3673 do { \
3674 p[ihi] = ((CH) >> 8) & 0xff; \
3675 p[ilo] = (CH) & 0xff; \
3676 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00003677 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003678
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003679#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003680 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00003681 if (s[i] >= 0x10000)
3682 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003683#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003684 /* 2 * (size + pairs + (byteorder == 0)) */
3685 if (size > PY_SSIZE_T_MAX ||
3686 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00003687 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003688 nsize = size + pairs + (byteorder == 0);
3689 bytesize = nsize * 2;
3690 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003691 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003692 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003693 if (v == NULL)
3694 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003695
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003696 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003697 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003698 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00003699 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00003700 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00003701
3702 if (byteorder == -1) {
3703 /* force LE */
3704 ihi = 1;
3705 ilo = 0;
3706 }
3707 else if (byteorder == 1) {
3708 /* force BE */
3709 ihi = 0;
3710 ilo = 1;
3711 }
3712
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003713 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003714 Py_UNICODE ch = *s++;
3715 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003716#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003717 if (ch >= 0x10000) {
3718 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
3719 ch = 0xD800 | ((ch-0x10000) >> 10);
3720 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003721#endif
Tim Peters772747b2001-08-09 22:21:55 +00003722 STORECHAR(ch);
3723 if (ch2)
3724 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003725 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003726
3727 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003728 return v;
Tim Peters772747b2001-08-09 22:21:55 +00003729#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00003730}
3731
3732PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
3733{
3734 if (!PyUnicode_Check(unicode)) {
3735 PyErr_BadArgument();
3736 return NULL;
3737 }
3738 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003739 PyUnicode_GET_SIZE(unicode),
3740 NULL,
3741 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003742}
3743
3744/* --- Unicode Escape Codec ----------------------------------------------- */
3745
Fredrik Lundh06d12682001-01-24 07:59:11 +00003746static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00003747
Guido van Rossumd57fd912000-03-10 22:53:23 +00003748PyObject *PyUnicode_DecodeUnicodeEscape(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003749 Py_ssize_t size,
3750 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003751{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003752 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003753 Py_ssize_t startinpos;
3754 Py_ssize_t endinpos;
3755 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003756 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003757 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003758 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003759 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003760 char* message;
3761 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003762 PyObject *errorHandler = NULL;
3763 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003764
Guido van Rossumd57fd912000-03-10 22:53:23 +00003765 /* Escaped strings will always be longer than the resulting
3766 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003767 length after conversion to the true value.
3768 (but if the error callback returns a long replacement string
3769 we'll have to allocate more space) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003770 v = _PyUnicode_New(size);
3771 if (v == NULL)
3772 goto onError;
3773 if (size == 0)
3774 return (PyObject *)v;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003775
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003776 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003777 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003778
Guido van Rossumd57fd912000-03-10 22:53:23 +00003779 while (s < end) {
3780 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00003781 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003782 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003783
3784 /* Non-escape characters are interpreted as Unicode ordinals */
3785 if (*s != '\\') {
Fredrik Lundhccc74732001-02-18 22:13:49 +00003786 *p++ = (unsigned char) *s++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003787 continue;
3788 }
3789
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003790 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003791 /* \ - Escapes */
3792 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003793 c = *s++;
3794 if (s > end)
3795 c = '\0'; /* Invalid after \ */
3796 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003797
Benjamin Peterson29060642009-01-31 22:14:21 +00003798 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003799 case '\n': break;
3800 case '\\': *p++ = '\\'; break;
3801 case '\'': *p++ = '\''; break;
3802 case '\"': *p++ = '\"'; break;
3803 case 'b': *p++ = '\b'; break;
3804 case 'f': *p++ = '\014'; break; /* FF */
3805 case 't': *p++ = '\t'; break;
3806 case 'n': *p++ = '\n'; break;
3807 case 'r': *p++ = '\r'; break;
3808 case 'v': *p++ = '\013'; break; /* VT */
3809 case 'a': *p++ = '\007'; break; /* BEL, not classic C */
3810
Benjamin Peterson29060642009-01-31 22:14:21 +00003811 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003812 case '0': case '1': case '2': case '3':
3813 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003814 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003815 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003816 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003817 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003818 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00003819 }
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003820 *p++ = x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003821 break;
3822
Benjamin Peterson29060642009-01-31 22:14:21 +00003823 /* hex escapes */
3824 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003825 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003826 digits = 2;
3827 message = "truncated \\xXX escape";
3828 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003829
Benjamin Peterson29060642009-01-31 22:14:21 +00003830 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003831 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003832 digits = 4;
3833 message = "truncated \\uXXXX escape";
3834 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003835
Benjamin Peterson29060642009-01-31 22:14:21 +00003836 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00003837 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003838 digits = 8;
3839 message = "truncated \\UXXXXXXXX escape";
3840 hexescape:
3841 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003842 outpos = p-PyUnicode_AS_UNICODE(v);
3843 if (s+digits>end) {
3844 endinpos = size;
3845 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003846 errors, &errorHandler,
3847 "unicodeescape", "end of string in escape sequence",
3848 &starts, &end, &startinpos, &endinpos, &exc, &s,
3849 &v, &outpos, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003850 goto onError;
3851 goto nextByte;
3852 }
3853 for (i = 0; i < digits; ++i) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00003854 c = (unsigned char) s[i];
David Malcolm96960882010-11-05 17:23:41 +00003855 if (!Py_ISXDIGIT(c)) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003856 endinpos = (s+i+1)-starts;
3857 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003858 errors, &errorHandler,
3859 "unicodeescape", message,
3860 &starts, &end, &startinpos, &endinpos, &exc, &s,
3861 &v, &outpos, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00003862 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003863 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00003864 }
3865 chr = (chr<<4) & ~0xF;
3866 if (c >= '0' && c <= '9')
3867 chr += c - '0';
3868 else if (c >= 'a' && c <= 'f')
3869 chr += 10 + c - 'a';
3870 else
3871 chr += 10 + c - 'A';
3872 }
3873 s += i;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00003874 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003875 /* _decoding_error will have already written into the
3876 target buffer. */
3877 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003878 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00003879 /* when we get here, chr is a 32-bit unicode character */
3880 if (chr <= 0xffff)
3881 /* UCS-2 character */
3882 *p++ = (Py_UNICODE) chr;
3883 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00003884 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00003885 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00003886#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003887 *p++ = chr;
3888#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00003889 chr -= 0x10000L;
3890 *p++ = 0xD800 + (Py_UNICODE) (chr >> 10);
Fredrik Lundh45714e92001-06-26 16:39:36 +00003891 *p++ = 0xDC00 + (Py_UNICODE) (chr & 0x03FF);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003892#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00003893 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003894 endinpos = s-starts;
3895 outpos = p-PyUnicode_AS_UNICODE(v);
3896 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003897 errors, &errorHandler,
3898 "unicodeescape", "illegal Unicode character",
3899 &starts, &end, &startinpos, &endinpos, &exc, &s,
3900 &v, &outpos, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00003901 goto onError;
3902 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00003903 break;
3904
Benjamin Peterson29060642009-01-31 22:14:21 +00003905 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00003906 case 'N':
3907 message = "malformed \\N character escape";
3908 if (ucnhash_CAPI == NULL) {
3909 /* load the unicode data module */
Benjamin Petersonb173f782009-05-05 22:31:58 +00003910 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00003911 if (ucnhash_CAPI == NULL)
3912 goto ucnhashError;
3913 }
3914 if (*s == '{') {
3915 const char *start = s+1;
3916 /* look for the closing brace */
3917 while (*s != '}' && s < end)
3918 s++;
3919 if (s > start && s < end && *s == '}') {
3920 /* found a name. look it up in the unicode database */
3921 message = "unknown Unicode character name";
3922 s++;
Martin v. Löwis480f1bb2006-03-09 23:38:20 +00003923 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1), &chr))
Fredrik Lundhccc74732001-02-18 22:13:49 +00003924 goto store;
3925 }
3926 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003927 endinpos = s-starts;
3928 outpos = p-PyUnicode_AS_UNICODE(v);
3929 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003930 errors, &errorHandler,
3931 "unicodeescape", message,
3932 &starts, &end, &startinpos, &endinpos, &exc, &s,
3933 &v, &outpos, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00003934 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003935 break;
3936
3937 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00003938 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003939 message = "\\ at end of string";
3940 s--;
3941 endinpos = s-starts;
3942 outpos = p-PyUnicode_AS_UNICODE(v);
3943 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003944 errors, &errorHandler,
3945 "unicodeescape", message,
3946 &starts, &end, &startinpos, &endinpos, &exc, &s,
3947 &v, &outpos, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00003948 goto onError;
3949 }
3950 else {
3951 *p++ = '\\';
3952 *p++ = (unsigned char)s[-1];
3953 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00003954 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003955 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003956 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003957 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003958 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003959 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003960 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00003961 Py_XDECREF(errorHandler);
3962 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003963 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00003964
Benjamin Peterson29060642009-01-31 22:14:21 +00003965 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00003966 PyErr_SetString(
3967 PyExc_UnicodeError,
3968 "\\N escapes not supported (can't load unicodedata module)"
3969 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003970 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003971 Py_XDECREF(errorHandler);
3972 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00003973 return NULL;
3974
Benjamin Peterson29060642009-01-31 22:14:21 +00003975 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003976 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003977 Py_XDECREF(errorHandler);
3978 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003979 return NULL;
3980}
3981
3982/* Return a Unicode-Escape string version of the Unicode object.
3983
3984 If quotes is true, the string is enclosed in u"" or u'' quotes as
3985 appropriate.
3986
3987*/
3988
Thomas Wouters477c8d52006-05-27 19:21:47 +00003989Py_LOCAL_INLINE(const Py_UNICODE *) findchar(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003990 Py_ssize_t size,
3991 Py_UNICODE ch)
Thomas Wouters477c8d52006-05-27 19:21:47 +00003992{
3993 /* like wcschr, but doesn't stop at NULL characters */
3994
3995 while (size-- > 0) {
3996 if (*s == ch)
3997 return s;
3998 s++;
3999 }
4000
4001 return NULL;
4002}
Barry Warsaw51ac5802000-03-20 16:36:48 +00004003
Walter Dörwald79e913e2007-05-12 11:08:06 +00004004static const char *hexdigits = "0123456789abcdef";
4005
4006PyObject *PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004007 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004008{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004009 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004010 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004011
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004012#ifdef Py_UNICODE_WIDE
4013 const Py_ssize_t expandsize = 10;
4014#else
4015 const Py_ssize_t expandsize = 6;
4016#endif
4017
Thomas Wouters89f507f2006-12-13 04:49:30 +00004018 /* XXX(nnorwitz): rather than over-allocating, it would be
4019 better to choose a different scheme. Perhaps scan the
4020 first N-chars of the string and allocate based on that size.
4021 */
4022 /* Initial allocation is based on the longest-possible unichr
4023 escape.
4024
4025 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
4026 unichr, so in this case it's the longest unichr escape. In
4027 narrow (UTF-16) builds this is five chars per source unichr
4028 since there are two unichrs in the surrogate pair, so in narrow
4029 (UTF-16) builds it's not the longest unichr escape.
4030
4031 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
4032 so in the narrow (UTF-16) build case it's the longest unichr
4033 escape.
4034 */
4035
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004036 if (size == 0)
4037 return PyBytes_FromStringAndSize(NULL, 0);
4038
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004039 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00004040 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004041
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004042 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00004043 2
4044 + expandsize*size
4045 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004046 if (repr == NULL)
4047 return NULL;
4048
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004049 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004050
Guido van Rossumd57fd912000-03-10 22:53:23 +00004051 while (size-- > 0) {
4052 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004053
Walter Dörwald79e913e2007-05-12 11:08:06 +00004054 /* Escape backslashes */
4055 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004056 *p++ = '\\';
4057 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00004058 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004059 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004060
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00004061#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004062 /* Map 21-bit characters to '\U00xxxxxx' */
4063 else if (ch >= 0x10000) {
4064 *p++ = '\\';
4065 *p++ = 'U';
Walter Dörwald79e913e2007-05-12 11:08:06 +00004066 *p++ = hexdigits[(ch >> 28) & 0x0000000F];
4067 *p++ = hexdigits[(ch >> 24) & 0x0000000F];
4068 *p++ = hexdigits[(ch >> 20) & 0x0000000F];
4069 *p++ = hexdigits[(ch >> 16) & 0x0000000F];
4070 *p++ = hexdigits[(ch >> 12) & 0x0000000F];
4071 *p++ = hexdigits[(ch >> 8) & 0x0000000F];
4072 *p++ = hexdigits[(ch >> 4) & 0x0000000F];
4073 *p++ = hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00004074 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004075 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00004076#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004077 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
4078 else if (ch >= 0xD800 && ch < 0xDC00) {
4079 Py_UNICODE ch2;
4080 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00004081
Benjamin Peterson29060642009-01-31 22:14:21 +00004082 ch2 = *s++;
4083 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00004084 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004085 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
4086 *p++ = '\\';
4087 *p++ = 'U';
4088 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
4089 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
4090 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
4091 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
4092 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
4093 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
4094 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
4095 *p++ = hexdigits[ucs & 0x0000000F];
4096 continue;
4097 }
4098 /* Fall through: isolated surrogates are copied as-is */
4099 s--;
4100 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004101 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00004102#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00004103
Guido van Rossumd57fd912000-03-10 22:53:23 +00004104 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00004105 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004106 *p++ = '\\';
4107 *p++ = 'u';
Walter Dörwald79e913e2007-05-12 11:08:06 +00004108 *p++ = hexdigits[(ch >> 12) & 0x000F];
4109 *p++ = hexdigits[(ch >> 8) & 0x000F];
4110 *p++ = hexdigits[(ch >> 4) & 0x000F];
4111 *p++ = hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00004112 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004113
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00004114 /* Map special whitespace to '\t', \n', '\r' */
4115 else if (ch == '\t') {
4116 *p++ = '\\';
4117 *p++ = 't';
4118 }
4119 else if (ch == '\n') {
4120 *p++ = '\\';
4121 *p++ = 'n';
4122 }
4123 else if (ch == '\r') {
4124 *p++ = '\\';
4125 *p++ = 'r';
4126 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004127
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00004128 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00004129 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004130 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00004131 *p++ = 'x';
Walter Dörwald79e913e2007-05-12 11:08:06 +00004132 *p++ = hexdigits[(ch >> 4) & 0x000F];
4133 *p++ = hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00004134 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004135
Guido van Rossumd57fd912000-03-10 22:53:23 +00004136 /* Copy everything else as-is */
4137 else
4138 *p++ = (char) ch;
4139 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004140
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004141 assert(p - PyBytes_AS_STRING(repr) > 0);
4142 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
4143 return NULL;
4144 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004145}
4146
Alexandre Vassalotti2056bed2008-12-27 19:46:35 +00004147PyObject *PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004148{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004149 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004150 if (!PyUnicode_Check(unicode)) {
4151 PyErr_BadArgument();
4152 return NULL;
4153 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00004154 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
4155 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004156 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004157}
4158
4159/* --- Raw Unicode Escape Codec ------------------------------------------- */
4160
4161PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004162 Py_ssize_t size,
4163 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004164{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004165 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004166 Py_ssize_t startinpos;
4167 Py_ssize_t endinpos;
4168 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004169 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004170 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004171 const char *end;
4172 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004173 PyObject *errorHandler = NULL;
4174 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00004175
Guido van Rossumd57fd912000-03-10 22:53:23 +00004176 /* Escaped strings will always be longer than the resulting
4177 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004178 length after conversion to the true value. (But decoding error
4179 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004180 v = _PyUnicode_New(size);
4181 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004182 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004183 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004184 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004185 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004186 end = s + size;
4187 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004188 unsigned char c;
4189 Py_UCS4 x;
4190 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004191 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004192
Benjamin Peterson29060642009-01-31 22:14:21 +00004193 /* Non-escape characters are interpreted as Unicode ordinals */
4194 if (*s != '\\') {
4195 *p++ = (unsigned char)*s++;
4196 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004197 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004198 startinpos = s-starts;
4199
4200 /* \u-escapes are only interpreted iff the number of leading
4201 backslashes if odd */
4202 bs = s;
4203 for (;s < end;) {
4204 if (*s != '\\')
4205 break;
4206 *p++ = (unsigned char)*s++;
4207 }
4208 if (((s - bs) & 1) == 0 ||
4209 s >= end ||
4210 (*s != 'u' && *s != 'U')) {
4211 continue;
4212 }
4213 p--;
4214 count = *s=='u' ? 4 : 8;
4215 s++;
4216
4217 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
4218 outpos = p-PyUnicode_AS_UNICODE(v);
4219 for (x = 0, i = 0; i < count; ++i, ++s) {
4220 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00004221 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004222 endinpos = s-starts;
4223 if (unicode_decode_call_errorhandler(
4224 errors, &errorHandler,
4225 "rawunicodeescape", "truncated \\uXXXX",
4226 &starts, &end, &startinpos, &endinpos, &exc, &s,
4227 &v, &outpos, &p))
4228 goto onError;
4229 goto nextByte;
4230 }
4231 x = (x<<4) & ~0xF;
4232 if (c >= '0' && c <= '9')
4233 x += c - '0';
4234 else if (c >= 'a' && c <= 'f')
4235 x += 10 + c - 'a';
4236 else
4237 x += 10 + c - 'A';
4238 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00004239 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00004240 /* UCS-2 character */
4241 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004242 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004243 /* UCS-4 character. Either store directly, or as
4244 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00004245#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004246 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004247#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004248 x -= 0x10000L;
4249 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
4250 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00004251#endif
4252 } else {
4253 endinpos = s-starts;
4254 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004255 if (unicode_decode_call_errorhandler(
4256 errors, &errorHandler,
4257 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00004258 &starts, &end, &startinpos, &endinpos, &exc, &s,
4259 &v, &outpos, &p))
4260 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004261 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004262 nextByte:
4263 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004264 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004265 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004266 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004267 Py_XDECREF(errorHandler);
4268 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004269 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004270
Benjamin Peterson29060642009-01-31 22:14:21 +00004271 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004272 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004273 Py_XDECREF(errorHandler);
4274 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004275 return NULL;
4276}
4277
4278PyObject *PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004279 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004280{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004281 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004282 char *p;
4283 char *q;
4284
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004285#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004286 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004287#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004288 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004289#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00004290
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004291 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00004292 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00004293
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004294 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004295 if (repr == NULL)
4296 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00004297 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004298 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004299
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004300 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004301 while (size-- > 0) {
4302 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004303#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004304 /* Map 32-bit characters to '\Uxxxxxxxx' */
4305 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004306 *p++ = '\\';
4307 *p++ = 'U';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00004308 *p++ = hexdigits[(ch >> 28) & 0xf];
4309 *p++ = hexdigits[(ch >> 24) & 0xf];
4310 *p++ = hexdigits[(ch >> 20) & 0xf];
4311 *p++ = hexdigits[(ch >> 16) & 0xf];
4312 *p++ = hexdigits[(ch >> 12) & 0xf];
4313 *p++ = hexdigits[(ch >> 8) & 0xf];
4314 *p++ = hexdigits[(ch >> 4) & 0xf];
4315 *p++ = hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00004316 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004317 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00004318#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004319 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
4320 if (ch >= 0xD800 && ch < 0xDC00) {
4321 Py_UNICODE ch2;
4322 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004323
Benjamin Peterson29060642009-01-31 22:14:21 +00004324 ch2 = *s++;
4325 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00004326 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004327 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
4328 *p++ = '\\';
4329 *p++ = 'U';
4330 *p++ = hexdigits[(ucs >> 28) & 0xf];
4331 *p++ = hexdigits[(ucs >> 24) & 0xf];
4332 *p++ = hexdigits[(ucs >> 20) & 0xf];
4333 *p++ = hexdigits[(ucs >> 16) & 0xf];
4334 *p++ = hexdigits[(ucs >> 12) & 0xf];
4335 *p++ = hexdigits[(ucs >> 8) & 0xf];
4336 *p++ = hexdigits[(ucs >> 4) & 0xf];
4337 *p++ = hexdigits[ucs & 0xf];
4338 continue;
4339 }
4340 /* Fall through: isolated surrogates are copied as-is */
4341 s--;
4342 size++;
4343 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004344#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004345 /* Map 16-bit characters to '\uxxxx' */
4346 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004347 *p++ = '\\';
4348 *p++ = 'u';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00004349 *p++ = hexdigits[(ch >> 12) & 0xf];
4350 *p++ = hexdigits[(ch >> 8) & 0xf];
4351 *p++ = hexdigits[(ch >> 4) & 0xf];
4352 *p++ = hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00004353 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004354 /* Copy everything else as-is */
4355 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00004356 *p++ = (char) ch;
4357 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00004358 size = p - q;
4359
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004360 assert(size > 0);
4361 if (_PyBytes_Resize(&repr, size) < 0)
4362 return NULL;
4363 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004364}
4365
4366PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
4367{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004368 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004369 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00004370 PyErr_BadArgument();
4371 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004372 }
Walter Dörwald711005d2007-05-12 12:03:26 +00004373 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
4374 PyUnicode_GET_SIZE(unicode));
4375
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004376 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004377}
4378
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004379/* --- Unicode Internal Codec ------------------------------------------- */
4380
4381PyObject *_PyUnicode_DecodeUnicodeInternal(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004382 Py_ssize_t size,
4383 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004384{
4385 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004386 Py_ssize_t startinpos;
4387 Py_ssize_t endinpos;
4388 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004389 PyUnicodeObject *v;
4390 Py_UNICODE *p;
4391 const char *end;
4392 const char *reason;
4393 PyObject *errorHandler = NULL;
4394 PyObject *exc = NULL;
4395
Neal Norwitzd43069c2006-01-08 01:12:10 +00004396#ifdef Py_UNICODE_WIDE
4397 Py_UNICODE unimax = PyUnicode_GetMax();
4398#endif
4399
Thomas Wouters89f507f2006-12-13 04:49:30 +00004400 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004401 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
4402 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004403 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004404 if (PyUnicode_GetSize((PyObject *)v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004405 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004406 p = PyUnicode_AS_UNICODE(v);
4407 end = s + size;
4408
4409 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00004410 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004411 /* We have to sanity check the raw data, otherwise doom looms for
4412 some malformed UCS-4 data. */
4413 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00004414#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004415 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00004416#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004417 end-s < Py_UNICODE_SIZE
4418 )
Benjamin Peterson29060642009-01-31 22:14:21 +00004419 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004420 startinpos = s - starts;
4421 if (end-s < Py_UNICODE_SIZE) {
4422 endinpos = end-starts;
4423 reason = "truncated input";
4424 }
4425 else {
4426 endinpos = s - starts + Py_UNICODE_SIZE;
4427 reason = "illegal code point (> 0x10FFFF)";
4428 }
4429 outpos = p - PyUnicode_AS_UNICODE(v);
4430 if (unicode_decode_call_errorhandler(
4431 errors, &errorHandler,
4432 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00004433 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00004434 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004435 goto onError;
4436 }
4437 }
4438 else {
4439 p++;
4440 s += Py_UNICODE_SIZE;
4441 }
4442 }
4443
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004444 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004445 goto onError;
4446 Py_XDECREF(errorHandler);
4447 Py_XDECREF(exc);
4448 return (PyObject *)v;
4449
Benjamin Peterson29060642009-01-31 22:14:21 +00004450 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004451 Py_XDECREF(v);
4452 Py_XDECREF(errorHandler);
4453 Py_XDECREF(exc);
4454 return NULL;
4455}
4456
Guido van Rossumd57fd912000-03-10 22:53:23 +00004457/* --- Latin-1 Codec ------------------------------------------------------ */
4458
4459PyObject *PyUnicode_DecodeLatin1(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004460 Py_ssize_t size,
4461 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004462{
4463 PyUnicodeObject *v;
4464 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00004465 const char *e, *unrolled_end;
Tim Petersced69f82003-09-16 20:30:58 +00004466
Guido van Rossumd57fd912000-03-10 22:53:23 +00004467 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004468 if (size == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004469 Py_UNICODE r = *(unsigned char*)s;
4470 return PyUnicode_FromUnicode(&r, 1);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004471 }
4472
Guido van Rossumd57fd912000-03-10 22:53:23 +00004473 v = _PyUnicode_New(size);
4474 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004475 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004476 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004477 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004478 p = PyUnicode_AS_UNICODE(v);
Antoine Pitrouab868312009-01-10 15:40:25 +00004479 e = s + size;
4480 /* Unrolling the copy makes it much faster by reducing the looping
4481 overhead. This is similar to what many memcpy() implementations do. */
4482 unrolled_end = e - 4;
4483 while (s < unrolled_end) {
4484 p[0] = (unsigned char) s[0];
4485 p[1] = (unsigned char) s[1];
4486 p[2] = (unsigned char) s[2];
4487 p[3] = (unsigned char) s[3];
4488 s += 4;
4489 p += 4;
4490 }
4491 while (s < e)
4492 *p++ = (unsigned char) *s++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004493 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004494
Benjamin Peterson29060642009-01-31 22:14:21 +00004495 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004496 Py_XDECREF(v);
4497 return NULL;
4498}
4499
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004500/* create or adjust a UnicodeEncodeError */
4501static void make_encode_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004502 const char *encoding,
4503 const Py_UNICODE *unicode, Py_ssize_t size,
4504 Py_ssize_t startpos, Py_ssize_t endpos,
4505 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004506{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004507 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004508 *exceptionObject = PyUnicodeEncodeError_Create(
4509 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004510 }
4511 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004512 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
4513 goto onError;
4514 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
4515 goto onError;
4516 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
4517 goto onError;
4518 return;
4519 onError:
4520 Py_DECREF(*exceptionObject);
4521 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004522 }
4523}
4524
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004525/* raises a UnicodeEncodeError */
4526static void raise_encode_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004527 const char *encoding,
4528 const Py_UNICODE *unicode, Py_ssize_t size,
4529 Py_ssize_t startpos, Py_ssize_t endpos,
4530 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004531{
4532 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004533 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004534 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004535 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004536}
4537
4538/* error handling callback helper:
4539 build arguments, call the callback and check the arguments,
4540 put the result into newpos and return the replacement string, which
4541 has to be freed by the caller */
4542static PyObject *unicode_encode_call_errorhandler(const char *errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00004543 PyObject **errorHandler,
4544 const char *encoding, const char *reason,
4545 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
4546 Py_ssize_t startpos, Py_ssize_t endpos,
4547 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004548{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004549 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004550
4551 PyObject *restuple;
4552 PyObject *resunicode;
4553
4554 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004555 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004556 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004557 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004558 }
4559
4560 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004561 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004562 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004563 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004564
4565 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00004566 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004567 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004568 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004569 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004570 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004571 Py_DECREF(restuple);
4572 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004573 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004574 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00004575 &resunicode, newpos)) {
4576 Py_DECREF(restuple);
4577 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004578 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004579 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
4580 PyErr_SetString(PyExc_TypeError, &argparse[3]);
4581 Py_DECREF(restuple);
4582 return NULL;
4583 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004584 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004585 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004586 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004587 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
4588 Py_DECREF(restuple);
4589 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004590 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004591 Py_INCREF(resunicode);
4592 Py_DECREF(restuple);
4593 return resunicode;
4594}
4595
4596static PyObject *unicode_encode_ucs1(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004597 Py_ssize_t size,
4598 const char *errors,
4599 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004600{
4601 /* output object */
4602 PyObject *res;
4603 /* pointers to the beginning and end+1 of input */
4604 const Py_UNICODE *startp = p;
4605 const Py_UNICODE *endp = p + size;
4606 /* pointer to the beginning of the unencodable characters */
4607 /* const Py_UNICODE *badp = NULL; */
4608 /* pointer into the output */
4609 char *str;
4610 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00004611 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004612 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
4613 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004614 PyObject *errorHandler = NULL;
4615 PyObject *exc = NULL;
4616 /* the following variable is used for caching string comparisons
4617 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
4618 int known_errorHandler = -1;
4619
4620 /* allocate enough for a simple encoding without
4621 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00004622 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00004623 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004624 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004625 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00004626 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004627 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004628 ressize = size;
4629
4630 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004631 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004632
Benjamin Peterson29060642009-01-31 22:14:21 +00004633 /* can we encode this? */
4634 if (c<limit) {
4635 /* no overflow check, because we know that the space is enough */
4636 *str++ = (char)c;
4637 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004638 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004639 else {
4640 Py_ssize_t unicodepos = p-startp;
4641 Py_ssize_t requiredsize;
4642 PyObject *repunicode;
4643 Py_ssize_t repsize;
4644 Py_ssize_t newpos;
4645 Py_ssize_t respos;
4646 Py_UNICODE *uni2;
4647 /* startpos for collecting unencodable chars */
4648 const Py_UNICODE *collstart = p;
4649 const Py_UNICODE *collend = p;
4650 /* find all unecodable characters */
4651 while ((collend < endp) && ((*collend)>=limit))
4652 ++collend;
4653 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
4654 if (known_errorHandler==-1) {
4655 if ((errors==NULL) || (!strcmp(errors, "strict")))
4656 known_errorHandler = 1;
4657 else if (!strcmp(errors, "replace"))
4658 known_errorHandler = 2;
4659 else if (!strcmp(errors, "ignore"))
4660 known_errorHandler = 3;
4661 else if (!strcmp(errors, "xmlcharrefreplace"))
4662 known_errorHandler = 4;
4663 else
4664 known_errorHandler = 0;
4665 }
4666 switch (known_errorHandler) {
4667 case 1: /* strict */
4668 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
4669 goto onError;
4670 case 2: /* replace */
4671 while (collstart++<collend)
4672 *str++ = '?'; /* fall through */
4673 case 3: /* ignore */
4674 p = collend;
4675 break;
4676 case 4: /* xmlcharrefreplace */
4677 respos = str - PyBytes_AS_STRING(res);
4678 /* determine replacement size (temporarily (mis)uses p) */
4679 for (p = collstart, repsize = 0; p < collend; ++p) {
4680 if (*p<10)
4681 repsize += 2+1+1;
4682 else if (*p<100)
4683 repsize += 2+2+1;
4684 else if (*p<1000)
4685 repsize += 2+3+1;
4686 else if (*p<10000)
4687 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00004688#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004689 else
4690 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00004691#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004692 else if (*p<100000)
4693 repsize += 2+5+1;
4694 else if (*p<1000000)
4695 repsize += 2+6+1;
4696 else
4697 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004698#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004699 }
4700 requiredsize = respos+repsize+(endp-collend);
4701 if (requiredsize > ressize) {
4702 if (requiredsize<2*ressize)
4703 requiredsize = 2*ressize;
4704 if (_PyBytes_Resize(&res, requiredsize))
4705 goto onError;
4706 str = PyBytes_AS_STRING(res) + respos;
4707 ressize = requiredsize;
4708 }
4709 /* generate replacement (temporarily (mis)uses p) */
4710 for (p = collstart; p < collend; ++p) {
4711 str += sprintf(str, "&#%d;", (int)*p);
4712 }
4713 p = collend;
4714 break;
4715 default:
4716 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
4717 encoding, reason, startp, size, &exc,
4718 collstart-startp, collend-startp, &newpos);
4719 if (repunicode == NULL)
4720 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004721 if (PyBytes_Check(repunicode)) {
4722 /* Directly copy bytes result to output. */
4723 repsize = PyBytes_Size(repunicode);
4724 if (repsize > 1) {
4725 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00004726 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00004727 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
4728 Py_DECREF(repunicode);
4729 goto onError;
4730 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00004731 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004732 ressize += repsize-1;
4733 }
4734 memcpy(str, PyBytes_AsString(repunicode), repsize);
4735 str += repsize;
4736 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004737 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00004738 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004739 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004740 /* need more space? (at least enough for what we
4741 have+the replacement+the rest of the string, so
4742 we won't have to check space for encodable characters) */
4743 respos = str - PyBytes_AS_STRING(res);
4744 repsize = PyUnicode_GET_SIZE(repunicode);
4745 requiredsize = respos+repsize+(endp-collend);
4746 if (requiredsize > ressize) {
4747 if (requiredsize<2*ressize)
4748 requiredsize = 2*ressize;
4749 if (_PyBytes_Resize(&res, requiredsize)) {
4750 Py_DECREF(repunicode);
4751 goto onError;
4752 }
4753 str = PyBytes_AS_STRING(res) + respos;
4754 ressize = requiredsize;
4755 }
4756 /* check if there is anything unencodable in the replacement
4757 and copy it to the output */
4758 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
4759 c = *uni2;
4760 if (c >= limit) {
4761 raise_encode_exception(&exc, encoding, startp, size,
4762 unicodepos, unicodepos+1, reason);
4763 Py_DECREF(repunicode);
4764 goto onError;
4765 }
4766 *str = (char)c;
4767 }
4768 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004769 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00004770 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004771 }
4772 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004773 /* Resize if we allocated to much */
4774 size = str - PyBytes_AS_STRING(res);
4775 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00004776 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004777 if (_PyBytes_Resize(&res, size) < 0)
4778 goto onError;
4779 }
4780
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004781 Py_XDECREF(errorHandler);
4782 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004783 return res;
4784
4785 onError:
4786 Py_XDECREF(res);
4787 Py_XDECREF(errorHandler);
4788 Py_XDECREF(exc);
4789 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004790}
4791
Guido van Rossumd57fd912000-03-10 22:53:23 +00004792PyObject *PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004793 Py_ssize_t size,
4794 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004795{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004796 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004797}
4798
4799PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
4800{
4801 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004802 PyErr_BadArgument();
4803 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004804 }
4805 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004806 PyUnicode_GET_SIZE(unicode),
4807 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004808}
4809
4810/* --- 7-bit ASCII Codec -------------------------------------------------- */
4811
Guido van Rossumd57fd912000-03-10 22:53:23 +00004812PyObject *PyUnicode_DecodeASCII(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004813 Py_ssize_t size,
4814 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004815{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004816 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004817 PyUnicodeObject *v;
4818 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004819 Py_ssize_t startinpos;
4820 Py_ssize_t endinpos;
4821 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004822 const char *e;
4823 PyObject *errorHandler = NULL;
4824 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00004825
Guido van Rossumd57fd912000-03-10 22:53:23 +00004826 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004827 if (size == 1 && *(unsigned char*)s < 128) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004828 Py_UNICODE r = *(unsigned char*)s;
4829 return PyUnicode_FromUnicode(&r, 1);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004830 }
Tim Petersced69f82003-09-16 20:30:58 +00004831
Guido van Rossumd57fd912000-03-10 22:53:23 +00004832 v = _PyUnicode_New(size);
4833 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004834 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004835 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004836 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004837 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004838 e = s + size;
4839 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004840 register unsigned char c = (unsigned char)*s;
4841 if (c < 128) {
4842 *p++ = c;
4843 ++s;
4844 }
4845 else {
4846 startinpos = s-starts;
4847 endinpos = startinpos + 1;
4848 outpos = p - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
4849 if (unicode_decode_call_errorhandler(
4850 errors, &errorHandler,
4851 "ascii", "ordinal not in range(128)",
4852 &starts, &e, &startinpos, &endinpos, &exc, &s,
4853 &v, &outpos, &p))
4854 goto onError;
4855 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004856 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00004857 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00004858 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
4859 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004860 Py_XDECREF(errorHandler);
4861 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004862 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004863
Benjamin Peterson29060642009-01-31 22:14:21 +00004864 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004865 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004866 Py_XDECREF(errorHandler);
4867 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004868 return NULL;
4869}
4870
Guido van Rossumd57fd912000-03-10 22:53:23 +00004871PyObject *PyUnicode_EncodeASCII(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004872 Py_ssize_t size,
4873 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004874{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004875 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004876}
4877
4878PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
4879{
4880 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004881 PyErr_BadArgument();
4882 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004883 }
4884 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004885 PyUnicode_GET_SIZE(unicode),
4886 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004887}
4888
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004889#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004890
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004891/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004892
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00004893#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004894#define NEED_RETRY
4895#endif
4896
4897/* XXX This code is limited to "true" double-byte encodings, as
4898 a) it assumes an incomplete character consists of a single byte, and
4899 b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
Benjamin Peterson29060642009-01-31 22:14:21 +00004900 encodings, see IsDBCSLeadByteEx documentation. */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004901
4902static int is_dbcs_lead_byte(const char *s, int offset)
4903{
4904 const char *curr = s + offset;
4905
4906 if (IsDBCSLeadByte(*curr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004907 const char *prev = CharPrev(s, curr);
4908 return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004909 }
4910 return 0;
4911}
4912
4913/*
4914 * Decode MBCS string into unicode object. If 'final' is set, converts
4915 * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
4916 */
4917static int decode_mbcs(PyUnicodeObject **v,
Benjamin Peterson29060642009-01-31 22:14:21 +00004918 const char *s, /* MBCS string */
4919 int size, /* sizeof MBCS string */
Victor Stinner554f3f02010-06-16 23:33:54 +00004920 int final,
4921 const char *errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004922{
4923 Py_UNICODE *p;
Victor Stinner554f3f02010-06-16 23:33:54 +00004924 Py_ssize_t n;
4925 DWORD usize;
4926 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004927
4928 assert(size >= 0);
4929
Victor Stinner554f3f02010-06-16 23:33:54 +00004930 /* check and handle 'errors' arg */
4931 if (errors==NULL || strcmp(errors, "strict")==0)
4932 flags = MB_ERR_INVALID_CHARS;
4933 else if (strcmp(errors, "ignore")==0)
4934 flags = 0;
4935 else {
4936 PyErr_Format(PyExc_ValueError,
4937 "mbcs encoding does not support errors='%s'",
4938 errors);
4939 return -1;
4940 }
4941
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004942 /* Skip trailing lead-byte unless 'final' is set */
4943 if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
Benjamin Peterson29060642009-01-31 22:14:21 +00004944 --size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004945
4946 /* First get the size of the result */
4947 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00004948 usize = MultiByteToWideChar(CP_ACP, flags, s, size, NULL, 0);
4949 if (usize==0)
4950 goto mbcs_decode_error;
4951 } else
4952 usize = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004953
4954 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004955 /* Create unicode object */
4956 *v = _PyUnicode_New(usize);
4957 if (*v == NULL)
4958 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00004959 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004960 }
4961 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004962 /* Extend unicode object */
4963 n = PyUnicode_GET_SIZE(*v);
4964 if (_PyUnicode_Resize(v, n + usize) < 0)
4965 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004966 }
4967
4968 /* Do the conversion */
Victor Stinner554f3f02010-06-16 23:33:54 +00004969 if (usize > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004970 p = PyUnicode_AS_UNICODE(*v) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00004971 if (0 == MultiByteToWideChar(CP_ACP, flags, s, size, p, usize)) {
4972 goto mbcs_decode_error;
Benjamin Peterson29060642009-01-31 22:14:21 +00004973 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004974 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004975 return size;
Victor Stinner554f3f02010-06-16 23:33:54 +00004976
4977mbcs_decode_error:
4978 /* If the last error was ERROR_NO_UNICODE_TRANSLATION, then
4979 we raise a UnicodeDecodeError - else it is a 'generic'
4980 windows error
4981 */
4982 if (GetLastError()==ERROR_NO_UNICODE_TRANSLATION) {
4983 /* Ideally, we should get reason from FormatMessage - this
4984 is the Windows 2000 English version of the message
4985 */
4986 PyObject *exc = NULL;
4987 const char *reason = "No mapping for the Unicode character exists "
4988 "in the target multi-byte code page.";
4989 make_decode_exception(&exc, "mbcs", s, size, 0, 0, reason);
4990 if (exc != NULL) {
4991 PyCodec_StrictErrors(exc);
4992 Py_DECREF(exc);
4993 }
4994 } else {
4995 PyErr_SetFromWindowsErrWithFilename(0, NULL);
4996 }
4997 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004998}
4999
5000PyObject *PyUnicode_DecodeMBCSStateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005001 Py_ssize_t size,
5002 const char *errors,
5003 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005004{
5005 PyUnicodeObject *v = NULL;
5006 int done;
5007
5008 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005009 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005010
5011#ifdef NEED_RETRY
5012 retry:
5013 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00005014 done = decode_mbcs(&v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005015 else
5016#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00005017 done = decode_mbcs(&v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005018
5019 if (done < 0) {
5020 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00005021 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005022 }
5023
5024 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005025 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005026
5027#ifdef NEED_RETRY
5028 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005029 s += done;
5030 size -= done;
5031 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005032 }
5033#endif
5034
5035 return (PyObject *)v;
5036}
5037
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005038PyObject *PyUnicode_DecodeMBCS(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005039 Py_ssize_t size,
5040 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005041{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005042 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
5043}
5044
5045/*
5046 * Convert unicode into string object (MBCS).
5047 * Returns 0 if succeed, -1 otherwise.
5048 */
5049static int encode_mbcs(PyObject **repr,
Benjamin Peterson29060642009-01-31 22:14:21 +00005050 const Py_UNICODE *p, /* unicode */
Victor Stinner554f3f02010-06-16 23:33:54 +00005051 int size, /* size of unicode */
5052 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005053{
Victor Stinner554f3f02010-06-16 23:33:54 +00005054 BOOL usedDefaultChar = FALSE;
5055 BOOL *pusedDefaultChar;
5056 int mbcssize;
5057 Py_ssize_t n;
5058 PyObject *exc = NULL;
5059 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005060
5061 assert(size >= 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005062
Victor Stinner554f3f02010-06-16 23:33:54 +00005063 /* check and handle 'errors' arg */
5064 if (errors==NULL || strcmp(errors, "strict")==0) {
5065 flags = WC_NO_BEST_FIT_CHARS;
5066 pusedDefaultChar = &usedDefaultChar;
5067 } else if (strcmp(errors, "replace")==0) {
5068 flags = 0;
5069 pusedDefaultChar = NULL;
5070 } else {
5071 PyErr_Format(PyExc_ValueError,
5072 "mbcs encoding does not support errors='%s'",
5073 errors);
5074 return -1;
5075 }
5076
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005077 /* First get the size of the result */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005078 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00005079 mbcssize = WideCharToMultiByte(CP_ACP, flags, p, size, NULL, 0,
5080 NULL, pusedDefaultChar);
Benjamin Peterson29060642009-01-31 22:14:21 +00005081 if (mbcssize == 0) {
5082 PyErr_SetFromWindowsErrWithFilename(0, NULL);
5083 return -1;
5084 }
Victor Stinner554f3f02010-06-16 23:33:54 +00005085 /* If we used a default char, then we failed! */
5086 if (pusedDefaultChar && *pusedDefaultChar)
5087 goto mbcs_encode_error;
5088 } else {
5089 mbcssize = 0;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005090 }
5091
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005092 if (*repr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005093 /* Create string object */
5094 *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
5095 if (*repr == NULL)
5096 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00005097 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005098 }
5099 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005100 /* Extend string object */
5101 n = PyBytes_Size(*repr);
5102 if (_PyBytes_Resize(repr, n + mbcssize) < 0)
5103 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005104 }
5105
5106 /* Do the conversion */
5107 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005108 char *s = PyBytes_AS_STRING(*repr) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00005109 if (0 == WideCharToMultiByte(CP_ACP, flags, p, size, s, mbcssize,
5110 NULL, pusedDefaultChar)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005111 PyErr_SetFromWindowsErrWithFilename(0, NULL);
5112 return -1;
5113 }
Victor Stinner554f3f02010-06-16 23:33:54 +00005114 if (pusedDefaultChar && *pusedDefaultChar)
5115 goto mbcs_encode_error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005116 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005117 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00005118
5119mbcs_encode_error:
5120 raise_encode_exception(&exc, "mbcs", p, size, 0, 0, "invalid character");
5121 Py_XDECREF(exc);
5122 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005123}
5124
5125PyObject *PyUnicode_EncodeMBCS(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00005126 Py_ssize_t size,
5127 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005128{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005129 PyObject *repr = NULL;
5130 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00005131
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005132#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00005133 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005134 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00005135 ret = encode_mbcs(&repr, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005136 else
5137#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00005138 ret = encode_mbcs(&repr, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005139
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005140 if (ret < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005141 Py_XDECREF(repr);
5142 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005143 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005144
5145#ifdef NEED_RETRY
5146 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005147 p += INT_MAX;
5148 size -= INT_MAX;
5149 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005150 }
5151#endif
5152
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005153 return repr;
5154}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00005155
Mark Hammond0ccda1e2003-07-01 00:13:27 +00005156PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
5157{
5158 if (!PyUnicode_Check(unicode)) {
5159 PyErr_BadArgument();
5160 return NULL;
5161 }
5162 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005163 PyUnicode_GET_SIZE(unicode),
5164 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00005165}
5166
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005167#undef NEED_RETRY
5168
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00005169#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005170
Guido van Rossumd57fd912000-03-10 22:53:23 +00005171/* --- Character Mapping Codec -------------------------------------------- */
5172
Guido van Rossumd57fd912000-03-10 22:53:23 +00005173PyObject *PyUnicode_DecodeCharmap(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005174 Py_ssize_t size,
5175 PyObject *mapping,
5176 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005177{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005178 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005179 Py_ssize_t startinpos;
5180 Py_ssize_t endinpos;
5181 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005182 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005183 PyUnicodeObject *v;
5184 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005185 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005186 PyObject *errorHandler = NULL;
5187 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005188 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005189 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00005190
Guido van Rossumd57fd912000-03-10 22:53:23 +00005191 /* Default to Latin-1 */
5192 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005193 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005194
5195 v = _PyUnicode_New(size);
5196 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005197 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005198 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005199 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005200 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005201 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005202 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005203 mapstring = PyUnicode_AS_UNICODE(mapping);
5204 maplen = PyUnicode_GET_SIZE(mapping);
5205 while (s < e) {
5206 unsigned char ch = *s;
5207 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005208
Benjamin Peterson29060642009-01-31 22:14:21 +00005209 if (ch < maplen)
5210 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005211
Benjamin Peterson29060642009-01-31 22:14:21 +00005212 if (x == 0xfffe) {
5213 /* undefined mapping */
5214 outpos = p-PyUnicode_AS_UNICODE(v);
5215 startinpos = s-starts;
5216 endinpos = startinpos+1;
5217 if (unicode_decode_call_errorhandler(
5218 errors, &errorHandler,
5219 "charmap", "character maps to <undefined>",
5220 &starts, &e, &startinpos, &endinpos, &exc, &s,
5221 &v, &outpos, &p)) {
5222 goto onError;
5223 }
5224 continue;
5225 }
5226 *p++ = x;
5227 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005228 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005229 }
5230 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005231 while (s < e) {
5232 unsigned char ch = *s;
5233 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005234
Benjamin Peterson29060642009-01-31 22:14:21 +00005235 /* Get mapping (char ordinal -> integer, Unicode char or None) */
5236 w = PyLong_FromLong((long)ch);
5237 if (w == NULL)
5238 goto onError;
5239 x = PyObject_GetItem(mapping, w);
5240 Py_DECREF(w);
5241 if (x == NULL) {
5242 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5243 /* No mapping found means: mapping is undefined. */
5244 PyErr_Clear();
5245 x = Py_None;
5246 Py_INCREF(x);
5247 } else
5248 goto onError;
5249 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005250
Benjamin Peterson29060642009-01-31 22:14:21 +00005251 /* Apply mapping */
5252 if (PyLong_Check(x)) {
5253 long value = PyLong_AS_LONG(x);
5254 if (value < 0 || value > 65535) {
5255 PyErr_SetString(PyExc_TypeError,
5256 "character mapping must be in range(65536)");
5257 Py_DECREF(x);
5258 goto onError;
5259 }
5260 *p++ = (Py_UNICODE)value;
5261 }
5262 else if (x == Py_None) {
5263 /* undefined mapping */
5264 outpos = p-PyUnicode_AS_UNICODE(v);
5265 startinpos = s-starts;
5266 endinpos = startinpos+1;
5267 if (unicode_decode_call_errorhandler(
5268 errors, &errorHandler,
5269 "charmap", "character maps to <undefined>",
5270 &starts, &e, &startinpos, &endinpos, &exc, &s,
5271 &v, &outpos, &p)) {
5272 Py_DECREF(x);
5273 goto onError;
5274 }
5275 Py_DECREF(x);
5276 continue;
5277 }
5278 else if (PyUnicode_Check(x)) {
5279 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005280
Benjamin Peterson29060642009-01-31 22:14:21 +00005281 if (targetsize == 1)
5282 /* 1-1 mapping */
5283 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005284
Benjamin Peterson29060642009-01-31 22:14:21 +00005285 else if (targetsize > 1) {
5286 /* 1-n mapping */
5287 if (targetsize > extrachars) {
5288 /* resize first */
5289 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
5290 Py_ssize_t needed = (targetsize - extrachars) + \
5291 (targetsize << 2);
5292 extrachars += needed;
5293 /* XXX overflow detection missing */
5294 if (_PyUnicode_Resize(&v,
5295 PyUnicode_GET_SIZE(v) + needed) < 0) {
5296 Py_DECREF(x);
5297 goto onError;
5298 }
5299 p = PyUnicode_AS_UNICODE(v) + oldpos;
5300 }
5301 Py_UNICODE_COPY(p,
5302 PyUnicode_AS_UNICODE(x),
5303 targetsize);
5304 p += targetsize;
5305 extrachars -= targetsize;
5306 }
5307 /* 1-0 mapping: skip the character */
5308 }
5309 else {
5310 /* wrong return value */
5311 PyErr_SetString(PyExc_TypeError,
5312 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00005313 Py_DECREF(x);
5314 goto onError;
5315 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005316 Py_DECREF(x);
5317 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005318 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005319 }
5320 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00005321 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
5322 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005323 Py_XDECREF(errorHandler);
5324 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005325 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00005326
Benjamin Peterson29060642009-01-31 22:14:21 +00005327 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005328 Py_XDECREF(errorHandler);
5329 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005330 Py_XDECREF(v);
5331 return NULL;
5332}
5333
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005334/* Charmap encoding: the lookup table */
5335
5336struct encoding_map{
Benjamin Peterson29060642009-01-31 22:14:21 +00005337 PyObject_HEAD
5338 unsigned char level1[32];
5339 int count2, count3;
5340 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005341};
5342
5343static PyObject*
5344encoding_map_size(PyObject *obj, PyObject* args)
5345{
5346 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005347 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00005348 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005349}
5350
5351static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005352 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00005353 PyDoc_STR("Return the size (in bytes) of this object") },
5354 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005355};
5356
5357static void
5358encoding_map_dealloc(PyObject* o)
5359{
Benjamin Peterson14339b62009-01-31 16:36:08 +00005360 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005361}
5362
5363static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005364 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005365 "EncodingMap", /*tp_name*/
5366 sizeof(struct encoding_map), /*tp_basicsize*/
5367 0, /*tp_itemsize*/
5368 /* methods */
5369 encoding_map_dealloc, /*tp_dealloc*/
5370 0, /*tp_print*/
5371 0, /*tp_getattr*/
5372 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00005373 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00005374 0, /*tp_repr*/
5375 0, /*tp_as_number*/
5376 0, /*tp_as_sequence*/
5377 0, /*tp_as_mapping*/
5378 0, /*tp_hash*/
5379 0, /*tp_call*/
5380 0, /*tp_str*/
5381 0, /*tp_getattro*/
5382 0, /*tp_setattro*/
5383 0, /*tp_as_buffer*/
5384 Py_TPFLAGS_DEFAULT, /*tp_flags*/
5385 0, /*tp_doc*/
5386 0, /*tp_traverse*/
5387 0, /*tp_clear*/
5388 0, /*tp_richcompare*/
5389 0, /*tp_weaklistoffset*/
5390 0, /*tp_iter*/
5391 0, /*tp_iternext*/
5392 encoding_map_methods, /*tp_methods*/
5393 0, /*tp_members*/
5394 0, /*tp_getset*/
5395 0, /*tp_base*/
5396 0, /*tp_dict*/
5397 0, /*tp_descr_get*/
5398 0, /*tp_descr_set*/
5399 0, /*tp_dictoffset*/
5400 0, /*tp_init*/
5401 0, /*tp_alloc*/
5402 0, /*tp_new*/
5403 0, /*tp_free*/
5404 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005405};
5406
5407PyObject*
5408PyUnicode_BuildEncodingMap(PyObject* string)
5409{
5410 Py_UNICODE *decode;
5411 PyObject *result;
5412 struct encoding_map *mresult;
5413 int i;
5414 int need_dict = 0;
5415 unsigned char level1[32];
5416 unsigned char level2[512];
5417 unsigned char *mlevel1, *mlevel2, *mlevel3;
5418 int count2 = 0, count3 = 0;
5419
5420 if (!PyUnicode_Check(string) || PyUnicode_GetSize(string) != 256) {
5421 PyErr_BadArgument();
5422 return NULL;
5423 }
5424 decode = PyUnicode_AS_UNICODE(string);
5425 memset(level1, 0xFF, sizeof level1);
5426 memset(level2, 0xFF, sizeof level2);
5427
5428 /* If there isn't a one-to-one mapping of NULL to \0,
5429 or if there are non-BMP characters, we need to use
5430 a mapping dictionary. */
5431 if (decode[0] != 0)
5432 need_dict = 1;
5433 for (i = 1; i < 256; i++) {
5434 int l1, l2;
5435 if (decode[i] == 0
Benjamin Peterson29060642009-01-31 22:14:21 +00005436#ifdef Py_UNICODE_WIDE
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005437 || decode[i] > 0xFFFF
Benjamin Peterson29060642009-01-31 22:14:21 +00005438#endif
5439 ) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005440 need_dict = 1;
5441 break;
5442 }
5443 if (decode[i] == 0xFFFE)
5444 /* unmapped character */
5445 continue;
5446 l1 = decode[i] >> 11;
5447 l2 = decode[i] >> 7;
5448 if (level1[l1] == 0xFF)
5449 level1[l1] = count2++;
5450 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00005451 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005452 }
5453
5454 if (count2 >= 0xFF || count3 >= 0xFF)
5455 need_dict = 1;
5456
5457 if (need_dict) {
5458 PyObject *result = PyDict_New();
5459 PyObject *key, *value;
5460 if (!result)
5461 return NULL;
5462 for (i = 0; i < 256; i++) {
5463 key = value = NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00005464 key = PyLong_FromLong(decode[i]);
5465 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005466 if (!key || !value)
5467 goto failed1;
5468 if (PyDict_SetItem(result, key, value) == -1)
5469 goto failed1;
5470 Py_DECREF(key);
5471 Py_DECREF(value);
5472 }
5473 return result;
5474 failed1:
5475 Py_XDECREF(key);
5476 Py_XDECREF(value);
5477 Py_DECREF(result);
5478 return NULL;
5479 }
5480
5481 /* Create a three-level trie */
5482 result = PyObject_MALLOC(sizeof(struct encoding_map) +
5483 16*count2 + 128*count3 - 1);
5484 if (!result)
5485 return PyErr_NoMemory();
5486 PyObject_Init(result, &EncodingMapType);
5487 mresult = (struct encoding_map*)result;
5488 mresult->count2 = count2;
5489 mresult->count3 = count3;
5490 mlevel1 = mresult->level1;
5491 mlevel2 = mresult->level23;
5492 mlevel3 = mresult->level23 + 16*count2;
5493 memcpy(mlevel1, level1, 32);
5494 memset(mlevel2, 0xFF, 16*count2);
5495 memset(mlevel3, 0, 128*count3);
5496 count3 = 0;
5497 for (i = 1; i < 256; i++) {
5498 int o1, o2, o3, i2, i3;
5499 if (decode[i] == 0xFFFE)
5500 /* unmapped character */
5501 continue;
5502 o1 = decode[i]>>11;
5503 o2 = (decode[i]>>7) & 0xF;
5504 i2 = 16*mlevel1[o1] + o2;
5505 if (mlevel2[i2] == 0xFF)
5506 mlevel2[i2] = count3++;
5507 o3 = decode[i] & 0x7F;
5508 i3 = 128*mlevel2[i2] + o3;
5509 mlevel3[i3] = i;
5510 }
5511 return result;
5512}
5513
5514static int
5515encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
5516{
5517 struct encoding_map *map = (struct encoding_map*)mapping;
5518 int l1 = c>>11;
5519 int l2 = (c>>7) & 0xF;
5520 int l3 = c & 0x7F;
5521 int i;
5522
5523#ifdef Py_UNICODE_WIDE
5524 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005525 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005526 }
5527#endif
5528 if (c == 0)
5529 return 0;
5530 /* level 1*/
5531 i = map->level1[l1];
5532 if (i == 0xFF) {
5533 return -1;
5534 }
5535 /* level 2*/
5536 i = map->level23[16*i+l2];
5537 if (i == 0xFF) {
5538 return -1;
5539 }
5540 /* level 3 */
5541 i = map->level23[16*map->count2 + 128*i + l3];
5542 if (i == 0) {
5543 return -1;
5544 }
5545 return i;
5546}
5547
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005548/* Lookup the character ch in the mapping. If the character
5549 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00005550 error occurred). */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005551static PyObject *charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005552{
Christian Heimes217cfd12007-12-02 14:31:20 +00005553 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005554 PyObject *x;
5555
5556 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005557 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005558 x = PyObject_GetItem(mapping, w);
5559 Py_DECREF(w);
5560 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005561 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5562 /* No mapping found means: mapping is undefined. */
5563 PyErr_Clear();
5564 x = Py_None;
5565 Py_INCREF(x);
5566 return x;
5567 } else
5568 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005569 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00005570 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00005571 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00005572 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005573 long value = PyLong_AS_LONG(x);
5574 if (value < 0 || value > 255) {
5575 PyErr_SetString(PyExc_TypeError,
5576 "character mapping must be in range(256)");
5577 Py_DECREF(x);
5578 return NULL;
5579 }
5580 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005581 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005582 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00005583 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005584 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005585 /* wrong return value */
5586 PyErr_Format(PyExc_TypeError,
5587 "character mapping must return integer, bytes or None, not %.400s",
5588 x->ob_type->tp_name);
5589 Py_DECREF(x);
5590 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005591 }
5592}
5593
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005594static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00005595charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005596{
Benjamin Peterson14339b62009-01-31 16:36:08 +00005597 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
5598 /* exponentially overallocate to minimize reallocations */
5599 if (requiredsize < 2*outsize)
5600 requiredsize = 2*outsize;
5601 if (_PyBytes_Resize(outobj, requiredsize))
5602 return -1;
5603 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005604}
5605
Benjamin Peterson14339b62009-01-31 16:36:08 +00005606typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00005607 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005608}charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005609/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00005610 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005611 space is available. Return a new reference to the object that
5612 was put in the output buffer, or Py_None, if the mapping was undefined
5613 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00005614 reallocation error occurred. The caller must decref the result */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005615static
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005616charmapencode_result charmapencode_output(Py_UNICODE c, PyObject *mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00005617 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005618{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005619 PyObject *rep;
5620 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00005621 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005622
Christian Heimes90aa7642007-12-19 02:45:37 +00005623 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005624 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00005625 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005626 if (res == -1)
5627 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00005628 if (outsize<requiredsize)
5629 if (charmapencode_resize(outobj, outpos, requiredsize))
5630 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00005631 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005632 outstart[(*outpos)++] = (char)res;
5633 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005634 }
5635
5636 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005637 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005638 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005639 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005640 Py_DECREF(rep);
5641 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005642 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005643 if (PyLong_Check(rep)) {
5644 Py_ssize_t requiredsize = *outpos+1;
5645 if (outsize<requiredsize)
5646 if (charmapencode_resize(outobj, outpos, requiredsize)) {
5647 Py_DECREF(rep);
5648 return enc_EXCEPTION;
5649 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005650 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005651 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005652 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005653 else {
5654 const char *repchars = PyBytes_AS_STRING(rep);
5655 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
5656 Py_ssize_t requiredsize = *outpos+repsize;
5657 if (outsize<requiredsize)
5658 if (charmapencode_resize(outobj, outpos, requiredsize)) {
5659 Py_DECREF(rep);
5660 return enc_EXCEPTION;
5661 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005662 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005663 memcpy(outstart + *outpos, repchars, repsize);
5664 *outpos += repsize;
5665 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005666 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005667 Py_DECREF(rep);
5668 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005669}
5670
5671/* handle an error in PyUnicode_EncodeCharmap
5672 Return 0 on success, -1 on error */
5673static
5674int charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00005675 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005676 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00005677 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00005678 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005679{
5680 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005681 Py_ssize_t repsize;
5682 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005683 Py_UNICODE *uni2;
5684 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005685 Py_ssize_t collstartpos = *inpos;
5686 Py_ssize_t collendpos = *inpos+1;
5687 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005688 char *encoding = "charmap";
5689 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005690 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005691
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005692 /* find all unencodable characters */
5693 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005694 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00005695 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005696 int res = encoding_map_lookup(p[collendpos], mapping);
5697 if (res != -1)
5698 break;
5699 ++collendpos;
5700 continue;
5701 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005702
Benjamin Peterson29060642009-01-31 22:14:21 +00005703 rep = charmapencode_lookup(p[collendpos], mapping);
5704 if (rep==NULL)
5705 return -1;
5706 else if (rep!=Py_None) {
5707 Py_DECREF(rep);
5708 break;
5709 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005710 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00005711 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005712 }
5713 /* cache callback name lookup
5714 * (if not done yet, i.e. it's the first error) */
5715 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005716 if ((errors==NULL) || (!strcmp(errors, "strict")))
5717 *known_errorHandler = 1;
5718 else if (!strcmp(errors, "replace"))
5719 *known_errorHandler = 2;
5720 else if (!strcmp(errors, "ignore"))
5721 *known_errorHandler = 3;
5722 else if (!strcmp(errors, "xmlcharrefreplace"))
5723 *known_errorHandler = 4;
5724 else
5725 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005726 }
5727 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005728 case 1: /* strict */
5729 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5730 return -1;
5731 case 2: /* replace */
5732 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005733 x = charmapencode_output('?', mapping, res, respos);
5734 if (x==enc_EXCEPTION) {
5735 return -1;
5736 }
5737 else if (x==enc_FAILED) {
5738 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5739 return -1;
5740 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005741 }
5742 /* fall through */
5743 case 3: /* ignore */
5744 *inpos = collendpos;
5745 break;
5746 case 4: /* xmlcharrefreplace */
5747 /* generate replacement (temporarily (mis)uses p) */
5748 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005749 char buffer[2+29+1+1];
5750 char *cp;
5751 sprintf(buffer, "&#%d;", (int)p[collpos]);
5752 for (cp = buffer; *cp; ++cp) {
5753 x = charmapencode_output(*cp, mapping, res, respos);
5754 if (x==enc_EXCEPTION)
5755 return -1;
5756 else if (x==enc_FAILED) {
5757 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5758 return -1;
5759 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005760 }
5761 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005762 *inpos = collendpos;
5763 break;
5764 default:
5765 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00005766 encoding, reason, p, size, exceptionObject,
5767 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005768 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005769 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005770 if (PyBytes_Check(repunicode)) {
5771 /* Directly copy bytes result to output. */
5772 Py_ssize_t outsize = PyBytes_Size(*res);
5773 Py_ssize_t requiredsize;
5774 repsize = PyBytes_Size(repunicode);
5775 requiredsize = *respos + repsize;
5776 if (requiredsize > outsize)
5777 /* Make room for all additional bytes. */
5778 if (charmapencode_resize(res, respos, requiredsize)) {
5779 Py_DECREF(repunicode);
5780 return -1;
5781 }
5782 memcpy(PyBytes_AsString(*res) + *respos,
5783 PyBytes_AsString(repunicode), repsize);
5784 *respos += repsize;
5785 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005786 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00005787 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005788 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005789 /* generate replacement */
5790 repsize = PyUnicode_GET_SIZE(repunicode);
5791 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005792 x = charmapencode_output(*uni2, mapping, res, respos);
5793 if (x==enc_EXCEPTION) {
5794 return -1;
5795 }
5796 else if (x==enc_FAILED) {
5797 Py_DECREF(repunicode);
5798 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5799 return -1;
5800 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005801 }
5802 *inpos = newpos;
5803 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005804 }
5805 return 0;
5806}
5807
Guido van Rossumd57fd912000-03-10 22:53:23 +00005808PyObject *PyUnicode_EncodeCharmap(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00005809 Py_ssize_t size,
5810 PyObject *mapping,
5811 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005812{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005813 /* output object */
5814 PyObject *res = NULL;
5815 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005816 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005817 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005818 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005819 PyObject *errorHandler = NULL;
5820 PyObject *exc = NULL;
5821 /* the following variable is used for caching string comparisons
5822 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
5823 * 3=ignore, 4=xmlcharrefreplace */
5824 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005825
5826 /* Default to Latin-1 */
5827 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005828 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005829
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005830 /* allocate enough for a simple encoding without
5831 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00005832 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005833 if (res == NULL)
5834 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00005835 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005836 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005837
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005838 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005839 /* try to encode it */
5840 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
5841 if (x==enc_EXCEPTION) /* error */
5842 goto onError;
5843 if (x==enc_FAILED) { /* unencodable character */
5844 if (charmap_encoding_error(p, size, &inpos, mapping,
5845 &exc,
5846 &known_errorHandler, &errorHandler, errors,
5847 &res, &respos)) {
5848 goto onError;
5849 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005850 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005851 else
5852 /* done with this character => adjust input position */
5853 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005854 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005855
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005856 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00005857 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005858 if (_PyBytes_Resize(&res, respos) < 0)
5859 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005860
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005861 Py_XDECREF(exc);
5862 Py_XDECREF(errorHandler);
5863 return res;
5864
Benjamin Peterson29060642009-01-31 22:14:21 +00005865 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005866 Py_XDECREF(res);
5867 Py_XDECREF(exc);
5868 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005869 return NULL;
5870}
5871
5872PyObject *PyUnicode_AsCharmapString(PyObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00005873 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005874{
5875 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005876 PyErr_BadArgument();
5877 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005878 }
5879 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005880 PyUnicode_GET_SIZE(unicode),
5881 mapping,
5882 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005883}
5884
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005885/* create or adjust a UnicodeTranslateError */
5886static void make_translate_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005887 const Py_UNICODE *unicode, Py_ssize_t size,
5888 Py_ssize_t startpos, Py_ssize_t endpos,
5889 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005890{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005891 if (*exceptionObject == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005892 *exceptionObject = PyUnicodeTranslateError_Create(
Benjamin Peterson29060642009-01-31 22:14:21 +00005893 unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005894 }
5895 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005896 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
5897 goto onError;
5898 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
5899 goto onError;
5900 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
5901 goto onError;
5902 return;
5903 onError:
5904 Py_DECREF(*exceptionObject);
5905 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005906 }
5907}
5908
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005909/* raises a UnicodeTranslateError */
5910static void raise_translate_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005911 const Py_UNICODE *unicode, Py_ssize_t size,
5912 Py_ssize_t startpos, Py_ssize_t endpos,
5913 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005914{
5915 make_translate_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005916 unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005917 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005918 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005919}
5920
5921/* error handling callback helper:
5922 build arguments, call the callback and check the arguments,
5923 put the result into newpos and return the replacement string, which
5924 has to be freed by the caller */
5925static PyObject *unicode_translate_call_errorhandler(const char *errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00005926 PyObject **errorHandler,
5927 const char *reason,
5928 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
5929 Py_ssize_t startpos, Py_ssize_t endpos,
5930 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005931{
Benjamin Peterson142957c2008-07-04 19:55:29 +00005932 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005933
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005934 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005935 PyObject *restuple;
5936 PyObject *resunicode;
5937
5938 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005939 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005940 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005941 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005942 }
5943
5944 make_translate_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005945 unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005946 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005947 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005948
5949 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00005950 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005951 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005952 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005953 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00005954 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00005955 Py_DECREF(restuple);
5956 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005957 }
5958 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00005959 &resunicode, &i_newpos)) {
5960 Py_DECREF(restuple);
5961 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005962 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00005963 if (i_newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005964 *newpos = size+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005965 else
5966 *newpos = i_newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005967 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005968 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
5969 Py_DECREF(restuple);
5970 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005971 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005972 Py_INCREF(resunicode);
5973 Py_DECREF(restuple);
5974 return resunicode;
5975}
5976
5977/* Lookup the character ch in the mapping and put the result in result,
5978 which must be decrefed by the caller.
5979 Return 0 on success, -1 on error */
5980static
5981int charmaptranslate_lookup(Py_UNICODE c, PyObject *mapping, PyObject **result)
5982{
Christian Heimes217cfd12007-12-02 14:31:20 +00005983 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005984 PyObject *x;
5985
5986 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005987 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005988 x = PyObject_GetItem(mapping, w);
5989 Py_DECREF(w);
5990 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005991 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5992 /* No mapping found means: use 1:1 mapping. */
5993 PyErr_Clear();
5994 *result = NULL;
5995 return 0;
5996 } else
5997 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005998 }
5999 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006000 *result = x;
6001 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006002 }
Christian Heimes217cfd12007-12-02 14:31:20 +00006003 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006004 long value = PyLong_AS_LONG(x);
6005 long max = PyUnicode_GetMax();
6006 if (value < 0 || value > max) {
6007 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00006008 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00006009 Py_DECREF(x);
6010 return -1;
6011 }
6012 *result = x;
6013 return 0;
6014 }
6015 else if (PyUnicode_Check(x)) {
6016 *result = x;
6017 return 0;
6018 }
6019 else {
6020 /* wrong return value */
6021 PyErr_SetString(PyExc_TypeError,
6022 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00006023 Py_DECREF(x);
6024 return -1;
6025 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006026}
6027/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00006028 if not reallocate and adjust various state variables.
6029 Return 0 on success, -1 on error */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006030static
Walter Dörwald4894c302003-10-24 14:25:28 +00006031int charmaptranslate_makespace(PyObject **outobj, Py_UNICODE **outp,
Benjamin Peterson29060642009-01-31 22:14:21 +00006032 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006033{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006034 Py_ssize_t oldsize = PyUnicode_GET_SIZE(*outobj);
Walter Dörwald4894c302003-10-24 14:25:28 +00006035 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006036 /* remember old output position */
6037 Py_ssize_t outpos = *outp-PyUnicode_AS_UNICODE(*outobj);
6038 /* exponentially overallocate to minimize reallocations */
6039 if (requiredsize < 2 * oldsize)
6040 requiredsize = 2 * oldsize;
6041 if (PyUnicode_Resize(outobj, requiredsize) < 0)
6042 return -1;
6043 *outp = PyUnicode_AS_UNICODE(*outobj) + outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006044 }
6045 return 0;
6046}
6047/* lookup the character, put the result in the output string and adjust
6048 various state variables. Return a new reference to the object that
6049 was put in the output buffer in *result, or Py_None, if the mapping was
6050 undefined (in which case no character was written).
6051 The called must decref result.
6052 Return 0 on success, -1 on error. */
6053static
Walter Dörwald4894c302003-10-24 14:25:28 +00006054int charmaptranslate_output(const Py_UNICODE *startinp, const Py_UNICODE *curinp,
Benjamin Peterson29060642009-01-31 22:14:21 +00006055 Py_ssize_t insize, PyObject *mapping, PyObject **outobj, Py_UNICODE **outp,
6056 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006057{
Walter Dörwald4894c302003-10-24 14:25:28 +00006058 if (charmaptranslate_lookup(*curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00006059 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006060 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006061 /* not found => default to 1:1 mapping */
6062 *(*outp)++ = *curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006063 }
6064 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00006065 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00006066 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006067 /* no overflow check, because we know that the space is enough */
6068 *(*outp)++ = (Py_UNICODE)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006069 }
6070 else if (PyUnicode_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006071 Py_ssize_t repsize = PyUnicode_GET_SIZE(*res);
6072 if (repsize==1) {
6073 /* no overflow check, because we know that the space is enough */
6074 *(*outp)++ = *PyUnicode_AS_UNICODE(*res);
6075 }
6076 else if (repsize!=0) {
6077 /* more than one character */
6078 Py_ssize_t requiredsize = (*outp-PyUnicode_AS_UNICODE(*outobj)) +
6079 (insize - (curinp-startinp)) +
6080 repsize - 1;
6081 if (charmaptranslate_makespace(outobj, outp, requiredsize))
6082 return -1;
6083 memcpy(*outp, PyUnicode_AS_UNICODE(*res), sizeof(Py_UNICODE)*repsize);
6084 *outp += repsize;
6085 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006086 }
6087 else
Benjamin Peterson29060642009-01-31 22:14:21 +00006088 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006089 return 0;
6090}
6091
6092PyObject *PyUnicode_TranslateCharmap(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00006093 Py_ssize_t size,
6094 PyObject *mapping,
6095 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006096{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006097 /* output object */
6098 PyObject *res = NULL;
6099 /* pointers to the beginning and end+1 of input */
6100 const Py_UNICODE *startp = p;
6101 const Py_UNICODE *endp = p + size;
6102 /* pointer into the output */
6103 Py_UNICODE *str;
6104 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006105 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006106 char *reason = "character maps to <undefined>";
6107 PyObject *errorHandler = NULL;
6108 PyObject *exc = NULL;
6109 /* the following variable is used for caching string comparisons
6110 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
6111 * 3=ignore, 4=xmlcharrefreplace */
6112 int known_errorHandler = -1;
6113
Guido van Rossumd57fd912000-03-10 22:53:23 +00006114 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006115 PyErr_BadArgument();
6116 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006117 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006118
6119 /* allocate enough for a simple 1:1 translation without
6120 replacements, if we need more, we'll resize */
6121 res = PyUnicode_FromUnicode(NULL, size);
6122 if (res == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006123 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006124 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006125 return res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006126 str = PyUnicode_AS_UNICODE(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006127
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006128 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006129 /* try to encode it */
6130 PyObject *x = NULL;
6131 if (charmaptranslate_output(startp, p, size, mapping, &res, &str, &x)) {
6132 Py_XDECREF(x);
6133 goto onError;
6134 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006135 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00006136 if (x!=Py_None) /* it worked => adjust input pointer */
6137 ++p;
6138 else { /* untranslatable character */
6139 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
6140 Py_ssize_t repsize;
6141 Py_ssize_t newpos;
6142 Py_UNICODE *uni2;
6143 /* startpos for collecting untranslatable chars */
6144 const Py_UNICODE *collstart = p;
6145 const Py_UNICODE *collend = p+1;
6146 const Py_UNICODE *coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006147
Benjamin Peterson29060642009-01-31 22:14:21 +00006148 /* find all untranslatable characters */
6149 while (collend < endp) {
6150 if (charmaptranslate_lookup(*collend, mapping, &x))
6151 goto onError;
6152 Py_XDECREF(x);
6153 if (x!=Py_None)
6154 break;
6155 ++collend;
6156 }
6157 /* cache callback name lookup
6158 * (if not done yet, i.e. it's the first error) */
6159 if (known_errorHandler==-1) {
6160 if ((errors==NULL) || (!strcmp(errors, "strict")))
6161 known_errorHandler = 1;
6162 else if (!strcmp(errors, "replace"))
6163 known_errorHandler = 2;
6164 else if (!strcmp(errors, "ignore"))
6165 known_errorHandler = 3;
6166 else if (!strcmp(errors, "xmlcharrefreplace"))
6167 known_errorHandler = 4;
6168 else
6169 known_errorHandler = 0;
6170 }
6171 switch (known_errorHandler) {
6172 case 1: /* strict */
6173 raise_translate_exception(&exc, startp, size, collstart-startp, collend-startp, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006174 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006175 case 2: /* replace */
6176 /* No need to check for space, this is a 1:1 replacement */
6177 for (coll = collstart; coll<collend; ++coll)
6178 *str++ = '?';
6179 /* fall through */
6180 case 3: /* ignore */
6181 p = collend;
6182 break;
6183 case 4: /* xmlcharrefreplace */
6184 /* generate replacement (temporarily (mis)uses p) */
6185 for (p = collstart; p < collend; ++p) {
6186 char buffer[2+29+1+1];
6187 char *cp;
6188 sprintf(buffer, "&#%d;", (int)*p);
6189 if (charmaptranslate_makespace(&res, &str,
6190 (str-PyUnicode_AS_UNICODE(res))+strlen(buffer)+(endp-collend)))
6191 goto onError;
6192 for (cp = buffer; *cp; ++cp)
6193 *str++ = *cp;
6194 }
6195 p = collend;
6196 break;
6197 default:
6198 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
6199 reason, startp, size, &exc,
6200 collstart-startp, collend-startp, &newpos);
6201 if (repunicode == NULL)
6202 goto onError;
6203 /* generate replacement */
6204 repsize = PyUnicode_GET_SIZE(repunicode);
6205 if (charmaptranslate_makespace(&res, &str,
6206 (str-PyUnicode_AS_UNICODE(res))+repsize+(endp-collend))) {
6207 Py_DECREF(repunicode);
6208 goto onError;
6209 }
6210 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2)
6211 *str++ = *uni2;
6212 p = startp + newpos;
6213 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006214 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006215 }
6216 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006217 /* Resize if we allocated to much */
6218 respos = str-PyUnicode_AS_UNICODE(res);
Walter Dörwald4894c302003-10-24 14:25:28 +00006219 if (respos<PyUnicode_GET_SIZE(res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006220 if (PyUnicode_Resize(&res, respos) < 0)
6221 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006222 }
6223 Py_XDECREF(exc);
6224 Py_XDECREF(errorHandler);
6225 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006226
Benjamin Peterson29060642009-01-31 22:14:21 +00006227 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006228 Py_XDECREF(res);
6229 Py_XDECREF(exc);
6230 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006231 return NULL;
6232}
6233
6234PyObject *PyUnicode_Translate(PyObject *str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006235 PyObject *mapping,
6236 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006237{
6238 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00006239
Guido van Rossumd57fd912000-03-10 22:53:23 +00006240 str = PyUnicode_FromObject(str);
6241 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006242 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006243 result = PyUnicode_TranslateCharmap(PyUnicode_AS_UNICODE(str),
Benjamin Peterson29060642009-01-31 22:14:21 +00006244 PyUnicode_GET_SIZE(str),
6245 mapping,
6246 errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006247 Py_DECREF(str);
6248 return result;
Tim Petersced69f82003-09-16 20:30:58 +00006249
Benjamin Peterson29060642009-01-31 22:14:21 +00006250 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006251 Py_XDECREF(str);
6252 return NULL;
6253}
Tim Petersced69f82003-09-16 20:30:58 +00006254
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00006255PyObject *
6256PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
6257 Py_ssize_t length)
6258{
6259 PyObject *result;
6260 Py_UNICODE *p; /* write pointer into result */
6261 Py_ssize_t i;
6262 /* Copy to a new string */
6263 result = (PyObject *)_PyUnicode_New(length);
6264 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
6265 if (result == NULL)
6266 return result;
6267 p = PyUnicode_AS_UNICODE(result);
6268 /* Iterate over code points */
6269 for (i = 0; i < length; i++) {
6270 Py_UNICODE ch =s[i];
6271 if (ch > 127) {
6272 int decimal = Py_UNICODE_TODECIMAL(ch);
6273 if (decimal >= 0)
6274 p[i] = '0' + decimal;
6275 }
6276 }
6277 return result;
6278}
Guido van Rossum9e896b32000-04-05 20:11:21 +00006279/* --- Decimal Encoder ---------------------------------------------------- */
6280
6281int PyUnicode_EncodeDecimal(Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00006282 Py_ssize_t length,
6283 char *output,
6284 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00006285{
6286 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006287 PyObject *errorHandler = NULL;
6288 PyObject *exc = NULL;
6289 const char *encoding = "decimal";
6290 const char *reason = "invalid decimal Unicode string";
6291 /* the following variable is used for caching string comparisons
6292 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6293 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00006294
6295 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006296 PyErr_BadArgument();
6297 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00006298 }
6299
6300 p = s;
6301 end = s + length;
6302 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006303 register Py_UNICODE ch = *p;
6304 int decimal;
6305 PyObject *repunicode;
6306 Py_ssize_t repsize;
6307 Py_ssize_t newpos;
6308 Py_UNICODE *uni2;
6309 Py_UNICODE *collstart;
6310 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00006311
Benjamin Peterson29060642009-01-31 22:14:21 +00006312 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006313 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00006314 ++p;
6315 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006316 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006317 decimal = Py_UNICODE_TODECIMAL(ch);
6318 if (decimal >= 0) {
6319 *output++ = '0' + decimal;
6320 ++p;
6321 continue;
6322 }
6323 if (0 < ch && ch < 256) {
6324 *output++ = (char)ch;
6325 ++p;
6326 continue;
6327 }
6328 /* All other characters are considered unencodable */
6329 collstart = p;
6330 collend = p+1;
6331 while (collend < end) {
6332 if ((0 < *collend && *collend < 256) ||
6333 !Py_UNICODE_ISSPACE(*collend) ||
6334 Py_UNICODE_TODECIMAL(*collend))
6335 break;
6336 }
6337 /* cache callback name lookup
6338 * (if not done yet, i.e. it's the first error) */
6339 if (known_errorHandler==-1) {
6340 if ((errors==NULL) || (!strcmp(errors, "strict")))
6341 known_errorHandler = 1;
6342 else if (!strcmp(errors, "replace"))
6343 known_errorHandler = 2;
6344 else if (!strcmp(errors, "ignore"))
6345 known_errorHandler = 3;
6346 else if (!strcmp(errors, "xmlcharrefreplace"))
6347 known_errorHandler = 4;
6348 else
6349 known_errorHandler = 0;
6350 }
6351 switch (known_errorHandler) {
6352 case 1: /* strict */
6353 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
6354 goto onError;
6355 case 2: /* replace */
6356 for (p = collstart; p < collend; ++p)
6357 *output++ = '?';
6358 /* fall through */
6359 case 3: /* ignore */
6360 p = collend;
6361 break;
6362 case 4: /* xmlcharrefreplace */
6363 /* generate replacement (temporarily (mis)uses p) */
6364 for (p = collstart; p < collend; ++p)
6365 output += sprintf(output, "&#%d;", (int)*p);
6366 p = collend;
6367 break;
6368 default:
6369 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
6370 encoding, reason, s, length, &exc,
6371 collstart-s, collend-s, &newpos);
6372 if (repunicode == NULL)
6373 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006374 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006375 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006376 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
6377 Py_DECREF(repunicode);
6378 goto onError;
6379 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006380 /* generate replacement */
6381 repsize = PyUnicode_GET_SIZE(repunicode);
6382 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
6383 Py_UNICODE ch = *uni2;
6384 if (Py_UNICODE_ISSPACE(ch))
6385 *output++ = ' ';
6386 else {
6387 decimal = Py_UNICODE_TODECIMAL(ch);
6388 if (decimal >= 0)
6389 *output++ = '0' + decimal;
6390 else if (0 < ch && ch < 256)
6391 *output++ = (char)ch;
6392 else {
6393 Py_DECREF(repunicode);
6394 raise_encode_exception(&exc, encoding,
6395 s, length, collstart-s, collend-s, reason);
6396 goto onError;
6397 }
6398 }
6399 }
6400 p = s + newpos;
6401 Py_DECREF(repunicode);
6402 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00006403 }
6404 /* 0-terminate the output string */
6405 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006406 Py_XDECREF(exc);
6407 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00006408 return 0;
6409
Benjamin Peterson29060642009-01-31 22:14:21 +00006410 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006411 Py_XDECREF(exc);
6412 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00006413 return -1;
6414}
6415
Guido van Rossumd57fd912000-03-10 22:53:23 +00006416/* --- Helpers ------------------------------------------------------------ */
6417
Eric Smith8c663262007-08-25 02:26:07 +00006418#include "stringlib/unicodedefs.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00006419#include "stringlib/fastsearch.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006420
Thomas Wouters477c8d52006-05-27 19:21:47 +00006421#include "stringlib/count.h"
6422#include "stringlib/find.h"
6423#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006424#include "stringlib/split.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00006425
Eric Smith5807c412008-05-11 21:00:57 +00006426#define _Py_InsertThousandsGrouping _PyUnicode_InsertThousandsGrouping
Eric Smitha3b1ac82009-04-03 14:45:06 +00006427#define _Py_InsertThousandsGroupingLocale _PyUnicode_InsertThousandsGroupingLocale
Eric Smith5807c412008-05-11 21:00:57 +00006428#include "stringlib/localeutil.h"
6429
Thomas Wouters477c8d52006-05-27 19:21:47 +00006430/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006431#define ADJUST_INDICES(start, end, len) \
6432 if (end > len) \
6433 end = len; \
6434 else if (end < 0) { \
6435 end += len; \
6436 if (end < 0) \
6437 end = 0; \
6438 } \
6439 if (start < 0) { \
6440 start += len; \
6441 if (start < 0) \
6442 start = 0; \
6443 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00006444
Martin v. Löwis18e16552006-02-15 17:27:45 +00006445Py_ssize_t PyUnicode_Count(PyObject *str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00006446 PyObject *substr,
6447 Py_ssize_t start,
6448 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006449{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006450 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006451 PyUnicodeObject* str_obj;
6452 PyUnicodeObject* sub_obj;
Tim Petersced69f82003-09-16 20:30:58 +00006453
Thomas Wouters477c8d52006-05-27 19:21:47 +00006454 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
6455 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00006456 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006457 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
6458 if (!sub_obj) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006459 Py_DECREF(str_obj);
6460 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006461 }
Tim Petersced69f82003-09-16 20:30:58 +00006462
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006463 ADJUST_INDICES(start, end, str_obj->length);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006464 result = stringlib_count(
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006465 str_obj->str + start, end - start, sub_obj->str, sub_obj->length,
6466 PY_SSIZE_T_MAX
Thomas Wouters477c8d52006-05-27 19:21:47 +00006467 );
6468
6469 Py_DECREF(sub_obj);
6470 Py_DECREF(str_obj);
6471
Guido van Rossumd57fd912000-03-10 22:53:23 +00006472 return result;
6473}
6474
Martin v. Löwis18e16552006-02-15 17:27:45 +00006475Py_ssize_t PyUnicode_Find(PyObject *str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00006476 PyObject *sub,
6477 Py_ssize_t start,
6478 Py_ssize_t end,
6479 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006480{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006481 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00006482
Guido van Rossumd57fd912000-03-10 22:53:23 +00006483 str = PyUnicode_FromObject(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006484 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00006485 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006486 sub = PyUnicode_FromObject(sub);
6487 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006488 Py_DECREF(str);
6489 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006490 }
Tim Petersced69f82003-09-16 20:30:58 +00006491
Thomas Wouters477c8d52006-05-27 19:21:47 +00006492 if (direction > 0)
6493 result = stringlib_find_slice(
6494 PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
6495 PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
6496 start, end
6497 );
6498 else
6499 result = stringlib_rfind_slice(
6500 PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
6501 PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
6502 start, end
6503 );
6504
Guido van Rossumd57fd912000-03-10 22:53:23 +00006505 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006506 Py_DECREF(sub);
6507
Guido van Rossumd57fd912000-03-10 22:53:23 +00006508 return result;
6509}
6510
Tim Petersced69f82003-09-16 20:30:58 +00006511static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006512int tailmatch(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006513 PyUnicodeObject *substring,
6514 Py_ssize_t start,
6515 Py_ssize_t end,
6516 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006517{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006518 if (substring->length == 0)
6519 return 1;
6520
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006521 ADJUST_INDICES(start, end, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006522 end -= substring->length;
6523 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00006524 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006525
6526 if (direction > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006527 if (Py_UNICODE_MATCH(self, end, substring))
6528 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006529 } else {
6530 if (Py_UNICODE_MATCH(self, start, substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00006531 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006532 }
6533
6534 return 0;
6535}
6536
Martin v. Löwis18e16552006-02-15 17:27:45 +00006537Py_ssize_t PyUnicode_Tailmatch(PyObject *str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006538 PyObject *substr,
6539 Py_ssize_t start,
6540 Py_ssize_t end,
6541 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006542{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006543 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00006544
Guido van Rossumd57fd912000-03-10 22:53:23 +00006545 str = PyUnicode_FromObject(str);
6546 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006547 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006548 substr = PyUnicode_FromObject(substr);
6549 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006550 Py_DECREF(str);
6551 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006552 }
Tim Petersced69f82003-09-16 20:30:58 +00006553
Guido van Rossumd57fd912000-03-10 22:53:23 +00006554 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006555 (PyUnicodeObject *)substr,
6556 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006557 Py_DECREF(str);
6558 Py_DECREF(substr);
6559 return result;
6560}
6561
Guido van Rossumd57fd912000-03-10 22:53:23 +00006562/* Apply fixfct filter to the Unicode object self and return a
6563 reference to the modified object */
6564
Tim Petersced69f82003-09-16 20:30:58 +00006565static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006566PyObject *fixup(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006567 int (*fixfct)(PyUnicodeObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00006568{
6569
6570 PyUnicodeObject *u;
6571
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006572 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006573 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006574 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006575
6576 Py_UNICODE_COPY(u->str, self->str, self->length);
6577
Tim Peters7a29bd52001-09-12 03:03:31 +00006578 if (!fixfct(u) && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006579 /* fixfct should return TRUE if it modified the buffer. If
6580 FALSE, return a reference to the original buffer instead
6581 (to save space, not time) */
6582 Py_INCREF(self);
6583 Py_DECREF(u);
6584 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006585 }
6586 return (PyObject*) u;
6587}
6588
Tim Petersced69f82003-09-16 20:30:58 +00006589static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006590int fixupper(PyUnicodeObject *self)
6591{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006592 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006593 Py_UNICODE *s = self->str;
6594 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006595
Guido van Rossumd57fd912000-03-10 22:53:23 +00006596 while (len-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006597 register Py_UNICODE ch;
Tim Petersced69f82003-09-16 20:30:58 +00006598
Benjamin Peterson29060642009-01-31 22:14:21 +00006599 ch = Py_UNICODE_TOUPPER(*s);
6600 if (ch != *s) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006601 status = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006602 *s = ch;
6603 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006604 s++;
6605 }
6606
6607 return status;
6608}
6609
Tim Petersced69f82003-09-16 20:30:58 +00006610static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006611int fixlower(PyUnicodeObject *self)
6612{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006613 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006614 Py_UNICODE *s = self->str;
6615 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006616
Guido van Rossumd57fd912000-03-10 22:53:23 +00006617 while (len-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006618 register Py_UNICODE ch;
Tim Petersced69f82003-09-16 20:30:58 +00006619
Benjamin Peterson29060642009-01-31 22:14:21 +00006620 ch = Py_UNICODE_TOLOWER(*s);
6621 if (ch != *s) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006622 status = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006623 *s = ch;
6624 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006625 s++;
6626 }
6627
6628 return status;
6629}
6630
Tim Petersced69f82003-09-16 20:30:58 +00006631static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006632int fixswapcase(PyUnicodeObject *self)
6633{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006634 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006635 Py_UNICODE *s = self->str;
6636 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006637
Guido van Rossumd57fd912000-03-10 22:53:23 +00006638 while (len-- > 0) {
6639 if (Py_UNICODE_ISUPPER(*s)) {
6640 *s = Py_UNICODE_TOLOWER(*s);
6641 status = 1;
6642 } else if (Py_UNICODE_ISLOWER(*s)) {
6643 *s = Py_UNICODE_TOUPPER(*s);
6644 status = 1;
6645 }
6646 s++;
6647 }
6648
6649 return status;
6650}
6651
Tim Petersced69f82003-09-16 20:30:58 +00006652static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006653int fixcapitalize(PyUnicodeObject *self)
6654{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006655 Py_ssize_t len = self->length;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006656 Py_UNICODE *s = self->str;
6657 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006658
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006659 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006660 return 0;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006661 if (Py_UNICODE_ISLOWER(*s)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006662 *s = Py_UNICODE_TOUPPER(*s);
6663 status = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006664 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006665 s++;
6666 while (--len > 0) {
6667 if (Py_UNICODE_ISUPPER(*s)) {
6668 *s = Py_UNICODE_TOLOWER(*s);
6669 status = 1;
6670 }
6671 s++;
6672 }
6673 return status;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006674}
6675
6676static
6677int fixtitle(PyUnicodeObject *self)
6678{
6679 register Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
6680 register Py_UNICODE *e;
6681 int previous_is_cased;
6682
6683 /* Shortcut for single character strings */
6684 if (PyUnicode_GET_SIZE(self) == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006685 Py_UNICODE ch = Py_UNICODE_TOTITLE(*p);
6686 if (*p != ch) {
6687 *p = ch;
6688 return 1;
6689 }
6690 else
6691 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006692 }
Tim Petersced69f82003-09-16 20:30:58 +00006693
Guido van Rossumd57fd912000-03-10 22:53:23 +00006694 e = p + PyUnicode_GET_SIZE(self);
6695 previous_is_cased = 0;
6696 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006697 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00006698
Benjamin Peterson29060642009-01-31 22:14:21 +00006699 if (previous_is_cased)
6700 *p = Py_UNICODE_TOLOWER(ch);
6701 else
6702 *p = Py_UNICODE_TOTITLE(ch);
Tim Petersced69f82003-09-16 20:30:58 +00006703
Benjamin Peterson29060642009-01-31 22:14:21 +00006704 if (Py_UNICODE_ISLOWER(ch) ||
6705 Py_UNICODE_ISUPPER(ch) ||
6706 Py_UNICODE_ISTITLE(ch))
6707 previous_is_cased = 1;
6708 else
6709 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006710 }
6711 return 1;
6712}
6713
Tim Peters8ce9f162004-08-27 01:49:32 +00006714PyObject *
6715PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006716{
Skip Montanaro6543b452004-09-16 03:28:13 +00006717 const Py_UNICODE blank = ' ';
6718 const Py_UNICODE *sep = &blank;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006719 Py_ssize_t seplen = 1;
Tim Peters05eba1f2004-08-27 21:32:02 +00006720 PyUnicodeObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00006721 Py_UNICODE *res_p; /* pointer to free byte in res's string area */
6722 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006723 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
6724 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00006725 PyObject *item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006726 Py_ssize_t sz, i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006727
Tim Peters05eba1f2004-08-27 21:32:02 +00006728 fseq = PySequence_Fast(seq, "");
6729 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006730 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00006731 }
6732
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006733 /* NOTE: the following code can't call back into Python code,
6734 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00006735 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006736
Tim Peters05eba1f2004-08-27 21:32:02 +00006737 seqlen = PySequence_Fast_GET_SIZE(fseq);
6738 /* If empty sequence, return u"". */
6739 if (seqlen == 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006740 res = _PyUnicode_New(0); /* empty sequence; return u"" */
6741 goto Done;
Tim Peters05eba1f2004-08-27 21:32:02 +00006742 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006743 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00006744 /* If singleton sequence with an exact Unicode, return that. */
6745 if (seqlen == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006746 item = items[0];
6747 if (PyUnicode_CheckExact(item)) {
6748 Py_INCREF(item);
6749 res = (PyUnicodeObject *)item;
6750 goto Done;
6751 }
Tim Peters8ce9f162004-08-27 01:49:32 +00006752 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006753 else {
6754 /* Set up sep and seplen */
6755 if (separator == NULL) {
6756 sep = &blank;
6757 seplen = 1;
Tim Peters05eba1f2004-08-27 21:32:02 +00006758 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006759 else {
6760 if (!PyUnicode_Check(separator)) {
6761 PyErr_Format(PyExc_TypeError,
6762 "separator: expected str instance,"
6763 " %.80s found",
6764 Py_TYPE(separator)->tp_name);
6765 goto onError;
6766 }
6767 sep = PyUnicode_AS_UNICODE(separator);
6768 seplen = PyUnicode_GET_SIZE(separator);
Tim Peters05eba1f2004-08-27 21:32:02 +00006769 }
6770 }
6771
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006772 /* There are at least two things to join, or else we have a subclass
6773 * of str in the sequence.
6774 * Do a pre-pass to figure out the total amount of space we'll
6775 * need (sz), and see whether all argument are strings.
6776 */
6777 sz = 0;
6778 for (i = 0; i < seqlen; i++) {
6779 const Py_ssize_t old_sz = sz;
6780 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00006781 if (!PyUnicode_Check(item)) {
6782 PyErr_Format(PyExc_TypeError,
6783 "sequence item %zd: expected str instance,"
6784 " %.80s found",
6785 i, Py_TYPE(item)->tp_name);
6786 goto onError;
6787 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006788 sz += PyUnicode_GET_SIZE(item);
6789 if (i != 0)
6790 sz += seplen;
6791 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
6792 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00006793 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006794 goto onError;
6795 }
6796 }
Tim Petersced69f82003-09-16 20:30:58 +00006797
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006798 res = _PyUnicode_New(sz);
6799 if (res == NULL)
6800 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00006801
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006802 /* Catenate everything. */
6803 res_p = PyUnicode_AS_UNICODE(res);
6804 for (i = 0; i < seqlen; ++i) {
6805 Py_ssize_t itemlen;
6806 item = items[i];
6807 itemlen = PyUnicode_GET_SIZE(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00006808 /* Copy item, and maybe the separator. */
6809 if (i) {
6810 Py_UNICODE_COPY(res_p, sep, seplen);
6811 res_p += seplen;
6812 }
6813 Py_UNICODE_COPY(res_p, PyUnicode_AS_UNICODE(item), itemlen);
6814 res_p += itemlen;
Tim Peters05eba1f2004-08-27 21:32:02 +00006815 }
Tim Peters8ce9f162004-08-27 01:49:32 +00006816
Benjamin Peterson29060642009-01-31 22:14:21 +00006817 Done:
Tim Peters05eba1f2004-08-27 21:32:02 +00006818 Py_DECREF(fseq);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006819 return (PyObject *)res;
6820
Benjamin Peterson29060642009-01-31 22:14:21 +00006821 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00006822 Py_DECREF(fseq);
Tim Peters8ce9f162004-08-27 01:49:32 +00006823 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006824 return NULL;
6825}
6826
Tim Petersced69f82003-09-16 20:30:58 +00006827static
6828PyUnicodeObject *pad(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006829 Py_ssize_t left,
6830 Py_ssize_t right,
6831 Py_UNICODE fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006832{
6833 PyUnicodeObject *u;
6834
6835 if (left < 0)
6836 left = 0;
6837 if (right < 0)
6838 right = 0;
6839
Tim Peters7a29bd52001-09-12 03:03:31 +00006840 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006841 Py_INCREF(self);
6842 return self;
6843 }
6844
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006845 if (left > PY_SSIZE_T_MAX - self->length ||
6846 right > PY_SSIZE_T_MAX - (left + self->length)) {
6847 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
6848 return NULL;
6849 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006850 u = _PyUnicode_New(left + self->length + right);
6851 if (u) {
6852 if (left)
6853 Py_UNICODE_FILL(u->str, fill, left);
6854 Py_UNICODE_COPY(u->str + left, self->str, self->length);
6855 if (right)
6856 Py_UNICODE_FILL(u->str + left + self->length, fill, right);
6857 }
6858
6859 return u;
6860}
6861
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006862PyObject *PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006863{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006864 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006865
6866 string = PyUnicode_FromObject(string);
6867 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006868 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006869
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006870 list = stringlib_splitlines(
6871 (PyObject*) string, PyUnicode_AS_UNICODE(string),
6872 PyUnicode_GET_SIZE(string), keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006873
6874 Py_DECREF(string);
6875 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006876}
6877
Tim Petersced69f82003-09-16 20:30:58 +00006878static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006879PyObject *split(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006880 PyUnicodeObject *substring,
6881 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006882{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006883 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006884 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006885
Guido van Rossumd57fd912000-03-10 22:53:23 +00006886 if (substring == NULL)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006887 return stringlib_split_whitespace(
6888 (PyObject*) self, self->str, self->length, maxcount
6889 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00006890
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006891 return stringlib_split(
6892 (PyObject*) self, self->str, self->length,
6893 substring->str, substring->length,
6894 maxcount
6895 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00006896}
6897
Tim Petersced69f82003-09-16 20:30:58 +00006898static
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006899PyObject *rsplit(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006900 PyUnicodeObject *substring,
6901 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006902{
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006903 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006904 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006905
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006906 if (substring == NULL)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006907 return stringlib_rsplit_whitespace(
6908 (PyObject*) self, self->str, self->length, maxcount
6909 );
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006910
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006911 return stringlib_rsplit(
6912 (PyObject*) self, self->str, self->length,
6913 substring->str, substring->length,
6914 maxcount
6915 );
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006916}
6917
6918static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006919PyObject *replace(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006920 PyUnicodeObject *str1,
6921 PyUnicodeObject *str2,
6922 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006923{
6924 PyUnicodeObject *u;
6925
6926 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006927 maxcount = PY_SSIZE_T_MAX;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006928 else if (maxcount == 0 || self->length == 0)
6929 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006930
Thomas Wouters477c8d52006-05-27 19:21:47 +00006931 if (str1->length == str2->length) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +00006932 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006933 /* same length */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006934 if (str1->length == 0)
6935 goto nothing;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006936 if (str1->length == 1) {
6937 /* replace characters */
6938 Py_UNICODE u1, u2;
6939 if (!findchar(self->str, self->length, str1->str[0]))
6940 goto nothing;
6941 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
6942 if (!u)
6943 return NULL;
6944 Py_UNICODE_COPY(u->str, self->str, self->length);
6945 u1 = str1->str[0];
6946 u2 = str2->str[0];
6947 for (i = 0; i < u->length; i++)
6948 if (u->str[i] == u1) {
6949 if (--maxcount < 0)
6950 break;
6951 u->str[i] = u2;
6952 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006953 } else {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006954 i = stringlib_find(
6955 self->str, self->length, str1->str, str1->length, 0
Guido van Rossumd57fd912000-03-10 22:53:23 +00006956 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00006957 if (i < 0)
6958 goto nothing;
6959 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
6960 if (!u)
6961 return NULL;
6962 Py_UNICODE_COPY(u->str, self->str, self->length);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006963
6964 /* change everything in-place, starting with this one */
6965 Py_UNICODE_COPY(u->str+i, str2->str, str2->length);
6966 i += str1->length;
6967
6968 while ( --maxcount > 0) {
6969 i = stringlib_find(self->str+i, self->length-i,
6970 str1->str, str1->length,
6971 i);
6972 if (i == -1)
6973 break;
6974 Py_UNICODE_COPY(u->str+i, str2->str, str2->length);
6975 i += str1->length;
6976 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006977 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006978 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006979
6980 Py_ssize_t n, i, j, e;
6981 Py_ssize_t product, new_size, delta;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006982 Py_UNICODE *p;
6983
6984 /* replace strings */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006985 n = stringlib_count(self->str, self->length, str1->str, str1->length,
6986 maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006987 if (n == 0)
6988 goto nothing;
6989 /* new_size = self->length + n * (str2->length - str1->length)); */
6990 delta = (str2->length - str1->length);
6991 if (delta == 0) {
6992 new_size = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006993 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006994 product = n * (str2->length - str1->length);
6995 if ((product / (str2->length - str1->length)) != n) {
6996 PyErr_SetString(PyExc_OverflowError,
6997 "replace string is too long");
6998 return NULL;
6999 }
7000 new_size = self->length + product;
7001 if (new_size < 0) {
7002 PyErr_SetString(PyExc_OverflowError,
7003 "replace string is too long");
7004 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007005 }
7006 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00007007 u = _PyUnicode_New(new_size);
7008 if (!u)
7009 return NULL;
7010 i = 0;
7011 p = u->str;
7012 e = self->length - str1->length;
7013 if (str1->length > 0) {
7014 while (n-- > 0) {
7015 /* look for next match */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007016 j = stringlib_find(self->str+i, self->length-i,
7017 str1->str, str1->length,
7018 i);
7019 if (j == -1)
7020 break;
7021 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00007022 /* copy unchanged part [i:j] */
7023 Py_UNICODE_COPY(p, self->str+i, j-i);
7024 p += j - i;
7025 }
7026 /* copy substitution string */
7027 if (str2->length > 0) {
7028 Py_UNICODE_COPY(p, str2->str, str2->length);
7029 p += str2->length;
7030 }
7031 i = j + str1->length;
7032 }
7033 if (i < self->length)
7034 /* copy tail [i:] */
7035 Py_UNICODE_COPY(p, self->str+i, self->length-i);
7036 } else {
7037 /* interleave */
7038 while (n > 0) {
7039 Py_UNICODE_COPY(p, str2->str, str2->length);
7040 p += str2->length;
7041 if (--n <= 0)
7042 break;
7043 *p++ = self->str[i++];
7044 }
7045 Py_UNICODE_COPY(p, self->str+i, self->length-i);
7046 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007047 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007048 return (PyObject *) u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007049
Benjamin Peterson29060642009-01-31 22:14:21 +00007050 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00007051 /* nothing to replace; return original string (when possible) */
7052 if (PyUnicode_CheckExact(self)) {
7053 Py_INCREF(self);
7054 return (PyObject *) self;
7055 }
7056 return PyUnicode_FromUnicode(self->str, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007057}
7058
7059/* --- Unicode Object Methods --------------------------------------------- */
7060
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007061PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007062 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007063\n\
7064Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007065characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007066
7067static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007068unicode_title(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007069{
Guido van Rossumd57fd912000-03-10 22:53:23 +00007070 return fixup(self, fixtitle);
7071}
7072
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007073PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007074 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007075\n\
7076Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +00007077have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007078
7079static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007080unicode_capitalize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007081{
Guido van Rossumd57fd912000-03-10 22:53:23 +00007082 return fixup(self, fixcapitalize);
7083}
7084
7085#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007086PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007087 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007088\n\
7089Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007090normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007091
7092static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007093unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007094{
7095 PyObject *list;
7096 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007097 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007098
Guido van Rossumd57fd912000-03-10 22:53:23 +00007099 /* Split into words */
7100 list = split(self, NULL, -1);
7101 if (!list)
7102 return NULL;
7103
7104 /* Capitalize each word */
7105 for (i = 0; i < PyList_GET_SIZE(list); i++) {
7106 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00007107 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007108 if (item == NULL)
7109 goto onError;
7110 Py_DECREF(PyList_GET_ITEM(list, i));
7111 PyList_SET_ITEM(list, i, item);
7112 }
7113
7114 /* Join the words to form a new string */
7115 item = PyUnicode_Join(NULL, list);
7116
Benjamin Peterson29060642009-01-31 22:14:21 +00007117 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007118 Py_DECREF(list);
7119 return (PyObject *)item;
7120}
7121#endif
7122
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007123/* Argument converter. Coerces to a single unicode character */
7124
7125static int
7126convert_uc(PyObject *obj, void *addr)
7127{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007128 Py_UNICODE *fillcharloc = (Py_UNICODE *)addr;
7129 PyObject *uniobj;
7130 Py_UNICODE *unistr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007131
Benjamin Peterson14339b62009-01-31 16:36:08 +00007132 uniobj = PyUnicode_FromObject(obj);
7133 if (uniobj == NULL) {
7134 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00007135 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007136 return 0;
7137 }
7138 if (PyUnicode_GET_SIZE(uniobj) != 1) {
7139 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00007140 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007141 Py_DECREF(uniobj);
7142 return 0;
7143 }
7144 unistr = PyUnicode_AS_UNICODE(uniobj);
7145 *fillcharloc = unistr[0];
7146 Py_DECREF(uniobj);
7147 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007148}
7149
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007150PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007151 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007152\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007153Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007154done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007155
7156static PyObject *
7157unicode_center(PyUnicodeObject *self, PyObject *args)
7158{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007159 Py_ssize_t marg, left;
7160 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007161 Py_UNICODE fillchar = ' ';
Guido van Rossumd57fd912000-03-10 22:53:23 +00007162
Thomas Woutersde017742006-02-16 19:34:37 +00007163 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007164 return NULL;
7165
Tim Peters7a29bd52001-09-12 03:03:31 +00007166 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00007167 Py_INCREF(self);
7168 return (PyObject*) self;
7169 }
7170
7171 marg = width - self->length;
7172 left = marg / 2 + (marg & width & 1);
7173
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007174 return (PyObject*) pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007175}
7176
Marc-André Lemburge5034372000-08-08 08:04:29 +00007177#if 0
7178
7179/* This code should go into some future Unicode collation support
7180 module. The basic comparison should compare ordinals on a naive
Georg Brandlc6c31782009-06-08 13:41:29 +00007181 basis (this is what Java does and thus Jython too). */
Marc-André Lemburge5034372000-08-08 08:04:29 +00007182
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007183/* speedy UTF-16 code point order comparison */
7184/* gleaned from: */
7185/* http://www-4.ibm.com/software/developer/library/utf16.html?dwzone=unicode */
7186
Marc-André Lemburge12896e2000-07-07 17:51:08 +00007187static short utf16Fixup[32] =
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007188{
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007189 0, 0, 0, 0, 0, 0, 0, 0,
Tim Petersced69f82003-09-16 20:30:58 +00007190 0, 0, 0, 0, 0, 0, 0, 0,
7191 0, 0, 0, 0, 0, 0, 0, 0,
Marc-André Lemburge12896e2000-07-07 17:51:08 +00007192 0, 0, 0, 0x2000, -0x800, -0x800, -0x800, -0x800
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007193};
7194
Guido van Rossumd57fd912000-03-10 22:53:23 +00007195static int
7196unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
7197{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007198 Py_ssize_t len1, len2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007199
Guido van Rossumd57fd912000-03-10 22:53:23 +00007200 Py_UNICODE *s1 = str1->str;
7201 Py_UNICODE *s2 = str2->str;
7202
7203 len1 = str1->length;
7204 len2 = str2->length;
Tim Petersced69f82003-09-16 20:30:58 +00007205
Guido van Rossumd57fd912000-03-10 22:53:23 +00007206 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00007207 Py_UNICODE c1, c2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007208
7209 c1 = *s1++;
7210 c2 = *s2++;
Fredrik Lundh45714e92001-06-26 16:39:36 +00007211
Benjamin Peterson29060642009-01-31 22:14:21 +00007212 if (c1 > (1<<11) * 26)
7213 c1 += utf16Fixup[c1>>11];
7214 if (c2 > (1<<11) * 26)
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007215 c2 += utf16Fixup[c2>>11];
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007216 /* now c1 and c2 are in UTF-32-compatible order */
Fredrik Lundh45714e92001-06-26 16:39:36 +00007217
7218 if (c1 != c2)
7219 return (c1 < c2) ? -1 : 1;
Tim Petersced69f82003-09-16 20:30:58 +00007220
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007221 len1--; len2--;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007222 }
7223
7224 return (len1 < len2) ? -1 : (len1 != len2);
7225}
7226
Marc-André Lemburge5034372000-08-08 08:04:29 +00007227#else
7228
7229static int
7230unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
7231{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007232 register Py_ssize_t len1, len2;
Marc-André Lemburge5034372000-08-08 08:04:29 +00007233
7234 Py_UNICODE *s1 = str1->str;
7235 Py_UNICODE *s2 = str2->str;
7236
7237 len1 = str1->length;
7238 len2 = str2->length;
Tim Petersced69f82003-09-16 20:30:58 +00007239
Marc-André Lemburge5034372000-08-08 08:04:29 +00007240 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00007241 Py_UNICODE c1, c2;
Marc-André Lemburge5034372000-08-08 08:04:29 +00007242
Fredrik Lundh45714e92001-06-26 16:39:36 +00007243 c1 = *s1++;
7244 c2 = *s2++;
7245
7246 if (c1 != c2)
7247 return (c1 < c2) ? -1 : 1;
7248
Marc-André Lemburge5034372000-08-08 08:04:29 +00007249 len1--; len2--;
7250 }
7251
7252 return (len1 < len2) ? -1 : (len1 != len2);
7253}
7254
7255#endif
7256
Guido van Rossumd57fd912000-03-10 22:53:23 +00007257int PyUnicode_Compare(PyObject *left,
Benjamin Peterson29060642009-01-31 22:14:21 +00007258 PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007259{
Guido van Rossum09dc34f2007-05-04 04:17:33 +00007260 if (PyUnicode_Check(left) && PyUnicode_Check(right))
7261 return unicode_compare((PyUnicodeObject *)left,
7262 (PyUnicodeObject *)right);
Guido van Rossum09dc34f2007-05-04 04:17:33 +00007263 PyErr_Format(PyExc_TypeError,
7264 "Can't compare %.100s and %.100s",
7265 left->ob_type->tp_name,
7266 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007267 return -1;
7268}
7269
Martin v. Löwis5b222132007-06-10 09:51:05 +00007270int
7271PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
7272{
7273 int i;
7274 Py_UNICODE *id;
7275 assert(PyUnicode_Check(uni));
7276 id = PyUnicode_AS_UNICODE(uni);
7277 /* Compare Unicode string and source character set string */
7278 for (i = 0; id[i] && str[i]; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00007279 if (id[i] != str[i])
7280 return ((int)id[i] < (int)str[i]) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +00007281 /* This check keeps Python strings that end in '\0' from comparing equal
7282 to C strings identical up to that point. */
Benjamin Petersona23831f2010-04-25 21:54:00 +00007283 if (PyUnicode_GET_SIZE(uni) != i || id[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00007284 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00007285 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00007286 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00007287 return 0;
7288}
7289
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007290
Benjamin Peterson29060642009-01-31 22:14:21 +00007291#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +00007292 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007293
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007294PyObject *PyUnicode_RichCompare(PyObject *left,
7295 PyObject *right,
7296 int op)
7297{
7298 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007299
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007300 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
7301 PyObject *v;
7302 if (((PyUnicodeObject *) left)->length !=
7303 ((PyUnicodeObject *) right)->length) {
7304 if (op == Py_EQ) {
7305 Py_INCREF(Py_False);
7306 return Py_False;
7307 }
7308 if (op == Py_NE) {
7309 Py_INCREF(Py_True);
7310 return Py_True;
7311 }
7312 }
7313 if (left == right)
7314 result = 0;
7315 else
7316 result = unicode_compare((PyUnicodeObject *)left,
7317 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007318
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007319 /* Convert the return value to a Boolean */
7320 switch (op) {
7321 case Py_EQ:
7322 v = TEST_COND(result == 0);
7323 break;
7324 case Py_NE:
7325 v = TEST_COND(result != 0);
7326 break;
7327 case Py_LE:
7328 v = TEST_COND(result <= 0);
7329 break;
7330 case Py_GE:
7331 v = TEST_COND(result >= 0);
7332 break;
7333 case Py_LT:
7334 v = TEST_COND(result == -1);
7335 break;
7336 case Py_GT:
7337 v = TEST_COND(result == 1);
7338 break;
7339 default:
7340 PyErr_BadArgument();
7341 return NULL;
7342 }
7343 Py_INCREF(v);
7344 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007345 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007346
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007347 Py_INCREF(Py_NotImplemented);
7348 return Py_NotImplemented;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007349}
7350
Guido van Rossum403d68b2000-03-13 15:55:09 +00007351int PyUnicode_Contains(PyObject *container,
Benjamin Peterson29060642009-01-31 22:14:21 +00007352 PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +00007353{
Thomas Wouters477c8d52006-05-27 19:21:47 +00007354 PyObject *str, *sub;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007355 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007356
7357 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +00007358 sub = PyUnicode_FromObject(element);
7359 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007360 PyErr_Format(PyExc_TypeError,
7361 "'in <string>' requires string as left operand, not %s",
7362 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007363 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007364 }
7365
Thomas Wouters477c8d52006-05-27 19:21:47 +00007366 str = PyUnicode_FromObject(container);
7367 if (!str) {
7368 Py_DECREF(sub);
7369 return -1;
7370 }
7371
7372 result = stringlib_contains_obj(str, sub);
7373
7374 Py_DECREF(str);
7375 Py_DECREF(sub);
7376
Guido van Rossum403d68b2000-03-13 15:55:09 +00007377 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007378}
7379
Guido van Rossumd57fd912000-03-10 22:53:23 +00007380/* Concat to string or Unicode object giving a new Unicode object. */
7381
7382PyObject *PyUnicode_Concat(PyObject *left,
Benjamin Peterson29060642009-01-31 22:14:21 +00007383 PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007384{
7385 PyUnicodeObject *u = NULL, *v = NULL, *w;
7386
7387 /* Coerce the two arguments */
7388 u = (PyUnicodeObject *)PyUnicode_FromObject(left);
7389 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007390 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007391 v = (PyUnicodeObject *)PyUnicode_FromObject(right);
7392 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007393 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007394
7395 /* Shortcuts */
7396 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007397 Py_DECREF(v);
7398 return (PyObject *)u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007399 }
7400 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007401 Py_DECREF(u);
7402 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007403 }
7404
7405 /* Concat the two Unicode strings */
7406 w = _PyUnicode_New(u->length + v->length);
7407 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007408 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007409 Py_UNICODE_COPY(w->str, u->str, u->length);
7410 Py_UNICODE_COPY(w->str + u->length, v->str, v->length);
7411
7412 Py_DECREF(u);
7413 Py_DECREF(v);
7414 return (PyObject *)w;
7415
Benjamin Peterson29060642009-01-31 22:14:21 +00007416 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007417 Py_XDECREF(u);
7418 Py_XDECREF(v);
7419 return NULL;
7420}
7421
Walter Dörwald1ab83302007-05-18 17:15:44 +00007422void
7423PyUnicode_Append(PyObject **pleft, PyObject *right)
7424{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007425 PyObject *new;
7426 if (*pleft == NULL)
7427 return;
7428 if (right == NULL || !PyUnicode_Check(*pleft)) {
7429 Py_DECREF(*pleft);
7430 *pleft = NULL;
7431 return;
7432 }
7433 new = PyUnicode_Concat(*pleft, right);
7434 Py_DECREF(*pleft);
7435 *pleft = new;
Walter Dörwald1ab83302007-05-18 17:15:44 +00007436}
7437
7438void
7439PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
7440{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007441 PyUnicode_Append(pleft, right);
7442 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +00007443}
7444
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007445PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007446 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007447\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00007448Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007449string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007450interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007451
7452static PyObject *
7453unicode_count(PyUnicodeObject *self, PyObject *args)
7454{
7455 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007456 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007457 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007458 PyObject *result;
7459
Jesus Ceaac451502011-04-20 17:09:23 +02007460 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
7461 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +00007462 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007463
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007464 ADJUST_INDICES(start, end, self->length);
Christian Heimes217cfd12007-12-02 14:31:20 +00007465 result = PyLong_FromSsize_t(
Thomas Wouters477c8d52006-05-27 19:21:47 +00007466 stringlib_count(self->str + start, end - start,
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007467 substring->str, substring->length,
7468 PY_SSIZE_T_MAX)
Thomas Wouters477c8d52006-05-27 19:21:47 +00007469 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007470
7471 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007472
Guido van Rossumd57fd912000-03-10 22:53:23 +00007473 return result;
7474}
7475
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007476PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +00007477 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007478\n\
Victor Stinnere14e2122010-11-07 18:41:46 +00007479Encode S using the codec registered for encoding. Default encoding\n\
7480is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +00007481handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007482a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
7483'xmlcharrefreplace' as well as any other name registered with\n\
7484codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007485
7486static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +00007487unicode_encode(PyUnicodeObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007488{
Benjamin Peterson308d6372009-09-18 21:42:35 +00007489 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +00007490 char *encoding = NULL;
7491 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +00007492
Benjamin Peterson308d6372009-09-18 21:42:35 +00007493 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
7494 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007495 return NULL;
Georg Brandl3b9406b2010-12-03 07:54:09 +00007496 return PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007497}
7498
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007499PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007500 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007501\n\
7502Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007503If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007504
7505static PyObject*
7506unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
7507{
7508 Py_UNICODE *e;
7509 Py_UNICODE *p;
7510 Py_UNICODE *q;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007511 Py_UNICODE *qe;
7512 Py_ssize_t i, j, incr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007513 PyUnicodeObject *u;
7514 int tabsize = 8;
7515
7516 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00007517 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007518
Thomas Wouters7e474022000-07-16 12:04:32 +00007519 /* First pass: determine size of output string */
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007520 i = 0; /* chars up to and including most recent \n or \r */
7521 j = 0; /* chars since most recent \n or \r (use in tab calculations) */
7522 e = self->str + self->length; /* end of input */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007523 for (p = self->str; p < e; p++)
7524 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007525 if (tabsize > 0) {
7526 incr = tabsize - (j % tabsize); /* cannot overflow */
7527 if (j > PY_SSIZE_T_MAX - incr)
7528 goto overflow1;
7529 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007530 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007531 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007532 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007533 if (j > PY_SSIZE_T_MAX - 1)
7534 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007535 j++;
7536 if (*p == '\n' || *p == '\r') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007537 if (i > PY_SSIZE_T_MAX - j)
7538 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007539 i += j;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007540 j = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007541 }
7542 }
7543
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007544 if (i > PY_SSIZE_T_MAX - j)
Benjamin Peterson29060642009-01-31 22:14:21 +00007545 goto overflow1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007546
Guido van Rossumd57fd912000-03-10 22:53:23 +00007547 /* Second pass: create output string and fill it */
7548 u = _PyUnicode_New(i + j);
7549 if (!u)
7550 return NULL;
7551
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007552 j = 0; /* same as in first pass */
7553 q = u->str; /* next output char */
7554 qe = u->str + u->length; /* end of output */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007555
7556 for (p = self->str; p < e; p++)
7557 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007558 if (tabsize > 0) {
7559 i = tabsize - (j % tabsize);
7560 j += i;
7561 while (i--) {
7562 if (q >= qe)
7563 goto overflow2;
7564 *q++ = ' ';
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007565 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007566 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007567 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007568 else {
7569 if (q >= qe)
7570 goto overflow2;
7571 *q++ = *p;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007572 j++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007573 if (*p == '\n' || *p == '\r')
7574 j = 0;
7575 }
7576
7577 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007578
7579 overflow2:
7580 Py_DECREF(u);
7581 overflow1:
7582 PyErr_SetString(PyExc_OverflowError, "new string is too long");
7583 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007584}
7585
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007586PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007587 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007588\n\
7589Return the lowest index in S where substring sub is found,\n\
Guido van Rossum806c2462007-08-06 23:33:07 +00007590such that sub is contained within s[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007591arguments start and end are interpreted as in slice notation.\n\
7592\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007593Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007594
7595static PyObject *
7596unicode_find(PyUnicodeObject *self, PyObject *args)
7597{
Jesus Ceaac451502011-04-20 17:09:23 +02007598 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00007599 Py_ssize_t start;
7600 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007601 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007602
Jesus Ceaac451502011-04-20 17:09:23 +02007603 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
7604 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007605 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007606
Thomas Wouters477c8d52006-05-27 19:21:47 +00007607 result = stringlib_find_slice(
7608 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
7609 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
7610 start, end
7611 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007612
7613 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007614
Christian Heimes217cfd12007-12-02 14:31:20 +00007615 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007616}
7617
7618static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00007619unicode_getitem(PyUnicodeObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007620{
7621 if (index < 0 || index >= self->length) {
7622 PyErr_SetString(PyExc_IndexError, "string index out of range");
7623 return NULL;
7624 }
7625
7626 return (PyObject*) PyUnicode_FromUnicode(&self->str[index], 1);
7627}
7628
Guido van Rossumc2504932007-09-18 19:42:40 +00007629/* Believe it or not, this produces the same value for ASCII strings
7630 as string_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00007631static Py_hash_t
Neil Schemenauerf8c37d12007-09-07 20:49:04 +00007632unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007633{
Guido van Rossumc2504932007-09-18 19:42:40 +00007634 Py_ssize_t len;
7635 Py_UNICODE *p;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00007636 Py_hash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +00007637
7638 if (self->hash != -1)
7639 return self->hash;
Christian Heimes90aa7642007-12-19 02:45:37 +00007640 len = Py_SIZE(self);
Guido van Rossumc2504932007-09-18 19:42:40 +00007641 p = self->str;
7642 x = *p << 7;
7643 while (--len >= 0)
7644 x = (1000003*x) ^ *p++;
Christian Heimes90aa7642007-12-19 02:45:37 +00007645 x ^= Py_SIZE(self);
Guido van Rossumc2504932007-09-18 19:42:40 +00007646 if (x == -1)
7647 x = -2;
7648 self->hash = x;
7649 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007650}
7651
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007652PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007653 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007654\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007655Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007656
7657static PyObject *
7658unicode_index(PyUnicodeObject *self, PyObject *args)
7659{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007660 Py_ssize_t result;
Jesus Ceaac451502011-04-20 17:09:23 +02007661 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00007662 Py_ssize_t start;
7663 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007664
Jesus Ceaac451502011-04-20 17:09:23 +02007665 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
7666 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007667 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007668
Thomas Wouters477c8d52006-05-27 19:21:47 +00007669 result = stringlib_find_slice(
7670 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
7671 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
7672 start, end
7673 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007674
7675 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007676
Guido van Rossumd57fd912000-03-10 22:53:23 +00007677 if (result < 0) {
7678 PyErr_SetString(PyExc_ValueError, "substring not found");
7679 return NULL;
7680 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00007681
Christian Heimes217cfd12007-12-02 14:31:20 +00007682 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007683}
7684
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007685PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007686 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007687\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007688Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007689at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007690
7691static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007692unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007693{
7694 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7695 register const Py_UNICODE *e;
7696 int cased;
7697
Guido van Rossumd57fd912000-03-10 22:53:23 +00007698 /* Shortcut for single character strings */
7699 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007700 return PyBool_FromLong(Py_UNICODE_ISLOWER(*p));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007701
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007702 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007703 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007704 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007705
Guido van Rossumd57fd912000-03-10 22:53:23 +00007706 e = p + PyUnicode_GET_SIZE(self);
7707 cased = 0;
7708 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007709 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007710
Benjamin Peterson29060642009-01-31 22:14:21 +00007711 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
7712 return PyBool_FromLong(0);
7713 else if (!cased && Py_UNICODE_ISLOWER(ch))
7714 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007715 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007716 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007717}
7718
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007719PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007720 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007721\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007722Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007723at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007724
7725static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007726unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007727{
7728 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7729 register const Py_UNICODE *e;
7730 int cased;
7731
Guido van Rossumd57fd912000-03-10 22:53:23 +00007732 /* Shortcut for single character strings */
7733 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007734 return PyBool_FromLong(Py_UNICODE_ISUPPER(*p) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007735
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007736 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007737 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007738 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007739
Guido van Rossumd57fd912000-03-10 22:53:23 +00007740 e = p + PyUnicode_GET_SIZE(self);
7741 cased = 0;
7742 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007743 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007744
Benjamin Peterson29060642009-01-31 22:14:21 +00007745 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
7746 return PyBool_FromLong(0);
7747 else if (!cased && Py_UNICODE_ISUPPER(ch))
7748 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007749 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007750 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007751}
7752
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007753PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007754 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007755\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007756Return True if S is a titlecased string and there is at least one\n\
7757character in S, i.e. upper- and titlecase characters may only\n\
7758follow uncased characters and lowercase characters only cased ones.\n\
7759Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007760
7761static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007762unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007763{
7764 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7765 register const Py_UNICODE *e;
7766 int cased, previous_is_cased;
7767
Guido van Rossumd57fd912000-03-10 22:53:23 +00007768 /* Shortcut for single character strings */
7769 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007770 return PyBool_FromLong((Py_UNICODE_ISTITLE(*p) != 0) ||
7771 (Py_UNICODE_ISUPPER(*p) != 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007772
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007773 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007774 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007775 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007776
Guido van Rossumd57fd912000-03-10 22:53:23 +00007777 e = p + PyUnicode_GET_SIZE(self);
7778 cased = 0;
7779 previous_is_cased = 0;
7780 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007781 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007782
Benjamin Peterson29060642009-01-31 22:14:21 +00007783 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
7784 if (previous_is_cased)
7785 return PyBool_FromLong(0);
7786 previous_is_cased = 1;
7787 cased = 1;
7788 }
7789 else if (Py_UNICODE_ISLOWER(ch)) {
7790 if (!previous_is_cased)
7791 return PyBool_FromLong(0);
7792 previous_is_cased = 1;
7793 cased = 1;
7794 }
7795 else
7796 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007797 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007798 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007799}
7800
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007801PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007802 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007803\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007804Return True if all characters in S are whitespace\n\
7805and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007806
7807static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007808unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007809{
7810 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7811 register const Py_UNICODE *e;
7812
Guido van Rossumd57fd912000-03-10 22:53:23 +00007813 /* Shortcut for single character strings */
7814 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007815 Py_UNICODE_ISSPACE(*p))
7816 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007817
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007818 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007819 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007820 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007821
Guido van Rossumd57fd912000-03-10 22:53:23 +00007822 e = p + PyUnicode_GET_SIZE(self);
7823 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007824 if (!Py_UNICODE_ISSPACE(*p))
7825 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007826 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007827 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007828}
7829
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007830PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007831 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007832\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007833Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007834and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007835
7836static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007837unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007838{
7839 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7840 register const Py_UNICODE *e;
7841
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007842 /* Shortcut for single character strings */
7843 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007844 Py_UNICODE_ISALPHA(*p))
7845 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007846
7847 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007848 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007849 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007850
7851 e = p + PyUnicode_GET_SIZE(self);
7852 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007853 if (!Py_UNICODE_ISALPHA(*p))
7854 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007855 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007856 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007857}
7858
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007859PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007860 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007861\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007862Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007863and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007864
7865static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007866unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007867{
7868 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7869 register const Py_UNICODE *e;
7870
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007871 /* Shortcut for single character strings */
7872 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007873 Py_UNICODE_ISALNUM(*p))
7874 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007875
7876 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007877 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007878 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007879
7880 e = p + PyUnicode_GET_SIZE(self);
7881 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007882 if (!Py_UNICODE_ISALNUM(*p))
7883 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007884 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007885 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007886}
7887
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007888PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007889 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007890\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007891Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007892False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007893
7894static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007895unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007896{
7897 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7898 register const Py_UNICODE *e;
7899
Guido van Rossumd57fd912000-03-10 22:53:23 +00007900 /* Shortcut for single character strings */
7901 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007902 Py_UNICODE_ISDECIMAL(*p))
7903 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007904
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007905 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007906 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007907 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007908
Guido van Rossumd57fd912000-03-10 22:53:23 +00007909 e = p + PyUnicode_GET_SIZE(self);
7910 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007911 if (!Py_UNICODE_ISDECIMAL(*p))
7912 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007913 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007914 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007915}
7916
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007917PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007918 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007919\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007920Return True if all characters in S are digits\n\
7921and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007922
7923static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007924unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007925{
7926 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7927 register const Py_UNICODE *e;
7928
Guido van Rossumd57fd912000-03-10 22:53:23 +00007929 /* Shortcut for single character strings */
7930 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007931 Py_UNICODE_ISDIGIT(*p))
7932 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007933
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007934 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007935 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007936 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007937
Guido van Rossumd57fd912000-03-10 22:53:23 +00007938 e = p + PyUnicode_GET_SIZE(self);
7939 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007940 if (!Py_UNICODE_ISDIGIT(*p))
7941 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007942 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007943 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007944}
7945
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007946PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007947 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007948\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007949Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007950False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007951
7952static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007953unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007954{
7955 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7956 register const Py_UNICODE *e;
7957
Guido van Rossumd57fd912000-03-10 22:53:23 +00007958 /* Shortcut for single character strings */
7959 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007960 Py_UNICODE_ISNUMERIC(*p))
7961 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007962
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007963 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007964 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007965 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007966
Guido van Rossumd57fd912000-03-10 22:53:23 +00007967 e = p + PyUnicode_GET_SIZE(self);
7968 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007969 if (!Py_UNICODE_ISNUMERIC(*p))
7970 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007971 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007972 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007973}
7974
Martin v. Löwis47383402007-08-15 07:32:56 +00007975int
7976PyUnicode_IsIdentifier(PyObject *self)
7977{
7978 register const Py_UNICODE *p = PyUnicode_AS_UNICODE((PyUnicodeObject*)self);
7979 register const Py_UNICODE *e;
7980
7981 /* Special case for empty strings */
7982 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007983 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +00007984
7985 /* PEP 3131 says that the first character must be in
7986 XID_Start and subsequent characters in XID_Continue,
7987 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +00007988 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +00007989 letters, digits, underscore). However, given the current
7990 definition of XID_Start and XID_Continue, it is sufficient
7991 to check just for these, except that _ must be allowed
7992 as starting an identifier. */
7993 if (!_PyUnicode_IsXidStart(*p) && *p != 0x5F /* LOW LINE */)
7994 return 0;
7995
7996 e = p + PyUnicode_GET_SIZE(self);
7997 for (p++; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007998 if (!_PyUnicode_IsXidContinue(*p))
7999 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +00008000 }
8001 return 1;
8002}
8003
8004PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008005 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +00008006\n\
8007Return True if S is a valid identifier according\n\
8008to the language definition.");
8009
8010static PyObject*
8011unicode_isidentifier(PyObject *self)
8012{
8013 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
8014}
8015
Georg Brandl559e5d72008-06-11 18:37:52 +00008016PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008017 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +00008018\n\
8019Return True if all characters in S are considered\n\
8020printable in repr() or S is empty, False otherwise.");
8021
8022static PyObject*
8023unicode_isprintable(PyObject *self)
8024{
8025 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
8026 register const Py_UNICODE *e;
8027
8028 /* Shortcut for single character strings */
8029 if (PyUnicode_GET_SIZE(self) == 1 && Py_UNICODE_ISPRINTABLE(*p)) {
8030 Py_RETURN_TRUE;
8031 }
8032
8033 e = p + PyUnicode_GET_SIZE(self);
8034 for (; p < e; p++) {
8035 if (!Py_UNICODE_ISPRINTABLE(*p)) {
8036 Py_RETURN_FALSE;
8037 }
8038 }
8039 Py_RETURN_TRUE;
8040}
8041
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008042PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +00008043 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008044\n\
8045Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +00008046iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008047
8048static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008049unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008050{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008051 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008052}
8053
Martin v. Löwis18e16552006-02-15 17:27:45 +00008054static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +00008055unicode_length(PyUnicodeObject *self)
8056{
8057 return self->length;
8058}
8059
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008060PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008061 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008062\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008063Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008064done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008065
8066static PyObject *
8067unicode_ljust(PyUnicodeObject *self, PyObject *args)
8068{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008069 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008070 Py_UNICODE fillchar = ' ';
8071
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008072 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008073 return NULL;
8074
Tim Peters7a29bd52001-09-12 03:03:31 +00008075 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008076 Py_INCREF(self);
8077 return (PyObject*) self;
8078 }
8079
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008080 return (PyObject*) pad(self, 0, width - self->length, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008081}
8082
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008083PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008084 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008085\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008086Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008087
8088static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008089unicode_lower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008090{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008091 return fixup(self, fixlower);
8092}
8093
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008094#define LEFTSTRIP 0
8095#define RIGHTSTRIP 1
8096#define BOTHSTRIP 2
8097
8098/* Arrays indexed by above */
8099static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
8100
8101#define STRIPNAME(i) (stripformat[i]+3)
8102
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008103/* externally visible for str.strip(unicode) */
8104PyObject *
8105_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
8106{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008107 Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
8108 Py_ssize_t len = PyUnicode_GET_SIZE(self);
8109 Py_UNICODE *sep = PyUnicode_AS_UNICODE(sepobj);
8110 Py_ssize_t seplen = PyUnicode_GET_SIZE(sepobj);
8111 Py_ssize_t i, j;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008112
Benjamin Peterson29060642009-01-31 22:14:21 +00008113 BLOOM_MASK sepmask = make_bloom_mask(sep, seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008114
Benjamin Peterson14339b62009-01-31 16:36:08 +00008115 i = 0;
8116 if (striptype != RIGHTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008117 while (i < len && BLOOM_MEMBER(sepmask, s[i], sep, seplen)) {
8118 i++;
8119 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008120 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008121
Benjamin Peterson14339b62009-01-31 16:36:08 +00008122 j = len;
8123 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008124 do {
8125 j--;
8126 } while (j >= i && BLOOM_MEMBER(sepmask, s[j], sep, seplen));
8127 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008128 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008129
Benjamin Peterson14339b62009-01-31 16:36:08 +00008130 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008131 Py_INCREF(self);
8132 return (PyObject*)self;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008133 }
8134 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008135 return PyUnicode_FromUnicode(s+i, j-i);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008136}
8137
Guido van Rossumd57fd912000-03-10 22:53:23 +00008138
8139static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008140do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008141{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008142 Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
8143 Py_ssize_t len = PyUnicode_GET_SIZE(self), i, j;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008144
Benjamin Peterson14339b62009-01-31 16:36:08 +00008145 i = 0;
8146 if (striptype != RIGHTSTRIP) {
8147 while (i < len && Py_UNICODE_ISSPACE(s[i])) {
8148 i++;
8149 }
8150 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008151
Benjamin Peterson14339b62009-01-31 16:36:08 +00008152 j = len;
8153 if (striptype != LEFTSTRIP) {
8154 do {
8155 j--;
8156 } while (j >= i && Py_UNICODE_ISSPACE(s[j]));
8157 j++;
8158 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008159
Benjamin Peterson14339b62009-01-31 16:36:08 +00008160 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
8161 Py_INCREF(self);
8162 return (PyObject*)self;
8163 }
8164 else
8165 return PyUnicode_FromUnicode(s+i, j-i);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008166}
8167
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008168
8169static PyObject *
8170do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
8171{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008172 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008173
Benjamin Peterson14339b62009-01-31 16:36:08 +00008174 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
8175 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008176
Benjamin Peterson14339b62009-01-31 16:36:08 +00008177 if (sep != NULL && sep != Py_None) {
8178 if (PyUnicode_Check(sep))
8179 return _PyUnicode_XStrip(self, striptype, sep);
8180 else {
8181 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00008182 "%s arg must be None or str",
8183 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +00008184 return NULL;
8185 }
8186 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008187
Benjamin Peterson14339b62009-01-31 16:36:08 +00008188 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008189}
8190
8191
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008192PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008193 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008194\n\
8195Return a copy of the string S with leading and trailing\n\
8196whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008197If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008198
8199static PyObject *
8200unicode_strip(PyUnicodeObject *self, PyObject *args)
8201{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008202 if (PyTuple_GET_SIZE(args) == 0)
8203 return do_strip(self, BOTHSTRIP); /* Common case */
8204 else
8205 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008206}
8207
8208
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008209PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008210 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008211\n\
8212Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008213If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008214
8215static PyObject *
8216unicode_lstrip(PyUnicodeObject *self, PyObject *args)
8217{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008218 if (PyTuple_GET_SIZE(args) == 0)
8219 return do_strip(self, LEFTSTRIP); /* Common case */
8220 else
8221 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008222}
8223
8224
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008225PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008226 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008227\n\
8228Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008229If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008230
8231static PyObject *
8232unicode_rstrip(PyUnicodeObject *self, PyObject *args)
8233{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008234 if (PyTuple_GET_SIZE(args) == 0)
8235 return do_strip(self, RIGHTSTRIP); /* Common case */
8236 else
8237 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008238}
8239
8240
Guido van Rossumd57fd912000-03-10 22:53:23 +00008241static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +00008242unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008243{
8244 PyUnicodeObject *u;
8245 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008246 Py_ssize_t nchars;
Tim Peters8f422462000-09-09 06:13:41 +00008247 size_t nbytes;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008248
Georg Brandl222de0f2009-04-12 12:01:50 +00008249 if (len < 1) {
8250 Py_INCREF(unicode_empty);
8251 return (PyObject *)unicode_empty;
8252 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008253
Tim Peters7a29bd52001-09-12 03:03:31 +00008254 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008255 /* no repeat, return original string */
8256 Py_INCREF(str);
8257 return (PyObject*) str;
8258 }
Tim Peters8f422462000-09-09 06:13:41 +00008259
8260 /* ensure # of chars needed doesn't overflow int and # of bytes
8261 * needed doesn't overflow size_t
8262 */
8263 nchars = len * str->length;
Georg Brandl222de0f2009-04-12 12:01:50 +00008264 if (nchars / len != str->length) {
Tim Peters8f422462000-09-09 06:13:41 +00008265 PyErr_SetString(PyExc_OverflowError,
8266 "repeated string is too long");
8267 return NULL;
8268 }
8269 nbytes = (nchars + 1) * sizeof(Py_UNICODE);
8270 if (nbytes / sizeof(Py_UNICODE) != (size_t)(nchars + 1)) {
8271 PyErr_SetString(PyExc_OverflowError,
8272 "repeated string is too long");
8273 return NULL;
8274 }
8275 u = _PyUnicode_New(nchars);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008276 if (!u)
8277 return NULL;
8278
8279 p = u->str;
8280
Georg Brandl222de0f2009-04-12 12:01:50 +00008281 if (str->length == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00008282 Py_UNICODE_FILL(p, str->str[0], len);
8283 } else {
Georg Brandl222de0f2009-04-12 12:01:50 +00008284 Py_ssize_t done = str->length; /* number of characters copied this far */
8285 Py_UNICODE_COPY(p, str->str, str->length);
Benjamin Peterson29060642009-01-31 22:14:21 +00008286 while (done < nchars) {
Christian Heimescc47b052008-03-25 14:56:36 +00008287 Py_ssize_t n = (done <= nchars-done) ? done : nchars-done;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008288 Py_UNICODE_COPY(p+done, p, n);
8289 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00008290 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008291 }
8292
8293 return (PyObject*) u;
8294}
8295
8296PyObject *PyUnicode_Replace(PyObject *obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00008297 PyObject *subobj,
8298 PyObject *replobj,
8299 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008300{
8301 PyObject *self;
8302 PyObject *str1;
8303 PyObject *str2;
8304 PyObject *result;
8305
8306 self = PyUnicode_FromObject(obj);
8307 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008308 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008309 str1 = PyUnicode_FromObject(subobj);
8310 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008311 Py_DECREF(self);
8312 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008313 }
8314 str2 = PyUnicode_FromObject(replobj);
8315 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008316 Py_DECREF(self);
8317 Py_DECREF(str1);
8318 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008319 }
Tim Petersced69f82003-09-16 20:30:58 +00008320 result = replace((PyUnicodeObject *)self,
Benjamin Peterson29060642009-01-31 22:14:21 +00008321 (PyUnicodeObject *)str1,
8322 (PyUnicodeObject *)str2,
8323 maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008324 Py_DECREF(self);
8325 Py_DECREF(str1);
8326 Py_DECREF(str2);
8327 return result;
8328}
8329
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008330PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +00008331 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008332\n\
8333Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +00008334old replaced by new. If the optional argument count is\n\
8335given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008336
8337static PyObject*
8338unicode_replace(PyUnicodeObject *self, PyObject *args)
8339{
8340 PyUnicodeObject *str1;
8341 PyUnicodeObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008342 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008343 PyObject *result;
8344
Martin v. Löwis18e16552006-02-15 17:27:45 +00008345 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008346 return NULL;
8347 str1 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str1);
8348 if (str1 == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008349 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008350 str2 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str2);
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +00008351 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008352 Py_DECREF(str1);
8353 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +00008354 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008355
8356 result = replace(self, str1, str2, maxcount);
8357
8358 Py_DECREF(str1);
8359 Py_DECREF(str2);
8360 return result;
8361}
8362
8363static
8364PyObject *unicode_repr(PyObject *unicode)
8365{
Walter Dörwald79e913e2007-05-12 11:08:06 +00008366 PyObject *repr;
Walter Dörwald1ab83302007-05-18 17:15:44 +00008367 Py_UNICODE *p;
Walter Dörwald79e913e2007-05-12 11:08:06 +00008368 Py_UNICODE *s = PyUnicode_AS_UNICODE(unicode);
8369 Py_ssize_t size = PyUnicode_GET_SIZE(unicode);
8370
8371 /* XXX(nnorwitz): rather than over-allocating, it would be
8372 better to choose a different scheme. Perhaps scan the
8373 first N-chars of the string and allocate based on that size.
8374 */
8375 /* Initial allocation is based on the longest-possible unichr
8376 escape.
8377
8378 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
8379 unichr, so in this case it's the longest unichr escape. In
8380 narrow (UTF-16) builds this is five chars per source unichr
8381 since there are two unichrs in the surrogate pair, so in narrow
8382 (UTF-16) builds it's not the longest unichr escape.
8383
8384 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
8385 so in the narrow (UTF-16) build case it's the longest unichr
8386 escape.
8387 */
8388
Walter Dörwald1ab83302007-05-18 17:15:44 +00008389 repr = PyUnicode_FromUnicode(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00008390 2 /* quotes */
Walter Dörwald79e913e2007-05-12 11:08:06 +00008391#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00008392 + 10*size
Walter Dörwald79e913e2007-05-12 11:08:06 +00008393#else
Benjamin Peterson29060642009-01-31 22:14:21 +00008394 + 6*size
Walter Dörwald79e913e2007-05-12 11:08:06 +00008395#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00008396 + 1);
Walter Dörwald79e913e2007-05-12 11:08:06 +00008397 if (repr == NULL)
8398 return NULL;
8399
Walter Dörwald1ab83302007-05-18 17:15:44 +00008400 p = PyUnicode_AS_UNICODE(repr);
Walter Dörwald79e913e2007-05-12 11:08:06 +00008401
8402 /* Add quote */
8403 *p++ = (findchar(s, size, '\'') &&
8404 !findchar(s, size, '"')) ? '"' : '\'';
8405 while (size-- > 0) {
8406 Py_UNICODE ch = *s++;
8407
8408 /* Escape quotes and backslashes */
Walter Dörwald1ab83302007-05-18 17:15:44 +00008409 if ((ch == PyUnicode_AS_UNICODE(repr)[0]) || (ch == '\\')) {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008410 *p++ = '\\';
Walter Dörwald1ab83302007-05-18 17:15:44 +00008411 *p++ = ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00008412 continue;
8413 }
8414
Benjamin Peterson29060642009-01-31 22:14:21 +00008415 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +00008416 if (ch == '\t') {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008417 *p++ = '\\';
8418 *p++ = 't';
8419 }
8420 else if (ch == '\n') {
8421 *p++ = '\\';
8422 *p++ = 'n';
8423 }
8424 else if (ch == '\r') {
8425 *p++ = '\\';
8426 *p++ = 'r';
8427 }
8428
8429 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +00008430 else if (ch < ' ' || ch == 0x7F) {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008431 *p++ = '\\';
8432 *p++ = 'x';
8433 *p++ = hexdigits[(ch >> 4) & 0x000F];
8434 *p++ = hexdigits[ch & 0x000F];
8435 }
8436
Georg Brandl559e5d72008-06-11 18:37:52 +00008437 /* Copy ASCII characters as-is */
8438 else if (ch < 0x7F) {
8439 *p++ = ch;
8440 }
8441
Benjamin Peterson29060642009-01-31 22:14:21 +00008442 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +00008443 else {
8444 Py_UCS4 ucs = ch;
8445
8446#ifndef Py_UNICODE_WIDE
8447 Py_UNICODE ch2 = 0;
8448 /* Get code point from surrogate pair */
8449 if (size > 0) {
8450 ch2 = *s;
8451 if (ch >= 0xD800 && ch < 0xDC00 && ch2 >= 0xDC00
Benjamin Peterson29060642009-01-31 22:14:21 +00008452 && ch2 <= 0xDFFF) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008453 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF))
Benjamin Peterson29060642009-01-31 22:14:21 +00008454 + 0x00010000;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008455 s++;
Georg Brandl559e5d72008-06-11 18:37:52 +00008456 size--;
8457 }
8458 }
8459#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00008460 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +00008461 (categories Z* and C* except ASCII space)
8462 */
8463 if (!Py_UNICODE_ISPRINTABLE(ucs)) {
8464 /* Map 8-bit characters to '\xhh' */
8465 if (ucs <= 0xff) {
8466 *p++ = '\\';
8467 *p++ = 'x';
8468 *p++ = hexdigits[(ch >> 4) & 0x000F];
8469 *p++ = hexdigits[ch & 0x000F];
8470 }
8471 /* Map 21-bit characters to '\U00xxxxxx' */
8472 else if (ucs >= 0x10000) {
8473 *p++ = '\\';
8474 *p++ = 'U';
8475 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
8476 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
8477 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
8478 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
8479 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
8480 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
8481 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
8482 *p++ = hexdigits[ucs & 0x0000000F];
8483 }
8484 /* Map 16-bit characters to '\uxxxx' */
8485 else {
8486 *p++ = '\\';
8487 *p++ = 'u';
8488 *p++ = hexdigits[(ucs >> 12) & 0x000F];
8489 *p++ = hexdigits[(ucs >> 8) & 0x000F];
8490 *p++ = hexdigits[(ucs >> 4) & 0x000F];
8491 *p++ = hexdigits[ucs & 0x000F];
8492 }
8493 }
8494 /* Copy characters as-is */
8495 else {
8496 *p++ = ch;
8497#ifndef Py_UNICODE_WIDE
8498 if (ucs >= 0x10000)
8499 *p++ = ch2;
8500#endif
8501 }
8502 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00008503 }
8504 /* Add quote */
Walter Dörwald1ab83302007-05-18 17:15:44 +00008505 *p++ = PyUnicode_AS_UNICODE(repr)[0];
Walter Dörwald79e913e2007-05-12 11:08:06 +00008506
8507 *p = '\0';
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00008508 PyUnicode_Resize(&repr, p - PyUnicode_AS_UNICODE(repr));
Walter Dörwald79e913e2007-05-12 11:08:06 +00008509 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008510}
8511
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008512PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008513 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008514\n\
8515Return the highest index in S where substring sub is found,\n\
Guido van Rossum806c2462007-08-06 23:33:07 +00008516such that sub is contained within s[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008517arguments start and end are interpreted as in slice notation.\n\
8518\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008519Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008520
8521static PyObject *
8522unicode_rfind(PyUnicodeObject *self, PyObject *args)
8523{
Jesus Ceaac451502011-04-20 17:09:23 +02008524 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00008525 Py_ssize_t start;
8526 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008527 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008528
Jesus Ceaac451502011-04-20 17:09:23 +02008529 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
8530 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008531 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008532
Thomas Wouters477c8d52006-05-27 19:21:47 +00008533 result = stringlib_rfind_slice(
8534 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
8535 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
8536 start, end
8537 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008538
8539 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008540
Christian Heimes217cfd12007-12-02 14:31:20 +00008541 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008542}
8543
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008544PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008545 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008546\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008547Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008548
8549static PyObject *
8550unicode_rindex(PyUnicodeObject *self, PyObject *args)
8551{
Jesus Ceaac451502011-04-20 17:09:23 +02008552 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00008553 Py_ssize_t start;
8554 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008555 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008556
Jesus Ceaac451502011-04-20 17:09:23 +02008557 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
8558 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008559 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008560
Thomas Wouters477c8d52006-05-27 19:21:47 +00008561 result = stringlib_rfind_slice(
8562 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
8563 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
8564 start, end
8565 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008566
8567 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008568
Guido van Rossumd57fd912000-03-10 22:53:23 +00008569 if (result < 0) {
8570 PyErr_SetString(PyExc_ValueError, "substring not found");
8571 return NULL;
8572 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008573 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008574}
8575
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008576PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008577 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008578\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008579Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008580done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008581
8582static PyObject *
8583unicode_rjust(PyUnicodeObject *self, PyObject *args)
8584{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008585 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008586 Py_UNICODE fillchar = ' ';
8587
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008588 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008589 return NULL;
8590
Tim Peters7a29bd52001-09-12 03:03:31 +00008591 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008592 Py_INCREF(self);
8593 return (PyObject*) self;
8594 }
8595
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008596 return (PyObject*) pad(self, width - self->length, 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008597}
8598
Guido van Rossumd57fd912000-03-10 22:53:23 +00008599PyObject *PyUnicode_Split(PyObject *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00008600 PyObject *sep,
8601 Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008602{
8603 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008604
Guido van Rossumd57fd912000-03-10 22:53:23 +00008605 s = PyUnicode_FromObject(s);
8606 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008607 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00008608 if (sep != NULL) {
8609 sep = PyUnicode_FromObject(sep);
8610 if (sep == NULL) {
8611 Py_DECREF(s);
8612 return NULL;
8613 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008614 }
8615
8616 result = split((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
8617
8618 Py_DECREF(s);
8619 Py_XDECREF(sep);
8620 return result;
8621}
8622
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008623PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008624 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008625\n\
8626Return a list of the words in S, using sep as the\n\
8627delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00008628splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00008629whitespace string is a separator and empty strings are\n\
8630removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008631
8632static PyObject*
8633unicode_split(PyUnicodeObject *self, PyObject *args)
8634{
8635 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008636 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008637
Martin v. Löwis18e16552006-02-15 17:27:45 +00008638 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008639 return NULL;
8640
8641 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008642 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008643 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00008644 return split(self, (PyUnicodeObject *)substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008645 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008646 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008647}
8648
Thomas Wouters477c8d52006-05-27 19:21:47 +00008649PyObject *
8650PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
8651{
8652 PyObject* str_obj;
8653 PyObject* sep_obj;
8654 PyObject* out;
8655
8656 str_obj = PyUnicode_FromObject(str_in);
8657 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008658 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008659 sep_obj = PyUnicode_FromObject(sep_in);
8660 if (!sep_obj) {
8661 Py_DECREF(str_obj);
8662 return NULL;
8663 }
8664
8665 out = stringlib_partition(
8666 str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
8667 sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
8668 );
8669
8670 Py_DECREF(sep_obj);
8671 Py_DECREF(str_obj);
8672
8673 return out;
8674}
8675
8676
8677PyObject *
8678PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
8679{
8680 PyObject* str_obj;
8681 PyObject* sep_obj;
8682 PyObject* out;
8683
8684 str_obj = PyUnicode_FromObject(str_in);
8685 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008686 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008687 sep_obj = PyUnicode_FromObject(sep_in);
8688 if (!sep_obj) {
8689 Py_DECREF(str_obj);
8690 return NULL;
8691 }
8692
8693 out = stringlib_rpartition(
8694 str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
8695 sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
8696 );
8697
8698 Py_DECREF(sep_obj);
8699 Py_DECREF(str_obj);
8700
8701 return out;
8702}
8703
8704PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008705 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008706\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00008707Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008708the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008709found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00008710
8711static PyObject*
8712unicode_partition(PyUnicodeObject *self, PyObject *separator)
8713{
8714 return PyUnicode_Partition((PyObject *)self, separator);
8715}
8716
8717PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +00008718 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008719\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00008720Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008721the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008722separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00008723
8724static PyObject*
8725unicode_rpartition(PyUnicodeObject *self, PyObject *separator)
8726{
8727 return PyUnicode_RPartition((PyObject *)self, separator);
8728}
8729
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008730PyObject *PyUnicode_RSplit(PyObject *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00008731 PyObject *sep,
8732 Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008733{
8734 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008735
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008736 s = PyUnicode_FromObject(s);
8737 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008738 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00008739 if (sep != NULL) {
8740 sep = PyUnicode_FromObject(sep);
8741 if (sep == NULL) {
8742 Py_DECREF(s);
8743 return NULL;
8744 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008745 }
8746
8747 result = rsplit((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
8748
8749 Py_DECREF(s);
8750 Py_XDECREF(sep);
8751 return result;
8752}
8753
8754PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008755 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008756\n\
8757Return a list of the words in S, using sep as the\n\
8758delimiter string, starting at the end of the string and\n\
8759working to the front. If maxsplit is given, at most maxsplit\n\
8760splits are done. If sep is not specified, any whitespace string\n\
8761is a separator.");
8762
8763static PyObject*
8764unicode_rsplit(PyUnicodeObject *self, PyObject *args)
8765{
8766 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008767 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008768
Martin v. Löwis18e16552006-02-15 17:27:45 +00008769 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008770 return NULL;
8771
8772 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008773 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008774 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00008775 return rsplit(self, (PyUnicodeObject *)substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008776 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008777 return PyUnicode_RSplit((PyObject *)self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008778}
8779
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008780PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008781 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008782\n\
8783Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +00008784Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008785is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008786
8787static PyObject*
8788unicode_splitlines(PyUnicodeObject *self, PyObject *args)
8789{
Guido van Rossum86662912000-04-11 15:38:46 +00008790 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008791
Guido van Rossum86662912000-04-11 15:38:46 +00008792 if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008793 return NULL;
8794
Guido van Rossum86662912000-04-11 15:38:46 +00008795 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008796}
8797
8798static
Guido van Rossumf15a29f2007-05-04 00:41:39 +00008799PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008800{
Walter Dörwald346737f2007-05-31 10:44:43 +00008801 if (PyUnicode_CheckExact(self)) {
8802 Py_INCREF(self);
8803 return self;
8804 } else
8805 /* Subtype -- return genuine unicode string with the same value. */
8806 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(self),
8807 PyUnicode_GET_SIZE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +00008808}
8809
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008810PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008811 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008812\n\
8813Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008814and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008815
8816static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008817unicode_swapcase(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008818{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008819 return fixup(self, fixswapcase);
8820}
8821
Georg Brandlceee0772007-11-27 23:48:05 +00008822PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008823 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +00008824\n\
8825Return a translation table usable for str.translate().\n\
8826If there is only one argument, it must be a dictionary mapping Unicode\n\
8827ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008828Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +00008829If there are two arguments, they must be strings of equal length, and\n\
8830in the resulting dictionary, each character in x will be mapped to the\n\
8831character at the same position in y. If there is a third argument, it\n\
8832must be a string, whose characters will be mapped to None in the result.");
8833
8834static PyObject*
8835unicode_maketrans(PyUnicodeObject *null, PyObject *args)
8836{
8837 PyObject *x, *y = NULL, *z = NULL;
8838 PyObject *new = NULL, *key, *value;
8839 Py_ssize_t i = 0;
8840 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008841
Georg Brandlceee0772007-11-27 23:48:05 +00008842 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
8843 return NULL;
8844 new = PyDict_New();
8845 if (!new)
8846 return NULL;
8847 if (y != NULL) {
8848 /* x must be a string too, of equal length */
8849 Py_ssize_t ylen = PyUnicode_GET_SIZE(y);
8850 if (!PyUnicode_Check(x)) {
8851 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
8852 "be a string if there is a second argument");
8853 goto err;
8854 }
8855 if (PyUnicode_GET_SIZE(x) != ylen) {
8856 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
8857 "arguments must have equal length");
8858 goto err;
8859 }
8860 /* create entries for translating chars in x to those in y */
8861 for (i = 0; i < PyUnicode_GET_SIZE(x); i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +00008862 key = PyLong_FromLong(PyUnicode_AS_UNICODE(x)[i]);
8863 value = PyLong_FromLong(PyUnicode_AS_UNICODE(y)[i]);
Georg Brandlceee0772007-11-27 23:48:05 +00008864 if (!key || !value)
8865 goto err;
8866 res = PyDict_SetItem(new, key, value);
8867 Py_DECREF(key);
8868 Py_DECREF(value);
8869 if (res < 0)
8870 goto err;
8871 }
8872 /* create entries for deleting chars in z */
8873 if (z != NULL) {
8874 for (i = 0; i < PyUnicode_GET_SIZE(z); i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +00008875 key = PyLong_FromLong(PyUnicode_AS_UNICODE(z)[i]);
Georg Brandlceee0772007-11-27 23:48:05 +00008876 if (!key)
8877 goto err;
8878 res = PyDict_SetItem(new, key, Py_None);
8879 Py_DECREF(key);
8880 if (res < 0)
8881 goto err;
8882 }
8883 }
8884 } else {
8885 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +00008886 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +00008887 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
8888 "to maketrans it must be a dict");
8889 goto err;
8890 }
8891 /* copy entries into the new dict, converting string keys to int keys */
8892 while (PyDict_Next(x, &i, &key, &value)) {
8893 if (PyUnicode_Check(key)) {
8894 /* convert string keys to integer keys */
8895 PyObject *newkey;
8896 if (PyUnicode_GET_SIZE(key) != 1) {
8897 PyErr_SetString(PyExc_ValueError, "string keys in translate "
8898 "table must be of length 1");
8899 goto err;
8900 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008901 newkey = PyLong_FromLong(PyUnicode_AS_UNICODE(key)[0]);
Georg Brandlceee0772007-11-27 23:48:05 +00008902 if (!newkey)
8903 goto err;
8904 res = PyDict_SetItem(new, newkey, value);
8905 Py_DECREF(newkey);
8906 if (res < 0)
8907 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +00008908 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +00008909 /* just keep integer keys */
8910 if (PyDict_SetItem(new, key, value) < 0)
8911 goto err;
8912 } else {
8913 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
8914 "be strings or integers");
8915 goto err;
8916 }
8917 }
8918 }
8919 return new;
8920 err:
8921 Py_DECREF(new);
8922 return NULL;
8923}
8924
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008925PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008926 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008927\n\
8928Return a copy of the string S, where all characters have been mapped\n\
8929through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008930Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +00008931Unmapped characters are left untouched. Characters mapped to None\n\
8932are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008933
8934static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008935unicode_translate(PyUnicodeObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008936{
Georg Brandlceee0772007-11-27 23:48:05 +00008937 return PyUnicode_TranslateCharmap(self->str, self->length, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008938}
8939
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008940PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008941 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008942\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008943Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008944
8945static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008946unicode_upper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008947{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008948 return fixup(self, fixupper);
8949}
8950
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008951PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008952 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008953\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +00008954Pad a numeric string S with zeros on the left, to fill a field\n\
8955of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008956
8957static PyObject *
8958unicode_zfill(PyUnicodeObject *self, PyObject *args)
8959{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008960 Py_ssize_t fill;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008961 PyUnicodeObject *u;
8962
Martin v. Löwis18e16552006-02-15 17:27:45 +00008963 Py_ssize_t width;
8964 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008965 return NULL;
8966
8967 if (self->length >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +00008968 if (PyUnicode_CheckExact(self)) {
8969 Py_INCREF(self);
8970 return (PyObject*) self;
8971 }
8972 else
8973 return PyUnicode_FromUnicode(
8974 PyUnicode_AS_UNICODE(self),
8975 PyUnicode_GET_SIZE(self)
Benjamin Peterson29060642009-01-31 22:14:21 +00008976 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008977 }
8978
8979 fill = width - self->length;
8980
8981 u = pad(self, fill, 0, '0');
8982
Walter Dörwald068325e2002-04-15 13:36:47 +00008983 if (u == NULL)
8984 return NULL;
8985
Guido van Rossumd57fd912000-03-10 22:53:23 +00008986 if (u->str[fill] == '+' || u->str[fill] == '-') {
8987 /* move sign to beginning of string */
8988 u->str[0] = u->str[fill];
8989 u->str[fill] = '0';
8990 }
8991
8992 return (PyObject*) u;
8993}
Guido van Rossumd57fd912000-03-10 22:53:23 +00008994
8995#if 0
8996static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008997unicode_freelistsize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008998{
Christian Heimes2202f872008-02-06 14:31:34 +00008999 return PyLong_FromLong(numfree);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009000}
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009001
9002static PyObject *
9003unicode__decimal2ascii(PyObject *self)
9004{
9005 return PyUnicode_TransformDecimalToASCII(PyUnicode_AS_UNICODE(self),
9006 PyUnicode_GET_SIZE(self));
9007}
Guido van Rossumd57fd912000-03-10 22:53:23 +00009008#endif
9009
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009010PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009011 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009012\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00009013Return True if S starts with the specified prefix, False otherwise.\n\
9014With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009015With optional end, stop comparing S at that position.\n\
9016prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009017
9018static PyObject *
9019unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00009020 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009021{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009022 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009023 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009024 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009025 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009026 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009027
Jesus Ceaac451502011-04-20 17:09:23 +02009028 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +00009029 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009030 if (PyTuple_Check(subobj)) {
9031 Py_ssize_t i;
9032 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
9033 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +00009034 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009035 if (substring == NULL)
9036 return NULL;
9037 result = tailmatch(self, substring, start, end, -1);
9038 Py_DECREF(substring);
9039 if (result) {
9040 Py_RETURN_TRUE;
9041 }
9042 }
9043 /* nothing matched */
9044 Py_RETURN_FALSE;
9045 }
9046 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +03009047 if (substring == NULL) {
9048 if (PyErr_ExceptionMatches(PyExc_TypeError))
9049 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
9050 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +00009051 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03009052 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009053 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009054 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009055 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009056}
9057
9058
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009059PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009060 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009061\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00009062Return True if S ends with the specified suffix, False otherwise.\n\
9063With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009064With optional end, stop comparing S at that position.\n\
9065suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009066
9067static PyObject *
9068unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00009069 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009070{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009071 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009072 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009073 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009074 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009075 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009076
Jesus Ceaac451502011-04-20 17:09:23 +02009077 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +00009078 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009079 if (PyTuple_Check(subobj)) {
9080 Py_ssize_t i;
9081 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
9082 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +00009083 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009084 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009085 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009086 result = tailmatch(self, substring, start, end, +1);
9087 Py_DECREF(substring);
9088 if (result) {
9089 Py_RETURN_TRUE;
9090 }
9091 }
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, "endswith 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
Eric Smith8c663262007-08-25 02:26:07 +00009106#include "stringlib/string_format.h"
9107
9108PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009109 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +00009110\n\
Eric Smith51d2fd92010-11-06 19:27:37 +00009111Return a formatted version of S, using substitutions from args and kwargs.\n\
9112The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +00009113
Eric Smith27bbca62010-11-04 17:06:58 +00009114PyDoc_STRVAR(format_map__doc__,
9115 "S.format_map(mapping) -> str\n\
9116\n\
Eric Smith51d2fd92010-11-06 19:27:37 +00009117Return a formatted version of S, using substitutions from mapping.\n\
9118The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +00009119
Eric Smith4a7d76d2008-05-30 18:10:19 +00009120static PyObject *
9121unicode__format__(PyObject* self, PyObject* args)
9122{
9123 PyObject *format_spec;
9124
9125 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
9126 return NULL;
9127
9128 return _PyUnicode_FormatAdvanced(self,
9129 PyUnicode_AS_UNICODE(format_spec),
9130 PyUnicode_GET_SIZE(format_spec));
9131}
9132
Eric Smith8c663262007-08-25 02:26:07 +00009133PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009134 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +00009135\n\
Eric Smith51d2fd92010-11-06 19:27:37 +00009136Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +00009137
9138static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009139unicode__sizeof__(PyUnicodeObject *v)
9140{
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00009141 return PyLong_FromSsize_t(sizeof(PyUnicodeObject) +
9142 sizeof(Py_UNICODE) * (v->length + 1));
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009143}
9144
9145PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009146 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009147
9148static PyObject *
Guido van Rossum5d9113d2003-01-29 17:58:45 +00009149unicode_getnewargs(PyUnicodeObject *v)
9150{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009151 return Py_BuildValue("(u#)", v->str, v->length);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00009152}
9153
Guido van Rossumd57fd912000-03-10 22:53:23 +00009154static PyMethodDef unicode_methods[] = {
9155
9156 /* Order is according to common usage: often used methods should
9157 appear first, since lookup is done sequentially. */
9158
Benjamin Peterson28a4dce2010-12-12 01:33:04 +00009159 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009160 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
9161 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009162 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009163 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
9164 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
9165 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
9166 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
9167 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
9168 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
9169 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00009170 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009171 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
9172 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
9173 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00009174 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009175 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
9176 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
9177 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00009178 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00009179 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009180 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00009181 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009182 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
9183 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
9184 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
9185 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
9186 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
9187 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
9188 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
9189 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
9190 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
9191 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
9192 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
9193 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
9194 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
9195 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +00009196 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +00009197 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009198 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +00009199 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +00009200 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +00009201 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +00009202 {"maketrans", (PyCFunction) unicode_maketrans,
9203 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009204 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +00009205#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009206 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +00009207#endif
9208
9209#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009210 /* These methods are just used for debugging the implementation. */
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009211 {"freelistsize", (PyCFunction) unicode_freelistsize, METH_NOARGS},
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009212 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +00009213#endif
9214
Benjamin Peterson14339b62009-01-31 16:36:08 +00009215 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +00009216 {NULL, NULL}
9217};
9218
Neil Schemenauerce30bc92002-11-18 16:10:18 +00009219static PyObject *
9220unicode_mod(PyObject *v, PyObject *w)
9221{
Benjamin Peterson29060642009-01-31 22:14:21 +00009222 if (!PyUnicode_Check(v)) {
9223 Py_INCREF(Py_NotImplemented);
9224 return Py_NotImplemented;
9225 }
9226 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +00009227}
9228
9229static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009230 0, /*nb_add*/
9231 0, /*nb_subtract*/
9232 0, /*nb_multiply*/
9233 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +00009234};
9235
Guido van Rossumd57fd912000-03-10 22:53:23 +00009236static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009237 (lenfunc) unicode_length, /* sq_length */
9238 PyUnicode_Concat, /* sq_concat */
9239 (ssizeargfunc) unicode_repeat, /* sq_repeat */
9240 (ssizeargfunc) unicode_getitem, /* sq_item */
9241 0, /* sq_slice */
9242 0, /* sq_ass_item */
9243 0, /* sq_ass_slice */
9244 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009245};
9246
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009247static PyObject*
9248unicode_subscript(PyUnicodeObject* self, PyObject* item)
9249{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009250 if (PyIndex_Check(item)) {
9251 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009252 if (i == -1 && PyErr_Occurred())
9253 return NULL;
9254 if (i < 0)
Martin v. Löwisdea59e52006-01-05 10:00:36 +00009255 i += PyUnicode_GET_SIZE(self);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009256 return unicode_getitem(self, i);
9257 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00009258 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009259 Py_UNICODE* source_buf;
9260 Py_UNICODE* result_buf;
9261 PyObject* result;
9262
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00009263 if (PySlice_GetIndicesEx(item, PyUnicode_GET_SIZE(self),
Benjamin Peterson29060642009-01-31 22:14:21 +00009264 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009265 return NULL;
9266 }
9267
9268 if (slicelength <= 0) {
9269 return PyUnicode_FromUnicode(NULL, 0);
Thomas Woutersed03b412007-08-28 21:37:11 +00009270 } else if (start == 0 && step == 1 && slicelength == self->length &&
9271 PyUnicode_CheckExact(self)) {
9272 Py_INCREF(self);
9273 return (PyObject *)self;
9274 } else if (step == 1) {
9275 return PyUnicode_FromUnicode(self->str + start, slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009276 } else {
9277 source_buf = PyUnicode_AS_UNICODE((PyObject*)self);
Christian Heimesb186d002008-03-18 15:15:01 +00009278 result_buf = (Py_UNICODE *)PyObject_MALLOC(slicelength*
9279 sizeof(Py_UNICODE));
Benjamin Peterson14339b62009-01-31 16:36:08 +00009280
Benjamin Peterson29060642009-01-31 22:14:21 +00009281 if (result_buf == NULL)
9282 return PyErr_NoMemory();
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009283
9284 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
9285 result_buf[i] = source_buf[cur];
9286 }
Tim Petersced69f82003-09-16 20:30:58 +00009287
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009288 result = PyUnicode_FromUnicode(result_buf, slicelength);
Christian Heimesb186d002008-03-18 15:15:01 +00009289 PyObject_FREE(result_buf);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009290 return result;
9291 }
9292 } else {
9293 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
9294 return NULL;
9295 }
9296}
9297
9298static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009299 (lenfunc)unicode_length, /* mp_length */
9300 (binaryfunc)unicode_subscript, /* mp_subscript */
9301 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009302};
9303
Guido van Rossumd57fd912000-03-10 22:53:23 +00009304
Guido van Rossumd57fd912000-03-10 22:53:23 +00009305/* Helpers for PyUnicode_Format() */
9306
9307static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00009308getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009309{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009310 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009311 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009312 (*p_argidx)++;
9313 if (arglen < 0)
9314 return args;
9315 else
9316 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009317 }
9318 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009319 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009320 return NULL;
9321}
9322
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009323/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009324
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009325static PyObject *
9326formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009327{
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009328 char *p;
9329 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009330 double x;
Tim Petersced69f82003-09-16 20:30:58 +00009331
Guido van Rossumd57fd912000-03-10 22:53:23 +00009332 x = PyFloat_AsDouble(v);
9333 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009334 return NULL;
9335
Guido van Rossumd57fd912000-03-10 22:53:23 +00009336 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009337 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +00009338
Eric Smith0923d1d2009-04-16 20:16:10 +00009339 p = PyOS_double_to_string(x, type, prec,
9340 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009341 if (p == NULL)
9342 return NULL;
9343 result = PyUnicode_FromStringAndSize(p, strlen(p));
Eric Smith0923d1d2009-04-16 20:16:10 +00009344 PyMem_Free(p);
9345 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009346}
9347
Tim Peters38fd5b62000-09-21 05:43:11 +00009348static PyObject*
9349formatlong(PyObject *val, int flags, int prec, int type)
9350{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009351 char *buf;
9352 int len;
9353 PyObject *str; /* temporary string object. */
9354 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +00009355
Benjamin Peterson14339b62009-01-31 16:36:08 +00009356 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
9357 if (!str)
9358 return NULL;
9359 result = PyUnicode_FromStringAndSize(buf, len);
9360 Py_DECREF(str);
9361 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +00009362}
9363
Guido van Rossumd57fd912000-03-10 22:53:23 +00009364static int
9365formatchar(Py_UNICODE *buf,
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009366 size_t buflen,
9367 PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009368{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00009369 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009370 if (PyUnicode_Check(v)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009371 if (PyUnicode_GET_SIZE(v) == 1) {
9372 buf[0] = PyUnicode_AS_UNICODE(v)[0];
9373 buf[1] = '\0';
9374 return 1;
9375 }
9376#ifndef Py_UNICODE_WIDE
9377 if (PyUnicode_GET_SIZE(v) == 2) {
9378 /* Decode a valid surrogate pair */
9379 int c0 = PyUnicode_AS_UNICODE(v)[0];
9380 int c1 = PyUnicode_AS_UNICODE(v)[1];
9381 if (0xD800 <= c0 && c0 <= 0xDBFF &&
9382 0xDC00 <= c1 && c1 <= 0xDFFF) {
9383 buf[0] = c0;
9384 buf[1] = c1;
9385 buf[2] = '\0';
9386 return 2;
9387 }
9388 }
9389#endif
9390 goto onError;
9391 }
9392 else {
9393 /* Integer input truncated to a character */
9394 long x;
9395 x = PyLong_AsLong(v);
9396 if (x == -1 && PyErr_Occurred())
9397 goto onError;
9398
9399 if (x < 0 || x > 0x10ffff) {
9400 PyErr_SetString(PyExc_OverflowError,
9401 "%c arg not in range(0x110000)");
9402 return -1;
9403 }
9404
9405#ifndef Py_UNICODE_WIDE
9406 if (x > 0xffff) {
9407 x -= 0x10000;
9408 buf[0] = (Py_UNICODE)(0xD800 | (x >> 10));
9409 buf[1] = (Py_UNICODE)(0xDC00 | (x & 0x3FF));
9410 return 2;
9411 }
9412#endif
9413 buf[0] = (Py_UNICODE) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009414 buf[1] = '\0';
9415 return 1;
9416 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00009417
Benjamin Peterson29060642009-01-31 22:14:21 +00009418 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009419 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009420 "%c requires int or char");
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009421 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009422}
9423
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009424/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009425 FORMATBUFLEN is the length of the buffer in which chars are formatted.
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009426*/
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009427#define FORMATBUFLEN (size_t)10
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009428
Guido van Rossumd57fd912000-03-10 22:53:23 +00009429PyObject *PyUnicode_Format(PyObject *format,
Benjamin Peterson29060642009-01-31 22:14:21 +00009430 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009431{
9432 Py_UNICODE *fmt, *res;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009433 Py_ssize_t fmtcnt, rescnt, reslen, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009434 int args_owned = 0;
9435 PyUnicodeObject *result = NULL;
9436 PyObject *dict = NULL;
9437 PyObject *uformat;
Tim Petersced69f82003-09-16 20:30:58 +00009438
Guido van Rossumd57fd912000-03-10 22:53:23 +00009439 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009440 PyErr_BadInternalCall();
9441 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009442 }
9443 uformat = PyUnicode_FromObject(format);
Fred Drakee4315f52000-05-09 19:53:39 +00009444 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009445 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009446 fmt = PyUnicode_AS_UNICODE(uformat);
9447 fmtcnt = PyUnicode_GET_SIZE(uformat);
9448
9449 reslen = rescnt = fmtcnt + 100;
9450 result = _PyUnicode_New(reslen);
9451 if (result == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009452 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009453 res = PyUnicode_AS_UNICODE(result);
9454
9455 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009456 arglen = PyTuple_Size(args);
9457 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009458 }
9459 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009460 arglen = -1;
9461 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009462 }
Christian Heimes90aa7642007-12-19 02:45:37 +00009463 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +00009464 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +00009465 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009466
9467 while (--fmtcnt >= 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009468 if (*fmt != '%') {
9469 if (--rescnt < 0) {
9470 rescnt = fmtcnt + 100;
9471 reslen += rescnt;
9472 if (_PyUnicode_Resize(&result, reslen) < 0)
9473 goto onError;
9474 res = PyUnicode_AS_UNICODE(result) + reslen - rescnt;
9475 --rescnt;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009476 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009477 *res++ = *fmt++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009478 }
9479 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009480 /* Got a format specifier */
9481 int flags = 0;
9482 Py_ssize_t width = -1;
9483 int prec = -1;
9484 Py_UNICODE c = '\0';
9485 Py_UNICODE fill;
9486 int isnumok;
9487 PyObject *v = NULL;
9488 PyObject *temp = NULL;
9489 Py_UNICODE *pbuf;
9490 Py_UNICODE sign;
9491 Py_ssize_t len;
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009492 Py_UNICODE formatbuf[FORMATBUFLEN]; /* For formatchar() */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009493
Benjamin Peterson29060642009-01-31 22:14:21 +00009494 fmt++;
9495 if (*fmt == '(') {
9496 Py_UNICODE *keystart;
9497 Py_ssize_t keylen;
9498 PyObject *key;
9499 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +00009500
Benjamin Peterson29060642009-01-31 22:14:21 +00009501 if (dict == NULL) {
9502 PyErr_SetString(PyExc_TypeError,
9503 "format requires a mapping");
9504 goto onError;
9505 }
9506 ++fmt;
9507 --fmtcnt;
9508 keystart = fmt;
9509 /* Skip over balanced parentheses */
9510 while (pcount > 0 && --fmtcnt >= 0) {
9511 if (*fmt == ')')
9512 --pcount;
9513 else if (*fmt == '(')
9514 ++pcount;
9515 fmt++;
9516 }
9517 keylen = fmt - keystart - 1;
9518 if (fmtcnt < 0 || pcount > 0) {
9519 PyErr_SetString(PyExc_ValueError,
9520 "incomplete format key");
9521 goto onError;
9522 }
9523#if 0
9524 /* keys are converted to strings using UTF-8 and
9525 then looked up since Python uses strings to hold
9526 variables names etc. in its namespaces and we
9527 wouldn't want to break common idioms. */
9528 key = PyUnicode_EncodeUTF8(keystart,
9529 keylen,
9530 NULL);
9531#else
9532 key = PyUnicode_FromUnicode(keystart, keylen);
9533#endif
9534 if (key == NULL)
9535 goto onError;
9536 if (args_owned) {
9537 Py_DECREF(args);
9538 args_owned = 0;
9539 }
9540 args = PyObject_GetItem(dict, key);
9541 Py_DECREF(key);
9542 if (args == NULL) {
9543 goto onError;
9544 }
9545 args_owned = 1;
9546 arglen = -1;
9547 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009548 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009549 while (--fmtcnt >= 0) {
9550 switch (c = *fmt++) {
9551 case '-': flags |= F_LJUST; continue;
9552 case '+': flags |= F_SIGN; continue;
9553 case ' ': flags |= F_BLANK; continue;
9554 case '#': flags |= F_ALT; continue;
9555 case '0': flags |= F_ZERO; continue;
9556 }
9557 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009558 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009559 if (c == '*') {
9560 v = getnextarg(args, arglen, &argidx);
9561 if (v == NULL)
9562 goto onError;
9563 if (!PyLong_Check(v)) {
9564 PyErr_SetString(PyExc_TypeError,
9565 "* wants int");
9566 goto onError;
9567 }
9568 width = PyLong_AsLong(v);
9569 if (width == -1 && PyErr_Occurred())
9570 goto onError;
9571 if (width < 0) {
9572 flags |= F_LJUST;
9573 width = -width;
9574 }
9575 if (--fmtcnt >= 0)
9576 c = *fmt++;
9577 }
9578 else if (c >= '0' && c <= '9') {
9579 width = c - '0';
9580 while (--fmtcnt >= 0) {
9581 c = *fmt++;
9582 if (c < '0' || c > '9')
9583 break;
9584 if ((width*10) / 10 != width) {
9585 PyErr_SetString(PyExc_ValueError,
9586 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009587 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00009588 }
9589 width = width*10 + (c - '0');
9590 }
9591 }
9592 if (c == '.') {
9593 prec = 0;
9594 if (--fmtcnt >= 0)
9595 c = *fmt++;
9596 if (c == '*') {
9597 v = getnextarg(args, arglen, &argidx);
9598 if (v == NULL)
9599 goto onError;
9600 if (!PyLong_Check(v)) {
9601 PyErr_SetString(PyExc_TypeError,
9602 "* wants int");
9603 goto onError;
9604 }
9605 prec = PyLong_AsLong(v);
9606 if (prec == -1 && PyErr_Occurred())
9607 goto onError;
9608 if (prec < 0)
9609 prec = 0;
9610 if (--fmtcnt >= 0)
9611 c = *fmt++;
9612 }
9613 else if (c >= '0' && c <= '9') {
9614 prec = c - '0';
9615 while (--fmtcnt >= 0) {
Stefan Krah99212f62010-07-19 17:58:26 +00009616 c = *fmt++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009617 if (c < '0' || c > '9')
9618 break;
9619 if ((prec*10) / 10 != prec) {
9620 PyErr_SetString(PyExc_ValueError,
9621 "prec too big");
9622 goto onError;
9623 }
9624 prec = prec*10 + (c - '0');
9625 }
9626 }
9627 } /* prec */
9628 if (fmtcnt >= 0) {
9629 if (c == 'h' || c == 'l' || c == 'L') {
9630 if (--fmtcnt >= 0)
9631 c = *fmt++;
9632 }
9633 }
9634 if (fmtcnt < 0) {
9635 PyErr_SetString(PyExc_ValueError,
9636 "incomplete format");
9637 goto onError;
9638 }
9639 if (c != '%') {
9640 v = getnextarg(args, arglen, &argidx);
9641 if (v == NULL)
9642 goto onError;
9643 }
9644 sign = 0;
9645 fill = ' ';
9646 switch (c) {
9647
9648 case '%':
9649 pbuf = formatbuf;
9650 /* presume that buffer length is at least 1 */
9651 pbuf[0] = '%';
9652 len = 1;
9653 break;
9654
9655 case 's':
9656 case 'r':
9657 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +00009658 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +00009659 temp = v;
9660 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009661 }
9662 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009663 if (c == 's')
9664 temp = PyObject_Str(v);
9665 else if (c == 'r')
9666 temp = PyObject_Repr(v);
9667 else
9668 temp = PyObject_ASCII(v);
9669 if (temp == NULL)
9670 goto onError;
9671 if (PyUnicode_Check(temp))
9672 /* nothing to do */;
9673 else {
9674 Py_DECREF(temp);
9675 PyErr_SetString(PyExc_TypeError,
9676 "%s argument has non-string str()");
9677 goto onError;
9678 }
9679 }
9680 pbuf = PyUnicode_AS_UNICODE(temp);
9681 len = PyUnicode_GET_SIZE(temp);
9682 if (prec >= 0 && len > prec)
9683 len = prec;
9684 break;
9685
9686 case 'i':
9687 case 'd':
9688 case 'u':
9689 case 'o':
9690 case 'x':
9691 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +00009692 isnumok = 0;
9693 if (PyNumber_Check(v)) {
9694 PyObject *iobj=NULL;
9695
9696 if (PyLong_Check(v)) {
9697 iobj = v;
9698 Py_INCREF(iobj);
9699 }
9700 else {
9701 iobj = PyNumber_Long(v);
9702 }
9703 if (iobj!=NULL) {
9704 if (PyLong_Check(iobj)) {
9705 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -07009706 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +00009707 Py_DECREF(iobj);
9708 if (!temp)
9709 goto onError;
9710 pbuf = PyUnicode_AS_UNICODE(temp);
9711 len = PyUnicode_GET_SIZE(temp);
9712 sign = 1;
9713 }
9714 else {
9715 Py_DECREF(iobj);
9716 }
9717 }
9718 }
9719 if (!isnumok) {
9720 PyErr_Format(PyExc_TypeError,
9721 "%%%c format: a number is required, "
9722 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
9723 goto onError;
9724 }
9725 if (flags & F_ZERO)
9726 fill = '0';
9727 break;
9728
9729 case 'e':
9730 case 'E':
9731 case 'f':
9732 case 'F':
9733 case 'g':
9734 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009735 temp = formatfloat(v, flags, prec, c);
9736 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +00009737 goto onError;
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009738 pbuf = PyUnicode_AS_UNICODE(temp);
9739 len = PyUnicode_GET_SIZE(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +00009740 sign = 1;
9741 if (flags & F_ZERO)
9742 fill = '0';
9743 break;
9744
9745 case 'c':
9746 pbuf = formatbuf;
9747 len = formatchar(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), v);
9748 if (len < 0)
9749 goto onError;
9750 break;
9751
9752 default:
9753 PyErr_Format(PyExc_ValueError,
9754 "unsupported format character '%c' (0x%x) "
9755 "at index %zd",
9756 (31<=c && c<=126) ? (char)c : '?',
9757 (int)c,
9758 (Py_ssize_t)(fmt - 1 -
9759 PyUnicode_AS_UNICODE(uformat)));
9760 goto onError;
9761 }
9762 if (sign) {
9763 if (*pbuf == '-' || *pbuf == '+') {
9764 sign = *pbuf++;
9765 len--;
9766 }
9767 else if (flags & F_SIGN)
9768 sign = '+';
9769 else if (flags & F_BLANK)
9770 sign = ' ';
9771 else
9772 sign = 0;
9773 }
9774 if (width < len)
9775 width = len;
9776 if (rescnt - (sign != 0) < width) {
9777 reslen -= rescnt;
9778 rescnt = width + fmtcnt + 100;
9779 reslen += rescnt;
9780 if (reslen < 0) {
9781 Py_XDECREF(temp);
9782 PyErr_NoMemory();
9783 goto onError;
9784 }
9785 if (_PyUnicode_Resize(&result, reslen) < 0) {
9786 Py_XDECREF(temp);
9787 goto onError;
9788 }
9789 res = PyUnicode_AS_UNICODE(result)
9790 + reslen - rescnt;
9791 }
9792 if (sign) {
9793 if (fill != ' ')
9794 *res++ = sign;
9795 rescnt--;
9796 if (width > len)
9797 width--;
9798 }
9799 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
9800 assert(pbuf[0] == '0');
9801 assert(pbuf[1] == c);
9802 if (fill != ' ') {
9803 *res++ = *pbuf++;
9804 *res++ = *pbuf++;
9805 }
9806 rescnt -= 2;
9807 width -= 2;
9808 if (width < 0)
9809 width = 0;
9810 len -= 2;
9811 }
9812 if (width > len && !(flags & F_LJUST)) {
9813 do {
9814 --rescnt;
9815 *res++ = fill;
9816 } while (--width > len);
9817 }
9818 if (fill == ' ') {
9819 if (sign)
9820 *res++ = sign;
9821 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
9822 assert(pbuf[0] == '0');
9823 assert(pbuf[1] == c);
9824 *res++ = *pbuf++;
9825 *res++ = *pbuf++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009826 }
9827 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009828 Py_UNICODE_COPY(res, pbuf, len);
9829 res += len;
9830 rescnt -= len;
9831 while (--width >= len) {
9832 --rescnt;
9833 *res++ = ' ';
9834 }
9835 if (dict && (argidx < arglen) && c != '%') {
9836 PyErr_SetString(PyExc_TypeError,
9837 "not all arguments converted during string formatting");
Thomas Woutersa96affe2006-03-12 00:29:36 +00009838 Py_XDECREF(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +00009839 goto onError;
9840 }
9841 Py_XDECREF(temp);
9842 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009843 } /* until end */
9844 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009845 PyErr_SetString(PyExc_TypeError,
9846 "not all arguments converted during string formatting");
9847 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009848 }
9849
Thomas Woutersa96affe2006-03-12 00:29:36 +00009850 if (_PyUnicode_Resize(&result, reslen - rescnt) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009851 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009852 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009853 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009854 }
9855 Py_DECREF(uformat);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009856 return (PyObject *)result;
9857
Benjamin Peterson29060642009-01-31 22:14:21 +00009858 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009859 Py_XDECREF(result);
9860 Py_DECREF(uformat);
9861 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009862 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009863 }
9864 return NULL;
9865}
9866
Jeremy Hylton938ace62002-07-17 16:30:39 +00009867static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +00009868unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
9869
Tim Peters6d6c1a32001-08-02 04:15:00 +00009870static PyObject *
9871unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9872{
Benjamin Peterson29060642009-01-31 22:14:21 +00009873 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009874 static char *kwlist[] = {"object", "encoding", "errors", 0};
9875 char *encoding = NULL;
9876 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00009877
Benjamin Peterson14339b62009-01-31 16:36:08 +00009878 if (type != &PyUnicode_Type)
9879 return unicode_subtype_new(type, args, kwds);
9880 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +00009881 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009882 return NULL;
9883 if (x == NULL)
9884 return (PyObject *)_PyUnicode_New(0);
9885 if (encoding == NULL && errors == NULL)
9886 return PyObject_Str(x);
9887 else
Benjamin Peterson29060642009-01-31 22:14:21 +00009888 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +00009889}
9890
Guido van Rossume023fe02001-08-30 03:12:59 +00009891static PyObject *
9892unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9893{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009894 PyUnicodeObject *tmp, *pnew;
9895 Py_ssize_t n;
Guido van Rossume023fe02001-08-30 03:12:59 +00009896
Benjamin Peterson14339b62009-01-31 16:36:08 +00009897 assert(PyType_IsSubtype(type, &PyUnicode_Type));
9898 tmp = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
9899 if (tmp == NULL)
9900 return NULL;
9901 assert(PyUnicode_Check(tmp));
9902 pnew = (PyUnicodeObject *) type->tp_alloc(type, n = tmp->length);
9903 if (pnew == NULL) {
9904 Py_DECREF(tmp);
9905 return NULL;
9906 }
9907 pnew->str = (Py_UNICODE*) PyObject_MALLOC(sizeof(Py_UNICODE) * (n+1));
9908 if (pnew->str == NULL) {
9909 _Py_ForgetReference((PyObject *)pnew);
9910 PyObject_Del(pnew);
9911 Py_DECREF(tmp);
9912 return PyErr_NoMemory();
9913 }
9914 Py_UNICODE_COPY(pnew->str, tmp->str, n+1);
9915 pnew->length = n;
9916 pnew->hash = tmp->hash;
9917 Py_DECREF(tmp);
9918 return (PyObject *)pnew;
Guido van Rossume023fe02001-08-30 03:12:59 +00009919}
9920
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009921PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +00009922 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00009923\n\
Collin Winterd474ce82007-08-07 19:42:11 +00009924Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +00009925encoding defaults to the current default string encoding.\n\
9926errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00009927
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009928static PyObject *unicode_iter(PyObject *seq);
9929
Guido van Rossumd57fd912000-03-10 22:53:23 +00009930PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00009931 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +00009932 "str", /* tp_name */
9933 sizeof(PyUnicodeObject), /* tp_size */
9934 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009935 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009936 (destructor)unicode_dealloc, /* tp_dealloc */
9937 0, /* tp_print */
9938 0, /* tp_getattr */
9939 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00009940 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009941 unicode_repr, /* tp_repr */
9942 &unicode_as_number, /* tp_as_number */
9943 &unicode_as_sequence, /* tp_as_sequence */
9944 &unicode_as_mapping, /* tp_as_mapping */
9945 (hashfunc) unicode_hash, /* tp_hash*/
9946 0, /* tp_call*/
9947 (reprfunc) unicode_str, /* tp_str */
9948 PyObject_GenericGetAttr, /* tp_getattro */
9949 0, /* tp_setattro */
9950 0, /* tp_as_buffer */
9951 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +00009952 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009953 unicode_doc, /* tp_doc */
9954 0, /* tp_traverse */
9955 0, /* tp_clear */
9956 PyUnicode_RichCompare, /* tp_richcompare */
9957 0, /* tp_weaklistoffset */
9958 unicode_iter, /* tp_iter */
9959 0, /* tp_iternext */
9960 unicode_methods, /* tp_methods */
9961 0, /* tp_members */
9962 0, /* tp_getset */
9963 &PyBaseObject_Type, /* tp_base */
9964 0, /* tp_dict */
9965 0, /* tp_descr_get */
9966 0, /* tp_descr_set */
9967 0, /* tp_dictoffset */
9968 0, /* tp_init */
9969 0, /* tp_alloc */
9970 unicode_new, /* tp_new */
9971 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009972};
9973
9974/* Initialize the Unicode implementation */
9975
Thomas Wouters78890102000-07-22 19:25:51 +00009976void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009977{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009978 int i;
9979
Thomas Wouters477c8d52006-05-27 19:21:47 +00009980 /* XXX - move this array to unicodectype.c ? */
9981 Py_UNICODE linebreak[] = {
9982 0x000A, /* LINE FEED */
9983 0x000D, /* CARRIAGE RETURN */
9984 0x001C, /* FILE SEPARATOR */
9985 0x001D, /* GROUP SEPARATOR */
9986 0x001E, /* RECORD SEPARATOR */
9987 0x0085, /* NEXT LINE */
9988 0x2028, /* LINE SEPARATOR */
9989 0x2029, /* PARAGRAPH SEPARATOR */
9990 };
9991
Fred Drakee4315f52000-05-09 19:53:39 +00009992 /* Init the implementation */
Christian Heimes2202f872008-02-06 14:31:34 +00009993 free_list = NULL;
9994 numfree = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009995 unicode_empty = _PyUnicode_New(0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009996 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00009997 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009998
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009999 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000010000 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000010001 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010002 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000010003
10004 /* initialize the linebreak bloom filter */
10005 bloom_linebreak = make_bloom_mask(
10006 linebreak, sizeof(linebreak) / sizeof(linebreak[0])
10007 );
Thomas Wouters0e3f5912006-08-11 14:57:12 +000010008
10009 PyType_Ready(&EncodingMapType);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010010}
10011
10012/* Finalize the Unicode implementation */
10013
Christian Heimesa156e092008-02-16 07:38:31 +000010014int
10015PyUnicode_ClearFreeList(void)
10016{
10017 int freelist_size = numfree;
10018 PyUnicodeObject *u;
10019
10020 for (u = free_list; u != NULL;) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010021 PyUnicodeObject *v = u;
10022 u = *(PyUnicodeObject **)u;
10023 if (v->str)
10024 PyObject_DEL(v->str);
10025 Py_XDECREF(v->defenc);
10026 PyObject_Del(v);
10027 numfree--;
Christian Heimesa156e092008-02-16 07:38:31 +000010028 }
10029 free_list = NULL;
10030 assert(numfree == 0);
10031 return freelist_size;
10032}
10033
Guido van Rossumd57fd912000-03-10 22:53:23 +000010034void
Thomas Wouters78890102000-07-22 19:25:51 +000010035_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010036{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000010037 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010038
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000010039 Py_XDECREF(unicode_empty);
10040 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000010041
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000010042 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010043 if (unicode_latin1[i]) {
10044 Py_DECREF(unicode_latin1[i]);
10045 unicode_latin1[i] = NULL;
10046 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000010047 }
Christian Heimesa156e092008-02-16 07:38:31 +000010048 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000010049}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000010050
Walter Dörwald16807132007-05-25 13:52:07 +000010051void
10052PyUnicode_InternInPlace(PyObject **p)
10053{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010054 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
10055 PyObject *t;
10056 if (s == NULL || !PyUnicode_Check(s))
10057 Py_FatalError(
10058 "PyUnicode_InternInPlace: unicode strings only please!");
10059 /* If it's a subclass, we don't really know what putting
10060 it in the interned dict might do. */
10061 if (!PyUnicode_CheckExact(s))
10062 return;
10063 if (PyUnicode_CHECK_INTERNED(s))
10064 return;
10065 if (interned == NULL) {
10066 interned = PyDict_New();
10067 if (interned == NULL) {
10068 PyErr_Clear(); /* Don't leave an exception */
10069 return;
10070 }
10071 }
10072 /* It might be that the GetItem call fails even
10073 though the key is present in the dictionary,
10074 namely when this happens during a stack overflow. */
10075 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000010076 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010077 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000010078
Benjamin Peterson29060642009-01-31 22:14:21 +000010079 if (t) {
10080 Py_INCREF(t);
10081 Py_DECREF(*p);
10082 *p = t;
10083 return;
10084 }
Walter Dörwald16807132007-05-25 13:52:07 +000010085
Benjamin Peterson14339b62009-01-31 16:36:08 +000010086 PyThreadState_GET()->recursion_critical = 1;
10087 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
10088 PyErr_Clear();
10089 PyThreadState_GET()->recursion_critical = 0;
10090 return;
10091 }
10092 PyThreadState_GET()->recursion_critical = 0;
10093 /* The two references in interned are not counted by refcnt.
10094 The deallocator will take care of this */
10095 Py_REFCNT(s) -= 2;
10096 PyUnicode_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000010097}
10098
10099void
10100PyUnicode_InternImmortal(PyObject **p)
10101{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010102 PyUnicode_InternInPlace(p);
10103 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
10104 PyUnicode_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
10105 Py_INCREF(*p);
10106 }
Walter Dörwald16807132007-05-25 13:52:07 +000010107}
10108
10109PyObject *
10110PyUnicode_InternFromString(const char *cp)
10111{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010112 PyObject *s = PyUnicode_FromString(cp);
10113 if (s == NULL)
10114 return NULL;
10115 PyUnicode_InternInPlace(&s);
10116 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000010117}
10118
10119void _Py_ReleaseInternedUnicodeStrings(void)
10120{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010121 PyObject *keys;
10122 PyUnicodeObject *s;
10123 Py_ssize_t i, n;
10124 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000010125
Benjamin Peterson14339b62009-01-31 16:36:08 +000010126 if (interned == NULL || !PyDict_Check(interned))
10127 return;
10128 keys = PyDict_Keys(interned);
10129 if (keys == NULL || !PyList_Check(keys)) {
10130 PyErr_Clear();
10131 return;
10132 }
Walter Dörwald16807132007-05-25 13:52:07 +000010133
Benjamin Peterson14339b62009-01-31 16:36:08 +000010134 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
10135 detector, interned unicode strings are not forcibly deallocated;
10136 rather, we give them their stolen references back, and then clear
10137 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000010138
Benjamin Peterson14339b62009-01-31 16:36:08 +000010139 n = PyList_GET_SIZE(keys);
10140 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000010141 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010142 for (i = 0; i < n; i++) {
10143 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
10144 switch (s->state) {
10145 case SSTATE_NOT_INTERNED:
10146 /* XXX Shouldn't happen */
10147 break;
10148 case SSTATE_INTERNED_IMMORTAL:
10149 Py_REFCNT(s) += 1;
10150 immortal_size += s->length;
10151 break;
10152 case SSTATE_INTERNED_MORTAL:
10153 Py_REFCNT(s) += 2;
10154 mortal_size += s->length;
10155 break;
10156 default:
10157 Py_FatalError("Inconsistent interned string state.");
10158 }
10159 s->state = SSTATE_NOT_INTERNED;
10160 }
10161 fprintf(stderr, "total size of all interned strings: "
10162 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
10163 "mortal/immortal\n", mortal_size, immortal_size);
10164 Py_DECREF(keys);
10165 PyDict_Clear(interned);
10166 Py_DECREF(interned);
10167 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000010168}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010169
10170
10171/********************* Unicode Iterator **************************/
10172
10173typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010174 PyObject_HEAD
10175 Py_ssize_t it_index;
10176 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010177} unicodeiterobject;
10178
10179static void
10180unicodeiter_dealloc(unicodeiterobject *it)
10181{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010182 _PyObject_GC_UNTRACK(it);
10183 Py_XDECREF(it->it_seq);
10184 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010185}
10186
10187static int
10188unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
10189{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010190 Py_VISIT(it->it_seq);
10191 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010192}
10193
10194static PyObject *
10195unicodeiter_next(unicodeiterobject *it)
10196{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010197 PyUnicodeObject *seq;
10198 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010199
Benjamin Peterson14339b62009-01-31 16:36:08 +000010200 assert(it != NULL);
10201 seq = it->it_seq;
10202 if (seq == NULL)
10203 return NULL;
10204 assert(PyUnicode_Check(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010205
Benjamin Peterson14339b62009-01-31 16:36:08 +000010206 if (it->it_index < PyUnicode_GET_SIZE(seq)) {
10207 item = PyUnicode_FromUnicode(
Benjamin Peterson29060642009-01-31 22:14:21 +000010208 PyUnicode_AS_UNICODE(seq)+it->it_index, 1);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010209 if (item != NULL)
10210 ++it->it_index;
10211 return item;
10212 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010213
Benjamin Peterson14339b62009-01-31 16:36:08 +000010214 Py_DECREF(seq);
10215 it->it_seq = NULL;
10216 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010217}
10218
10219static PyObject *
10220unicodeiter_len(unicodeiterobject *it)
10221{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010222 Py_ssize_t len = 0;
10223 if (it->it_seq)
10224 len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index;
10225 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010226}
10227
10228PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
10229
10230static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010231 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000010232 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000010233 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010234};
10235
10236PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010237 PyVarObject_HEAD_INIT(&PyType_Type, 0)
10238 "str_iterator", /* tp_name */
10239 sizeof(unicodeiterobject), /* tp_basicsize */
10240 0, /* tp_itemsize */
10241 /* methods */
10242 (destructor)unicodeiter_dealloc, /* tp_dealloc */
10243 0, /* tp_print */
10244 0, /* tp_getattr */
10245 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000010246 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000010247 0, /* tp_repr */
10248 0, /* tp_as_number */
10249 0, /* tp_as_sequence */
10250 0, /* tp_as_mapping */
10251 0, /* tp_hash */
10252 0, /* tp_call */
10253 0, /* tp_str */
10254 PyObject_GenericGetAttr, /* tp_getattro */
10255 0, /* tp_setattro */
10256 0, /* tp_as_buffer */
10257 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
10258 0, /* tp_doc */
10259 (traverseproc)unicodeiter_traverse, /* tp_traverse */
10260 0, /* tp_clear */
10261 0, /* tp_richcompare */
10262 0, /* tp_weaklistoffset */
10263 PyObject_SelfIter, /* tp_iter */
10264 (iternextfunc)unicodeiter_next, /* tp_iternext */
10265 unicodeiter_methods, /* tp_methods */
10266 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010267};
10268
10269static PyObject *
10270unicode_iter(PyObject *seq)
10271{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010272 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010273
Benjamin Peterson14339b62009-01-31 16:36:08 +000010274 if (!PyUnicode_Check(seq)) {
10275 PyErr_BadInternalCall();
10276 return NULL;
10277 }
10278 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
10279 if (it == NULL)
10280 return NULL;
10281 it->it_index = 0;
10282 Py_INCREF(seq);
10283 it->it_seq = (PyUnicodeObject *)seq;
10284 _PyObject_GC_TRACK(it);
10285 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010286}
10287
Martin v. Löwis5b222132007-06-10 09:51:05 +000010288size_t
10289Py_UNICODE_strlen(const Py_UNICODE *u)
10290{
10291 int res = 0;
10292 while(*u++)
10293 res++;
10294 return res;
10295}
10296
10297Py_UNICODE*
10298Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
10299{
10300 Py_UNICODE *u = s1;
10301 while ((*u++ = *s2++));
10302 return s1;
10303}
10304
10305Py_UNICODE*
10306Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
10307{
10308 Py_UNICODE *u = s1;
10309 while ((*u++ = *s2++))
10310 if (n-- == 0)
10311 break;
10312 return s1;
10313}
10314
Victor Stinnerc4eb7652010-09-01 23:43:50 +000010315Py_UNICODE*
10316Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
10317{
10318 Py_UNICODE *u1 = s1;
10319 u1 += Py_UNICODE_strlen(u1);
10320 Py_UNICODE_strcpy(u1, s2);
10321 return s1;
10322}
10323
Martin v. Löwis5b222132007-06-10 09:51:05 +000010324int
10325Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
10326{
10327 while (*s1 && *s2 && *s1 == *s2)
10328 s1++, s2++;
10329 if (*s1 && *s2)
10330 return (*s1 < *s2) ? -1 : +1;
10331 if (*s1)
10332 return 1;
10333 if (*s2)
10334 return -1;
10335 return 0;
10336}
10337
Victor Stinneref8d95c2010-08-16 22:03:11 +000010338int
10339Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
10340{
10341 register Py_UNICODE u1, u2;
10342 for (; n != 0; n--) {
10343 u1 = *s1;
10344 u2 = *s2;
10345 if (u1 != u2)
10346 return (u1 < u2) ? -1 : +1;
10347 if (u1 == '\0')
10348 return 0;
10349 s1++;
10350 s2++;
10351 }
10352 return 0;
10353}
10354
Martin v. Löwis5b222132007-06-10 09:51:05 +000010355Py_UNICODE*
10356Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
10357{
10358 const Py_UNICODE *p;
10359 for (p = s; *p; p++)
10360 if (*p == c)
10361 return (Py_UNICODE*)p;
10362 return NULL;
10363}
10364
Victor Stinner331ea922010-08-10 16:37:20 +000010365Py_UNICODE*
10366Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
10367{
10368 const Py_UNICODE *p;
10369 p = s + Py_UNICODE_strlen(s);
10370 while (p != s) {
10371 p--;
10372 if (*p == c)
10373 return (Py_UNICODE*)p;
10374 }
10375 return NULL;
10376}
10377
Victor Stinner71133ff2010-09-01 23:43:53 +000010378Py_UNICODE*
Victor Stinner46408602010-09-03 16:18:00 +000010379PyUnicode_AsUnicodeCopy(PyObject *object)
Victor Stinner71133ff2010-09-01 23:43:53 +000010380{
10381 PyUnicodeObject *unicode = (PyUnicodeObject *)object;
10382 Py_UNICODE *copy;
10383 Py_ssize_t size;
10384
10385 /* Ensure we won't overflow the size. */
10386 if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
10387 PyErr_NoMemory();
10388 return NULL;
10389 }
10390 size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
10391 size *= sizeof(Py_UNICODE);
10392 copy = PyMem_Malloc(size);
10393 if (copy == NULL) {
10394 PyErr_NoMemory();
10395 return NULL;
10396 }
10397 memcpy(copy, PyUnicode_AS_UNICODE(unicode), size);
10398 return copy;
10399}
Martin v. Löwis5b222132007-06-10 09:51:05 +000010400
Georg Brandl66c221e2010-10-14 07:04:07 +000010401/* A _string module, to export formatter_parser and formatter_field_name_split
10402 to the string.Formatter class implemented in Python. */
10403
10404static PyMethodDef _string_methods[] = {
10405 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
10406 METH_O, PyDoc_STR("split the argument as a field name")},
10407 {"formatter_parser", (PyCFunction) formatter_parser,
10408 METH_O, PyDoc_STR("parse the argument as a format string")},
10409 {NULL, NULL}
10410};
10411
10412static struct PyModuleDef _string_module = {
10413 PyModuleDef_HEAD_INIT,
10414 "_string",
10415 PyDoc_STR("string helper module"),
10416 0,
10417 _string_methods,
10418 NULL,
10419 NULL,
10420 NULL,
10421 NULL
10422};
10423
10424PyMODINIT_FUNC
10425PyInit__string(void)
10426{
10427 return PyModule_Create(&_string_module);
10428}
10429
10430
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010431#ifdef __cplusplus
10432}
10433#endif