blob: 456719685d48db4c03a74bb25fc4011b50b9ae47 [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;
755 if (*(f+1)=='S' || *(f+1)=='R' || *(f+1)=='A')
756 ++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':
816 (void)va_arg(count, int);
817 /* fall through... */
818 case '%':
819 n++;
820 break;
821 case 'd': case 'u': case 'i': case 'x':
822 (void) va_arg(count, int);
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000823#ifdef HAVE_LONG_LONG
824 if (longlongflag) {
825 if (width < MAX_LONG_LONG_CHARS)
826 width = MAX_LONG_LONG_CHARS;
827 }
828 else
829#endif
830 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
831 including sign. Decimal takes the most space. This
832 isn't enough for octal. If a width is specified we
833 need more (which we allocate later). */
834 if (width < MAX_LONG_CHARS)
835 width = MAX_LONG_CHARS;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000836 n += width;
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000837 /* XXX should allow for large precision here too. */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000838 if (abuffersize < width)
839 abuffersize = width;
840 break;
841 case 's':
842 {
843 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +0000844 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000845 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
846 if (!str)
847 goto fail;
848 n += PyUnicode_GET_SIZE(str);
849 /* Remember the str and switch to the next slot */
850 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000851 break;
852 }
853 case 'U':
854 {
855 PyObject *obj = va_arg(count, PyObject *);
856 assert(obj && PyUnicode_Check(obj));
857 n += PyUnicode_GET_SIZE(obj);
858 break;
859 }
860 case 'V':
861 {
862 PyObject *obj = va_arg(count, PyObject *);
863 const char *str = va_arg(count, const char *);
864 assert(obj || str);
865 assert(!obj || PyUnicode_Check(obj));
866 if (obj)
867 n += PyUnicode_GET_SIZE(obj);
868 else
869 n += strlen(str);
870 break;
871 }
872 case 'S':
873 {
874 PyObject *obj = va_arg(count, PyObject *);
875 PyObject *str;
876 assert(obj);
877 str = PyObject_Str(obj);
878 if (!str)
879 goto fail;
880 n += PyUnicode_GET_SIZE(str);
881 /* Remember the str and switch to the next slot */
882 *callresult++ = str;
883 break;
884 }
885 case 'R':
886 {
887 PyObject *obj = va_arg(count, PyObject *);
888 PyObject *repr;
889 assert(obj);
890 repr = PyObject_Repr(obj);
891 if (!repr)
892 goto fail;
893 n += PyUnicode_GET_SIZE(repr);
894 /* Remember the repr and switch to the next slot */
895 *callresult++ = repr;
896 break;
897 }
898 case 'A':
899 {
900 PyObject *obj = va_arg(count, PyObject *);
901 PyObject *ascii;
902 assert(obj);
903 ascii = PyObject_ASCII(obj);
904 if (!ascii)
905 goto fail;
906 n += PyUnicode_GET_SIZE(ascii);
907 /* Remember the repr and switch to the next slot */
908 *callresult++ = ascii;
909 break;
910 }
911 case 'p':
912 (void) va_arg(count, int);
913 /* maximum 64-bit pointer representation:
914 * 0xffffffffffffffff
915 * so 19 characters is enough.
916 * XXX I count 18 -- what's the extra for?
917 */
918 n += 19;
919 break;
920 default:
921 /* if we stumble upon an unknown
922 formatting code, copy the rest of
923 the format string to the output
924 string. (we cannot just skip the
925 code, since there's no way to know
926 what's in the argument list) */
927 n += strlen(p);
928 goto expand;
929 }
930 } else
931 n++;
932 }
Benjamin Peterson29060642009-01-31 22:14:21 +0000933 expand:
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000934 if (abuffersize > ITEM_BUFFER_LEN) {
935 /* add 1 for sprintf's trailing null byte */
936 abuffer = PyObject_Malloc(abuffersize + 1);
Benjamin Peterson14339b62009-01-31 16:36:08 +0000937 if (!abuffer) {
938 PyErr_NoMemory();
939 goto fail;
940 }
941 realbuffer = abuffer;
942 }
943 else
944 realbuffer = buffer;
945 /* step 4: fill the buffer */
946 /* Since we've analyzed how much space we need for the worst case,
947 we don't have to resize the string.
948 There can be no errors beyond this point. */
949 string = PyUnicode_FromUnicode(NULL, n);
950 if (!string)
951 goto fail;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000952
Benjamin Peterson14339b62009-01-31 16:36:08 +0000953 s = PyUnicode_AS_UNICODE(string);
954 callresult = callresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000955
Benjamin Peterson14339b62009-01-31 16:36:08 +0000956 for (f = format; *f; f++) {
957 if (*f == '%') {
958 const char* p = f++;
959 int longflag = 0;
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000960 int longlongflag = 0;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000961 int size_tflag = 0;
962 zeropad = (*f == '0');
963 /* parse the width.precision part */
964 width = 0;
David Malcolm96960882010-11-05 17:23:41 +0000965 while (Py_ISDIGIT((unsigned)*f))
Benjamin Peterson14339b62009-01-31 16:36:08 +0000966 width = (width*10) + *f++ - '0';
967 precision = 0;
968 if (*f == '.') {
969 f++;
David Malcolm96960882010-11-05 17:23:41 +0000970 while (Py_ISDIGIT((unsigned)*f))
Benjamin Peterson14339b62009-01-31 16:36:08 +0000971 precision = (precision*10) + *f++ - '0';
972 }
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000973 /* Handle %ld, %lu, %lld and %llu. */
974 if (*f == 'l') {
975 if (f[1] == 'd' || f[1] == 'u') {
976 longflag = 1;
977 ++f;
978 }
979#ifdef HAVE_LONG_LONG
980 else if (f[1] == 'l' &&
981 (f[2] == 'd' || f[2] == 'u')) {
982 longlongflag = 1;
983 f += 2;
984 }
985#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +0000986 }
987 /* handle the size_t flag. */
988 if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
989 size_tflag = 1;
990 ++f;
991 }
Walter Dörwaldd2034312007-05-18 16:29:38 +0000992
Benjamin Peterson14339b62009-01-31 16:36:08 +0000993 switch (*f) {
994 case 'c':
995 *s++ = va_arg(vargs, int);
996 break;
997 case 'd':
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000998 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
999 width, precision, 'd');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001000 if (longflag)
1001 sprintf(realbuffer, fmt, va_arg(vargs, long));
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001002#ifdef HAVE_LONG_LONG
1003 else if (longlongflag)
1004 sprintf(realbuffer, fmt, va_arg(vargs, PY_LONG_LONG));
1005#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001006 else if (size_tflag)
1007 sprintf(realbuffer, fmt, va_arg(vargs, Py_ssize_t));
1008 else
1009 sprintf(realbuffer, fmt, va_arg(vargs, int));
1010 appendstring(realbuffer);
1011 break;
1012 case 'u':
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001013 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
1014 width, precision, 'u');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001015 if (longflag)
1016 sprintf(realbuffer, fmt, va_arg(vargs, unsigned long));
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001017#ifdef HAVE_LONG_LONG
1018 else if (longlongflag)
1019 sprintf(realbuffer, fmt, va_arg(vargs,
1020 unsigned PY_LONG_LONG));
1021#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001022 else if (size_tflag)
1023 sprintf(realbuffer, fmt, va_arg(vargs, size_t));
1024 else
1025 sprintf(realbuffer, fmt, va_arg(vargs, unsigned int));
1026 appendstring(realbuffer);
1027 break;
1028 case 'i':
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001029 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'i');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001030 sprintf(realbuffer, fmt, va_arg(vargs, int));
1031 appendstring(realbuffer);
1032 break;
1033 case 'x':
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001034 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001035 sprintf(realbuffer, fmt, va_arg(vargs, int));
1036 appendstring(realbuffer);
1037 break;
1038 case 's':
1039 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001040 /* unused, since we already have the result */
1041 (void) va_arg(vargs, char *);
1042 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(*callresult),
1043 PyUnicode_GET_SIZE(*callresult));
1044 s += PyUnicode_GET_SIZE(*callresult);
1045 /* We're done with the unicode()/repr() => forget it */
1046 Py_DECREF(*callresult);
1047 /* switch to next unicode()/repr() result */
1048 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001049 break;
1050 }
1051 case 'U':
1052 {
1053 PyObject *obj = va_arg(vargs, PyObject *);
1054 Py_ssize_t size = PyUnicode_GET_SIZE(obj);
1055 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size);
1056 s += size;
1057 break;
1058 }
1059 case 'V':
1060 {
1061 PyObject *obj = va_arg(vargs, PyObject *);
1062 const char *str = va_arg(vargs, const char *);
1063 if (obj) {
1064 Py_ssize_t size = PyUnicode_GET_SIZE(obj);
1065 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size);
1066 s += size;
1067 } else {
1068 appendstring(str);
1069 }
1070 break;
1071 }
1072 case 'S':
1073 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00001074 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00001075 {
1076 Py_UNICODE *ucopy;
1077 Py_ssize_t usize;
1078 Py_ssize_t upos;
1079 /* unused, since we already have the result */
1080 (void) va_arg(vargs, PyObject *);
1081 ucopy = PyUnicode_AS_UNICODE(*callresult);
1082 usize = PyUnicode_GET_SIZE(*callresult);
1083 for (upos = 0; upos<usize;)
1084 *s++ = ucopy[upos++];
1085 /* We're done with the unicode()/repr() => forget it */
1086 Py_DECREF(*callresult);
1087 /* switch to next unicode()/repr() result */
1088 ++callresult;
1089 break;
1090 }
1091 case 'p':
1092 sprintf(buffer, "%p", va_arg(vargs, void*));
1093 /* %p is ill-defined: ensure leading 0x. */
1094 if (buffer[1] == 'X')
1095 buffer[1] = 'x';
1096 else if (buffer[1] != 'x') {
1097 memmove(buffer+2, buffer, strlen(buffer)+1);
1098 buffer[0] = '0';
1099 buffer[1] = 'x';
1100 }
1101 appendstring(buffer);
1102 break;
1103 case '%':
1104 *s++ = '%';
1105 break;
1106 default:
1107 appendstring(p);
1108 goto end;
1109 }
Victor Stinner1205f272010-09-11 00:54:47 +00001110 }
Victor Stinner1205f272010-09-11 00:54:47 +00001111 else
Benjamin Peterson14339b62009-01-31 16:36:08 +00001112 *s++ = *f;
1113 }
Walter Dörwaldd2034312007-05-18 16:29:38 +00001114
Benjamin Peterson29060642009-01-31 22:14:21 +00001115 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001116 if (callresults)
1117 PyObject_Free(callresults);
1118 if (abuffer)
1119 PyObject_Free(abuffer);
1120 PyUnicode_Resize(&string, s - PyUnicode_AS_UNICODE(string));
1121 return string;
Benjamin Peterson29060642009-01-31 22:14:21 +00001122 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001123 if (callresults) {
1124 PyObject **callresult2 = callresults;
1125 while (callresult2 < callresult) {
1126 Py_DECREF(*callresult2);
1127 ++callresult2;
1128 }
1129 PyObject_Free(callresults);
1130 }
1131 if (abuffer)
1132 PyObject_Free(abuffer);
1133 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001134}
1135
1136#undef appendstring
1137
1138PyObject *
1139PyUnicode_FromFormat(const char *format, ...)
1140{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001141 PyObject* ret;
1142 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001143
1144#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00001145 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001146#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00001147 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001148#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001149 ret = PyUnicode_FromFormatV(format, vargs);
1150 va_end(vargs);
1151 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001152}
1153
Victor Stinner5593d8a2010-10-02 11:11:27 +00001154/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
1155 convert a Unicode object to a wide character string.
1156
1157 - If w is NULL: return the number of wide characters (including the nul
1158 character) required to convert the unicode object. Ignore size argument.
1159
1160 - Otherwise: return the number of wide characters (excluding the nul
1161 character) written into w. Write at most size wide characters (including
1162 the nul character). */
1163static Py_ssize_t
Victor Stinner137c34c2010-09-29 10:25:54 +00001164unicode_aswidechar(PyUnicodeObject *unicode,
1165 wchar_t *w,
1166 Py_ssize_t size)
1167{
1168#if Py_UNICODE_SIZE == SIZEOF_WCHAR_T
Victor Stinner5593d8a2010-10-02 11:11:27 +00001169 Py_ssize_t res;
1170 if (w != NULL) {
1171 res = PyUnicode_GET_SIZE(unicode);
1172 if (size > res)
1173 size = res + 1;
1174 else
1175 res = size;
1176 memcpy(w, unicode->str, size * sizeof(wchar_t));
1177 return res;
1178 }
1179 else
1180 return PyUnicode_GET_SIZE(unicode) + 1;
1181#elif Py_UNICODE_SIZE == 2 && SIZEOF_WCHAR_T == 4
1182 register const Py_UNICODE *u;
1183 const Py_UNICODE *uend;
1184 const wchar_t *worig, *wend;
1185 Py_ssize_t nchar;
1186
Victor Stinner137c34c2010-09-29 10:25:54 +00001187 u = PyUnicode_AS_UNICODE(unicode);
Victor Stinner5593d8a2010-10-02 11:11:27 +00001188 uend = u + PyUnicode_GET_SIZE(unicode);
1189 if (w != NULL) {
1190 worig = w;
1191 wend = w + size;
1192 while (u != uend && w != wend) {
1193 if (0xD800 <= u[0] && u[0] <= 0xDBFF
1194 && 0xDC00 <= u[1] && u[1] <= 0xDFFF)
1195 {
1196 *w = (((u[0] & 0x3FF) << 10) | (u[1] & 0x3FF)) + 0x10000;
1197 u += 2;
1198 }
1199 else {
1200 *w = *u;
1201 u++;
1202 }
1203 w++;
1204 }
1205 if (w != wend)
1206 *w = L'\0';
1207 return w - worig;
1208 }
1209 else {
1210 nchar = 1; /* nul character at the end */
1211 while (u != uend) {
1212 if (0xD800 <= u[0] && u[0] <= 0xDBFF
1213 && 0xDC00 <= u[1] && u[1] <= 0xDFFF)
1214 u += 2;
1215 else
1216 u++;
1217 nchar++;
1218 }
1219 }
1220 return nchar;
1221#elif Py_UNICODE_SIZE == 4 && SIZEOF_WCHAR_T == 2
1222 register Py_UNICODE *u, *uend, ordinal;
1223 register Py_ssize_t i;
1224 wchar_t *worig, *wend;
1225 Py_ssize_t nchar;
1226
1227 u = PyUnicode_AS_UNICODE(unicode);
1228 uend = u + PyUnicode_GET_SIZE(u);
1229 if (w != NULL) {
1230 worig = w;
1231 wend = w + size;
1232 while (u != uend && w != wend) {
1233 ordinal = *u;
1234 if (ordinal > 0xffff) {
1235 ordinal -= 0x10000;
1236 *w++ = 0xD800 | (ordinal >> 10);
1237 *w++ = 0xDC00 | (ordinal & 0x3FF);
1238 }
1239 else
1240 *w++ = ordinal;
1241 u++;
1242 }
1243 if (w != wend)
1244 *w = 0;
1245 return w - worig;
1246 }
1247 else {
1248 nchar = 1; /* nul character */
1249 while (u != uend) {
1250 if (*u > 0xffff)
1251 nchar += 2;
1252 else
1253 nchar++;
1254 u++;
1255 }
1256 return nchar;
1257 }
1258#else
1259# error "unsupported wchar_t and Py_UNICODE sizes, see issue #8670"
Victor Stinner137c34c2010-09-29 10:25:54 +00001260#endif
1261}
1262
1263Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001264PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00001265 wchar_t *w,
1266 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001267{
1268 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001269 PyErr_BadInternalCall();
1270 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001271 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001272 return unicode_aswidechar((PyUnicodeObject*)unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001273}
1274
Victor Stinner137c34c2010-09-29 10:25:54 +00001275wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00001276PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00001277 Py_ssize_t *size)
1278{
1279 wchar_t* buffer;
1280 Py_ssize_t buflen;
1281
1282 if (unicode == NULL) {
1283 PyErr_BadInternalCall();
1284 return NULL;
1285 }
1286
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00001287 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, NULL, 0);
Victor Stinner5593d8a2010-10-02 11:11:27 +00001288 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00001289 PyErr_NoMemory();
1290 return NULL;
1291 }
1292
Victor Stinner137c34c2010-09-29 10:25:54 +00001293 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
1294 if (buffer == NULL) {
1295 PyErr_NoMemory();
1296 return NULL;
1297 }
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00001298 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, buffer, buflen);
Victor Stinner5593d8a2010-10-02 11:11:27 +00001299 if (size != NULL)
1300 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00001301 return buffer;
1302}
1303
Guido van Rossumd57fd912000-03-10 22:53:23 +00001304#endif
1305
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001306PyObject *PyUnicode_FromOrdinal(int ordinal)
1307{
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001308 Py_UNICODE s[2];
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001309
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001310 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001311 PyErr_SetString(PyExc_ValueError,
1312 "chr() arg not in range(0x110000)");
1313 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001314 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001315
1316#ifndef Py_UNICODE_WIDE
1317 if (ordinal > 0xffff) {
1318 ordinal -= 0x10000;
1319 s[0] = 0xD800 | (ordinal >> 10);
1320 s[1] = 0xDC00 | (ordinal & 0x3FF);
1321 return PyUnicode_FromUnicode(s, 2);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001322 }
1323#endif
1324
Hye-Shik Chang40574832004-04-06 07:24:51 +00001325 s[0] = (Py_UNICODE)ordinal;
1326 return PyUnicode_FromUnicode(s, 1);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001327}
1328
Guido van Rossumd57fd912000-03-10 22:53:23 +00001329PyObject *PyUnicode_FromObject(register PyObject *obj)
1330{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001331 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00001332 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001333 if (PyUnicode_CheckExact(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001334 Py_INCREF(obj);
1335 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001336 }
1337 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001338 /* For a Unicode subtype that's not a Unicode object,
1339 return a true Unicode object with the same data. */
1340 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(obj),
1341 PyUnicode_GET_SIZE(obj));
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001342 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001343 PyErr_Format(PyExc_TypeError,
1344 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00001345 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001346 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001347}
1348
1349PyObject *PyUnicode_FromEncodedObject(register PyObject *obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00001350 const char *encoding,
1351 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001352{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001353 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001354 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00001355
Guido van Rossumd57fd912000-03-10 22:53:23 +00001356 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001357 PyErr_BadInternalCall();
1358 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001359 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001360
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001361 /* Decoding bytes objects is the most common case and should be fast */
1362 if (PyBytes_Check(obj)) {
1363 if (PyBytes_GET_SIZE(obj) == 0) {
1364 Py_INCREF(unicode_empty);
1365 v = (PyObject *) unicode_empty;
1366 }
1367 else {
1368 v = PyUnicode_Decode(
1369 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
1370 encoding, errors);
1371 }
1372 return v;
1373 }
1374
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001375 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001376 PyErr_SetString(PyExc_TypeError,
1377 "decoding str is not supported");
1378 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001379 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001380
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001381 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
1382 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
1383 PyErr_Format(PyExc_TypeError,
1384 "coercing to str: need bytes, bytearray "
1385 "or buffer-like object, %.80s found",
1386 Py_TYPE(obj)->tp_name);
1387 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00001388 }
Tim Petersced69f82003-09-16 20:30:58 +00001389
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001390 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001391 Py_INCREF(unicode_empty);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001392 v = (PyObject *) unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001393 }
Tim Petersced69f82003-09-16 20:30:58 +00001394 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001395 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00001396
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001397 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001398 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001399}
1400
Victor Stinner600d3be2010-06-10 12:00:55 +00001401/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00001402 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
1403 1 on success. */
1404static int
1405normalize_encoding(const char *encoding,
1406 char *lower,
1407 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001408{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001409 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00001410 char *l;
1411 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001412
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001413 e = encoding;
1414 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00001415 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00001416 while (*e) {
1417 if (l == l_end)
1418 return 0;
David Malcolm96960882010-11-05 17:23:41 +00001419 if (Py_ISUPPER(*e)) {
1420 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001421 }
1422 else if (*e == '_') {
1423 *l++ = '-';
1424 e++;
1425 }
1426 else {
1427 *l++ = *e++;
1428 }
1429 }
1430 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00001431 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00001432}
1433
1434PyObject *PyUnicode_Decode(const char *s,
1435 Py_ssize_t size,
1436 const char *encoding,
1437 const char *errors)
1438{
1439 PyObject *buffer = NULL, *unicode;
1440 Py_buffer info;
1441 char lower[11]; /* Enough for any encoding shortcut */
1442
1443 if (encoding == NULL)
1444 encoding = PyUnicode_GetDefaultEncoding();
Fred Drakee4315f52000-05-09 19:53:39 +00001445
1446 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00001447 if (normalize_encoding(encoding, lower, sizeof(lower))) {
1448 if (strcmp(lower, "utf-8") == 0)
1449 return PyUnicode_DecodeUTF8(s, size, errors);
1450 else if ((strcmp(lower, "latin-1") == 0) ||
1451 (strcmp(lower, "iso-8859-1") == 0))
1452 return PyUnicode_DecodeLatin1(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001453#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Victor Stinner37296e82010-06-10 13:36:23 +00001454 else if (strcmp(lower, "mbcs") == 0)
1455 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001456#endif
Victor Stinner37296e82010-06-10 13:36:23 +00001457 else if (strcmp(lower, "ascii") == 0)
1458 return PyUnicode_DecodeASCII(s, size, errors);
1459 else if (strcmp(lower, "utf-16") == 0)
1460 return PyUnicode_DecodeUTF16(s, size, errors, 0);
1461 else if (strcmp(lower, "utf-32") == 0)
1462 return PyUnicode_DecodeUTF32(s, size, errors, 0);
1463 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001464
1465 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00001466 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00001467 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00001468 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00001469 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001470 if (buffer == NULL)
1471 goto onError;
1472 unicode = PyCodec_Decode(buffer, encoding, errors);
1473 if (unicode == NULL)
1474 goto onError;
1475 if (!PyUnicode_Check(unicode)) {
1476 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001477 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00001478 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001479 Py_DECREF(unicode);
1480 goto onError;
1481 }
1482 Py_DECREF(buffer);
1483 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00001484
Benjamin Peterson29060642009-01-31 22:14:21 +00001485 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001486 Py_XDECREF(buffer);
1487 return NULL;
1488}
1489
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001490PyObject *PyUnicode_AsDecodedObject(PyObject *unicode,
1491 const char *encoding,
1492 const char *errors)
1493{
1494 PyObject *v;
1495
1496 if (!PyUnicode_Check(unicode)) {
1497 PyErr_BadArgument();
1498 goto onError;
1499 }
1500
1501 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001502 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001503
1504 /* Decode via the codec registry */
1505 v = PyCodec_Decode(unicode, encoding, errors);
1506 if (v == NULL)
1507 goto onError;
1508 return v;
1509
Benjamin Peterson29060642009-01-31 22:14:21 +00001510 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001511 return NULL;
1512}
1513
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001514PyObject *PyUnicode_AsDecodedUnicode(PyObject *unicode,
1515 const char *encoding,
1516 const char *errors)
1517{
1518 PyObject *v;
1519
1520 if (!PyUnicode_Check(unicode)) {
1521 PyErr_BadArgument();
1522 goto onError;
1523 }
1524
1525 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001526 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001527
1528 /* Decode via the codec registry */
1529 v = PyCodec_Decode(unicode, encoding, errors);
1530 if (v == NULL)
1531 goto onError;
1532 if (!PyUnicode_Check(v)) {
1533 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001534 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001535 Py_TYPE(v)->tp_name);
1536 Py_DECREF(v);
1537 goto onError;
1538 }
1539 return v;
1540
Benjamin Peterson29060642009-01-31 22:14:21 +00001541 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001542 return NULL;
1543}
1544
Guido van Rossumd57fd912000-03-10 22:53:23 +00001545PyObject *PyUnicode_Encode(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00001546 Py_ssize_t size,
1547 const char *encoding,
1548 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001549{
1550 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00001551
Guido van Rossumd57fd912000-03-10 22:53:23 +00001552 unicode = PyUnicode_FromUnicode(s, size);
1553 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001554 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001555 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
1556 Py_DECREF(unicode);
1557 return v;
1558}
1559
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001560PyObject *PyUnicode_AsEncodedObject(PyObject *unicode,
1561 const char *encoding,
1562 const char *errors)
1563{
1564 PyObject *v;
1565
1566 if (!PyUnicode_Check(unicode)) {
1567 PyErr_BadArgument();
1568 goto onError;
1569 }
1570
1571 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001572 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001573
1574 /* Encode via the codec registry */
1575 v = PyCodec_Encode(unicode, encoding, errors);
1576 if (v == NULL)
1577 goto onError;
1578 return v;
1579
Benjamin Peterson29060642009-01-31 22:14:21 +00001580 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001581 return NULL;
1582}
1583
Victor Stinnerad158722010-10-27 00:25:46 +00001584PyObject *
1585PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00001586{
Victor Stinner313a1202010-06-11 23:56:51 +00001587#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Victor Stinnerad158722010-10-27 00:25:46 +00001588 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
1589 PyUnicode_GET_SIZE(unicode),
1590 NULL);
1591#elif defined(__APPLE__)
1592 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
1593 PyUnicode_GET_SIZE(unicode),
1594 "surrogateescape");
1595#else
1596 if (Py_FileSystemDefaultEncoding) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00001597 return PyUnicode_AsEncodedString(unicode,
1598 Py_FileSystemDefaultEncoding,
1599 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00001600 }
1601 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001602 /* locale encoding with surrogateescape */
1603 wchar_t *wchar;
1604 char *bytes;
1605 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00001606 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001607
1608 wchar = PyUnicode_AsWideCharString(unicode, NULL);
1609 if (wchar == NULL)
1610 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00001611 bytes = _Py_wchar2char(wchar, &error_pos);
1612 if (bytes == NULL) {
1613 if (error_pos != (size_t)-1) {
1614 char *errmsg = strerror(errno);
1615 PyObject *exc = NULL;
1616 if (errmsg == NULL)
1617 errmsg = "Py_wchar2char() failed";
1618 raise_encode_exception(&exc,
1619 "filesystemencoding",
1620 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
1621 error_pos, error_pos+1,
1622 errmsg);
1623 Py_XDECREF(exc);
1624 }
1625 else
1626 PyErr_NoMemory();
1627 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001628 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00001629 }
1630 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001631
1632 bytes_obj = PyBytes_FromString(bytes);
1633 PyMem_Free(bytes);
1634 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00001635 }
Victor Stinnerad158722010-10-27 00:25:46 +00001636#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00001637}
1638
Guido van Rossumd57fd912000-03-10 22:53:23 +00001639PyObject *PyUnicode_AsEncodedString(PyObject *unicode,
1640 const char *encoding,
1641 const char *errors)
1642{
1643 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00001644 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00001645
Guido van Rossumd57fd912000-03-10 22:53:23 +00001646 if (!PyUnicode_Check(unicode)) {
1647 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001648 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001649 }
Fred Drakee4315f52000-05-09 19:53:39 +00001650
Tim Petersced69f82003-09-16 20:30:58 +00001651 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001652 encoding = PyUnicode_GetDefaultEncoding();
Fred Drakee4315f52000-05-09 19:53:39 +00001653
1654 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00001655 if (normalize_encoding(encoding, lower, sizeof(lower))) {
1656 if (strcmp(lower, "utf-8") == 0)
1657 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
1658 PyUnicode_GET_SIZE(unicode),
1659 errors);
1660 else if ((strcmp(lower, "latin-1") == 0) ||
1661 (strcmp(lower, "iso-8859-1") == 0))
1662 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
1663 PyUnicode_GET_SIZE(unicode),
1664 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001665#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Victor Stinner37296e82010-06-10 13:36:23 +00001666 else if (strcmp(lower, "mbcs") == 0)
1667 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
1668 PyUnicode_GET_SIZE(unicode),
1669 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001670#endif
Victor Stinner37296e82010-06-10 13:36:23 +00001671 else if (strcmp(lower, "ascii") == 0)
1672 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
1673 PyUnicode_GET_SIZE(unicode),
1674 errors);
1675 }
Victor Stinner59e62db2010-05-15 13:14:32 +00001676 /* During bootstrap, we may need to find the encodings
1677 package, to load the file system encoding, and require the
1678 file system encoding in order to load the encodings
1679 package.
Christian Heimes6a27efa2008-10-30 21:48:26 +00001680
Victor Stinner59e62db2010-05-15 13:14:32 +00001681 Break out of this dependency by assuming that the path to
1682 the encodings module is ASCII-only. XXX could try wcstombs
1683 instead, if the file system encoding is the locale's
1684 encoding. */
Victor Stinner37296e82010-06-10 13:36:23 +00001685 if (Py_FileSystemDefaultEncoding &&
Victor Stinner59e62db2010-05-15 13:14:32 +00001686 strcmp(encoding, Py_FileSystemDefaultEncoding) == 0 &&
1687 !PyThreadState_GET()->interp->codecs_initialized)
1688 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
1689 PyUnicode_GET_SIZE(unicode),
1690 errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001691
1692 /* Encode via the codec registry */
1693 v = PyCodec_Encode(unicode, encoding, errors);
1694 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001695 return NULL;
1696
1697 /* The normal path */
1698 if (PyBytes_Check(v))
1699 return v;
1700
1701 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001702 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001703 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001704 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001705
1706 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1707 "encoder %s returned bytearray instead of bytes",
1708 encoding);
1709 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001710 Py_DECREF(v);
1711 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001712 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001713
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001714 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
1715 Py_DECREF(v);
1716 return b;
1717 }
1718
1719 PyErr_Format(PyExc_TypeError,
1720 "encoder did not return a bytes object (type=%.400s)",
1721 Py_TYPE(v)->tp_name);
1722 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001723 return NULL;
1724}
1725
1726PyObject *PyUnicode_AsEncodedUnicode(PyObject *unicode,
1727 const char *encoding,
1728 const char *errors)
1729{
1730 PyObject *v;
1731
1732 if (!PyUnicode_Check(unicode)) {
1733 PyErr_BadArgument();
1734 goto onError;
1735 }
1736
1737 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001738 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001739
1740 /* Encode via the codec registry */
1741 v = PyCodec_Encode(unicode, encoding, errors);
1742 if (v == NULL)
1743 goto onError;
1744 if (!PyUnicode_Check(v)) {
1745 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001746 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001747 Py_TYPE(v)->tp_name);
1748 Py_DECREF(v);
1749 goto onError;
1750 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001751 return v;
Tim Petersced69f82003-09-16 20:30:58 +00001752
Benjamin Peterson29060642009-01-31 22:14:21 +00001753 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001754 return NULL;
1755}
1756
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001757PyObject *_PyUnicode_AsDefaultEncodedString(PyObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00001758 const char *errors)
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001759{
1760 PyObject *v = ((PyUnicodeObject *)unicode)->defenc;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001761 if (v)
1762 return v;
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001763 if (errors != NULL)
1764 Py_FatalError("non-NULL encoding in _PyUnicode_AsDefaultEncodedString");
Guido van Rossum98297ee2007-11-06 21:34:58 +00001765 v = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
Guido van Rossum06610092007-08-16 21:02:22 +00001766 PyUnicode_GET_SIZE(unicode),
1767 NULL);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001768 if (!v)
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001769 return NULL;
Guido van Rossume7a0d392007-07-12 07:53:00 +00001770 ((PyUnicodeObject *)unicode)->defenc = v;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001771 return v;
1772}
1773
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001774PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00001775PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001776 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00001777 return PyUnicode_DecodeFSDefaultAndSize(s, size);
1778}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001779
Christian Heimes5894ba72007-11-04 11:43:14 +00001780PyObject*
1781PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
1782{
Victor Stinnerad158722010-10-27 00:25:46 +00001783#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
1784 return PyUnicode_DecodeMBCS(s, size, NULL);
1785#elif defined(__APPLE__)
1786 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
1787#else
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001788 /* During the early bootstrapping process, Py_FileSystemDefaultEncoding
1789 can be undefined. If it is case, decode using UTF-8. The following assumes
1790 that Py_FileSystemDefaultEncoding is set to a built-in encoding during the
1791 bootstrapping process where the codecs aren't ready yet.
1792 */
1793 if (Py_FileSystemDefaultEncoding) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001794 return PyUnicode_Decode(s, size,
1795 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00001796 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001797 }
1798 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001799 /* locale encoding with surrogateescape */
1800 wchar_t *wchar;
1801 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00001802 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001803
1804 if (s[size] != '\0' || size != strlen(s)) {
1805 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
1806 return NULL;
1807 }
1808
Victor Stinner168e1172010-10-16 23:16:16 +00001809 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001810 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00001811 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001812
Victor Stinner168e1172010-10-16 23:16:16 +00001813 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001814 PyMem_Free(wchar);
1815 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001816 }
Victor Stinnerad158722010-10-27 00:25:46 +00001817#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001818}
1819
Martin v. Löwis011e8422009-05-05 04:43:17 +00001820
1821int
1822PyUnicode_FSConverter(PyObject* arg, void* addr)
1823{
1824 PyObject *output = NULL;
1825 Py_ssize_t size;
1826 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00001827 if (arg == NULL) {
1828 Py_DECREF(*(PyObject**)addr);
1829 return 1;
1830 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00001831 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00001832 output = arg;
1833 Py_INCREF(output);
1834 }
1835 else {
1836 arg = PyUnicode_FromObject(arg);
1837 if (!arg)
1838 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00001839 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00001840 Py_DECREF(arg);
1841 if (!output)
1842 return 0;
1843 if (!PyBytes_Check(output)) {
1844 Py_DECREF(output);
1845 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
1846 return 0;
1847 }
1848 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00001849 size = PyBytes_GET_SIZE(output);
1850 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00001851 if (size != strlen(data)) {
1852 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
1853 Py_DECREF(output);
1854 return 0;
1855 }
1856 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00001857 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00001858}
1859
1860
Victor Stinner47fcb5b2010-08-13 23:59:58 +00001861int
1862PyUnicode_FSDecoder(PyObject* arg, void* addr)
1863{
1864 PyObject *output = NULL;
1865 Py_ssize_t size;
1866 void *data;
1867 if (arg == NULL) {
1868 Py_DECREF(*(PyObject**)addr);
1869 return 1;
1870 }
1871 if (PyUnicode_Check(arg)) {
1872 output = arg;
1873 Py_INCREF(output);
1874 }
1875 else {
1876 arg = PyBytes_FromObject(arg);
1877 if (!arg)
1878 return 0;
1879 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
1880 PyBytes_GET_SIZE(arg));
1881 Py_DECREF(arg);
1882 if (!output)
1883 return 0;
1884 if (!PyUnicode_Check(output)) {
1885 Py_DECREF(output);
1886 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
1887 return 0;
1888 }
1889 }
1890 size = PyUnicode_GET_SIZE(output);
1891 data = PyUnicode_AS_UNICODE(output);
1892 if (size != Py_UNICODE_strlen(data)) {
1893 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
1894 Py_DECREF(output);
1895 return 0;
1896 }
1897 *(PyObject**)addr = output;
1898 return Py_CLEANUP_SUPPORTED;
1899}
1900
1901
Martin v. Löwis5b222132007-06-10 09:51:05 +00001902char*
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001903_PyUnicode_AsStringAndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00001904{
Christian Heimesf3863112007-11-22 07:46:41 +00001905 PyObject *bytes;
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00001906 if (!PyUnicode_Check(unicode)) {
1907 PyErr_BadArgument();
1908 return NULL;
1909 }
Christian Heimesf3863112007-11-22 07:46:41 +00001910 bytes = _PyUnicode_AsDefaultEncodedString(unicode, NULL);
1911 if (bytes == NULL)
Martin v. Löwis5b222132007-06-10 09:51:05 +00001912 return NULL;
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001913 if (psize != NULL)
Christian Heimes72b710a2008-05-26 13:28:38 +00001914 *psize = PyBytes_GET_SIZE(bytes);
1915 return PyBytes_AS_STRING(bytes);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001916}
1917
1918char*
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001919_PyUnicode_AsString(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001920{
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001921 return _PyUnicode_AsStringAndSize(unicode, NULL);
Martin v. Löwis5b222132007-06-10 09:51:05 +00001922}
1923
Guido van Rossumd57fd912000-03-10 22:53:23 +00001924Py_UNICODE *PyUnicode_AsUnicode(PyObject *unicode)
1925{
1926 if (!PyUnicode_Check(unicode)) {
1927 PyErr_BadArgument();
1928 goto onError;
1929 }
1930 return PyUnicode_AS_UNICODE(unicode);
1931
Benjamin Peterson29060642009-01-31 22:14:21 +00001932 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001933 return NULL;
1934}
1935
Martin v. Löwis18e16552006-02-15 17:27:45 +00001936Py_ssize_t PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001937{
1938 if (!PyUnicode_Check(unicode)) {
1939 PyErr_BadArgument();
1940 goto onError;
1941 }
1942 return PyUnicode_GET_SIZE(unicode);
1943
Benjamin Peterson29060642009-01-31 22:14:21 +00001944 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001945 return -1;
1946}
1947
Thomas Wouters78890102000-07-22 19:25:51 +00001948const char *PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00001949{
Victor Stinner42cb4622010-09-01 19:39:01 +00001950 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00001951}
1952
Victor Stinner554f3f02010-06-16 23:33:54 +00001953/* create or adjust a UnicodeDecodeError */
1954static void
1955make_decode_exception(PyObject **exceptionObject,
1956 const char *encoding,
1957 const char *input, Py_ssize_t length,
1958 Py_ssize_t startpos, Py_ssize_t endpos,
1959 const char *reason)
1960{
1961 if (*exceptionObject == NULL) {
1962 *exceptionObject = PyUnicodeDecodeError_Create(
1963 encoding, input, length, startpos, endpos, reason);
1964 }
1965 else {
1966 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
1967 goto onError;
1968 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
1969 goto onError;
1970 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
1971 goto onError;
1972 }
1973 return;
1974
1975onError:
1976 Py_DECREF(*exceptionObject);
1977 *exceptionObject = NULL;
1978}
1979
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001980/* error handling callback helper:
1981 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00001982 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001983 and adjust various state variables.
1984 return 0 on success, -1 on error
1985*/
1986
1987static
1988int unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00001989 const char *encoding, const char *reason,
1990 const char **input, const char **inend, Py_ssize_t *startinpos,
1991 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
1992 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001993{
Benjamin Peterson142957c2008-07-04 19:55:29 +00001994 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001995
1996 PyObject *restuple = NULL;
1997 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001998 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00001999 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002000 Py_ssize_t requiredsize;
2001 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002002 Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002003 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002004 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002005 int res = -1;
2006
2007 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002008 *errorHandler = PyCodec_LookupError(errors);
2009 if (*errorHandler == NULL)
2010 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002011 }
2012
Victor Stinner554f3f02010-06-16 23:33:54 +00002013 make_decode_exception(exceptionObject,
2014 encoding,
2015 *input, *inend - *input,
2016 *startinpos, *endinpos,
2017 reason);
2018 if (*exceptionObject == NULL)
2019 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002020
2021 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
2022 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002023 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002024 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00002025 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00002026 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002027 }
2028 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00002029 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002030
2031 /* Copy back the bytes variables, which might have been modified by the
2032 callback */
2033 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
2034 if (!inputobj)
2035 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00002036 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002037 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00002038 }
Christian Heimes72b710a2008-05-26 13:28:38 +00002039 *input = PyBytes_AS_STRING(inputobj);
2040 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002041 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00002042 /* we can DECREF safely, as the exception has another reference,
2043 so the object won't go away. */
2044 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002045
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002046 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00002047 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00002048 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002049 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
2050 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00002051 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002052
2053 /* need more space? (at least enough for what we
2054 have+the replacement+the rest of the string (starting
2055 at the new input position), so we won't have to check space
2056 when there are no errors in the rest of the string) */
2057 repptr = PyUnicode_AS_UNICODE(repunicode);
2058 repsize = PyUnicode_GET_SIZE(repunicode);
2059 requiredsize = *outpos + repsize + insize-newpos;
2060 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002061 if (requiredsize<2*outsize)
2062 requiredsize = 2*outsize;
2063 if (_PyUnicode_Resize(output, requiredsize) < 0)
2064 goto onError;
2065 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002066 }
2067 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002068 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002069 Py_UNICODE_COPY(*outptr, repptr, repsize);
2070 *outptr += repsize;
2071 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002072
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002073 /* we made it! */
2074 res = 0;
2075
Benjamin Peterson29060642009-01-31 22:14:21 +00002076 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002077 Py_XDECREF(restuple);
2078 return res;
2079}
2080
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002081/* --- UTF-7 Codec -------------------------------------------------------- */
2082
Antoine Pitrou244651a2009-05-04 18:56:13 +00002083/* See RFC2152 for details. We encode conservatively and decode liberally. */
2084
2085/* Three simple macros defining base-64. */
2086
2087/* Is c a base-64 character? */
2088
2089#define IS_BASE64(c) \
2090 (((c) >= 'A' && (c) <= 'Z') || \
2091 ((c) >= 'a' && (c) <= 'z') || \
2092 ((c) >= '0' && (c) <= '9') || \
2093 (c) == '+' || (c) == '/')
2094
2095/* given that c is a base-64 character, what is its base-64 value? */
2096
2097#define FROM_BASE64(c) \
2098 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
2099 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
2100 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
2101 (c) == '+' ? 62 : 63)
2102
2103/* What is the base-64 character of the bottom 6 bits of n? */
2104
2105#define TO_BASE64(n) \
2106 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
2107
2108/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
2109 * decoded as itself. We are permissive on decoding; the only ASCII
2110 * byte not decoding to itself is the + which begins a base64
2111 * string. */
2112
2113#define DECODE_DIRECT(c) \
2114 ((c) <= 127 && (c) != '+')
2115
2116/* The UTF-7 encoder treats ASCII characters differently according to
2117 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
2118 * the above). See RFC2152. This array identifies these different
2119 * sets:
2120 * 0 : "Set D"
2121 * alphanumeric and '(),-./:?
2122 * 1 : "Set O"
2123 * !"#$%&*;<=>@[]^_`{|}
2124 * 2 : "whitespace"
2125 * ht nl cr sp
2126 * 3 : special (must be base64 encoded)
2127 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
2128 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002129
Tim Petersced69f82003-09-16 20:30:58 +00002130static
Antoine Pitrou244651a2009-05-04 18:56:13 +00002131char utf7_category[128] = {
2132/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
2133 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
2134/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
2135 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2136/* sp ! " # $ % & ' ( ) * + , - . / */
2137 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
2138/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
2139 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
2140/* @ A B C D E F G H I J K L M N O */
2141 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2142/* P Q R S T U V W X Y Z [ \ ] ^ _ */
2143 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
2144/* ` a b c d e f g h i j k l m n o */
2145 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2146/* p q r s t u v w x y z { | } ~ del */
2147 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002148};
2149
Antoine Pitrou244651a2009-05-04 18:56:13 +00002150/* ENCODE_DIRECT: this character should be encoded as itself. The
2151 * answer depends on whether we are encoding set O as itself, and also
2152 * on whether we are encoding whitespace as itself. RFC2152 makes it
2153 * clear that the answers to these questions vary between
2154 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00002155
Antoine Pitrou244651a2009-05-04 18:56:13 +00002156#define ENCODE_DIRECT(c, directO, directWS) \
2157 ((c) < 128 && (c) > 0 && \
2158 ((utf7_category[(c)] == 0) || \
2159 (directWS && (utf7_category[(c)] == 2)) || \
2160 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002161
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002162PyObject *PyUnicode_DecodeUTF7(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002163 Py_ssize_t size,
2164 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002165{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002166 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
2167}
2168
Antoine Pitrou244651a2009-05-04 18:56:13 +00002169/* The decoder. The only state we preserve is our read position,
2170 * i.e. how many characters we have consumed. So if we end in the
2171 * middle of a shift sequence we have to back off the read position
2172 * and the output to the beginning of the sequence, otherwise we lose
2173 * all the shift state (seen bits, number of bits seen, high
2174 * surrogate). */
2175
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002176PyObject *PyUnicode_DecodeUTF7Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002177 Py_ssize_t size,
2178 const char *errors,
2179 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002180{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002181 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002182 Py_ssize_t startinpos;
2183 Py_ssize_t endinpos;
2184 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002185 const char *e;
2186 PyUnicodeObject *unicode;
2187 Py_UNICODE *p;
2188 const char *errmsg = "";
2189 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002190 Py_UNICODE *shiftOutStart;
2191 unsigned int base64bits = 0;
2192 unsigned long base64buffer = 0;
2193 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002194 PyObject *errorHandler = NULL;
2195 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002196
2197 unicode = _PyUnicode_New(size);
2198 if (!unicode)
2199 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002200 if (size == 0) {
2201 if (consumed)
2202 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002203 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002204 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002205
2206 p = unicode->str;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002207 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002208 e = s + size;
2209
2210 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002211 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00002212 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00002213 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002214
Antoine Pitrou244651a2009-05-04 18:56:13 +00002215 if (inShift) { /* in a base-64 section */
2216 if (IS_BASE64(ch)) { /* consume a base-64 character */
2217 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
2218 base64bits += 6;
2219 s++;
2220 if (base64bits >= 16) {
2221 /* we have enough bits for a UTF-16 value */
2222 Py_UNICODE outCh = (Py_UNICODE)
2223 (base64buffer >> (base64bits-16));
2224 base64bits -= 16;
2225 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
2226 if (surrogate) {
2227 /* expecting a second surrogate */
2228 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
2229#ifdef Py_UNICODE_WIDE
2230 *p++ = (((surrogate & 0x3FF)<<10)
2231 | (outCh & 0x3FF)) + 0x10000;
2232#else
2233 *p++ = surrogate;
2234 *p++ = outCh;
2235#endif
2236 surrogate = 0;
2237 }
2238 else {
2239 surrogate = 0;
2240 errmsg = "second surrogate missing";
2241 goto utf7Error;
2242 }
2243 }
2244 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
2245 /* first surrogate */
2246 surrogate = outCh;
2247 }
2248 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
2249 errmsg = "unexpected second surrogate";
2250 goto utf7Error;
2251 }
2252 else {
2253 *p++ = outCh;
2254 }
2255 }
2256 }
2257 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002258 inShift = 0;
2259 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002260 if (surrogate) {
2261 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00002262 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002263 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002264 if (base64bits > 0) { /* left-over bits */
2265 if (base64bits >= 6) {
2266 /* We've seen at least one base-64 character */
2267 errmsg = "partial character in shift sequence";
2268 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002269 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002270 else {
2271 /* Some bits remain; they should be zero */
2272 if (base64buffer != 0) {
2273 errmsg = "non-zero padding bits in shift sequence";
2274 goto utf7Error;
2275 }
2276 }
2277 }
2278 if (ch != '-') {
2279 /* '-' is absorbed; other terminating
2280 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002281 *p++ = ch;
2282 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002283 }
2284 }
2285 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002286 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002287 s++; /* consume '+' */
2288 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002289 s++;
2290 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00002291 }
2292 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002293 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002294 shiftOutStart = p;
2295 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002296 }
2297 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002298 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002299 *p++ = ch;
2300 s++;
2301 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002302 else {
2303 startinpos = s-starts;
2304 s++;
2305 errmsg = "unexpected special character";
2306 goto utf7Error;
2307 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002308 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002309utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002310 outpos = p-PyUnicode_AS_UNICODE(unicode);
2311 endinpos = s-starts;
2312 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00002313 errors, &errorHandler,
2314 "utf7", errmsg,
2315 &starts, &e, &startinpos, &endinpos, &exc, &s,
2316 &unicode, &outpos, &p))
2317 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002318 }
2319
Antoine Pitrou244651a2009-05-04 18:56:13 +00002320 /* end of string */
2321
2322 if (inShift && !consumed) { /* in shift sequence, no more to follow */
2323 /* if we're in an inconsistent state, that's an error */
2324 if (surrogate ||
2325 (base64bits >= 6) ||
2326 (base64bits > 0 && base64buffer != 0)) {
2327 outpos = p-PyUnicode_AS_UNICODE(unicode);
2328 endinpos = size;
2329 if (unicode_decode_call_errorhandler(
2330 errors, &errorHandler,
2331 "utf7", "unterminated shift sequence",
2332 &starts, &e, &startinpos, &endinpos, &exc, &s,
2333 &unicode, &outpos, &p))
2334 goto onError;
2335 if (s < e)
2336 goto restart;
2337 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002338 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002339
2340 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002341 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00002342 if (inShift) {
2343 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002344 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002345 }
2346 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002347 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002348 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002349 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002350
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00002351 if (_PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002352 goto onError;
2353
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002354 Py_XDECREF(errorHandler);
2355 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002356 return (PyObject *)unicode;
2357
Benjamin Peterson29060642009-01-31 22:14:21 +00002358 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002359 Py_XDECREF(errorHandler);
2360 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002361 Py_DECREF(unicode);
2362 return NULL;
2363}
2364
2365
2366PyObject *PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002367 Py_ssize_t size,
Antoine Pitrou244651a2009-05-04 18:56:13 +00002368 int base64SetO,
2369 int base64WhiteSpace,
Benjamin Peterson29060642009-01-31 22:14:21 +00002370 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002371{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002372 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002373 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00002374 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002375 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002376 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002377 unsigned int base64bits = 0;
2378 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002379 char * out;
2380 char * start;
2381
2382 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00002383 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002384
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00002385 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00002386 return PyErr_NoMemory();
2387
Antoine Pitrou244651a2009-05-04 18:56:13 +00002388 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002389 if (v == NULL)
2390 return NULL;
2391
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002392 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002393 for (;i < size; ++i) {
2394 Py_UNICODE ch = s[i];
2395
Antoine Pitrou244651a2009-05-04 18:56:13 +00002396 if (inShift) {
2397 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
2398 /* shifting out */
2399 if (base64bits) { /* output remaining bits */
2400 *out++ = TO_BASE64(base64buffer << (6-base64bits));
2401 base64buffer = 0;
2402 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002403 }
2404 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002405 /* Characters not in the BASE64 set implicitly unshift the sequence
2406 so no '-' is required, except if the character is itself a '-' */
2407 if (IS_BASE64(ch) || ch == '-') {
2408 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002409 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002410 *out++ = (char) ch;
2411 }
2412 else {
2413 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00002414 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002415 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002416 else { /* not in a shift sequence */
2417 if (ch == '+') {
2418 *out++ = '+';
2419 *out++ = '-';
2420 }
2421 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
2422 *out++ = (char) ch;
2423 }
2424 else {
2425 *out++ = '+';
2426 inShift = 1;
2427 goto encode_char;
2428 }
2429 }
2430 continue;
2431encode_char:
2432#ifdef Py_UNICODE_WIDE
2433 if (ch >= 0x10000) {
2434 /* code first surrogate */
2435 base64bits += 16;
2436 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
2437 while (base64bits >= 6) {
2438 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
2439 base64bits -= 6;
2440 }
2441 /* prepare second surrogate */
2442 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
2443 }
2444#endif
2445 base64bits += 16;
2446 base64buffer = (base64buffer << 16) | ch;
2447 while (base64bits >= 6) {
2448 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
2449 base64bits -= 6;
2450 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00002451 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002452 if (base64bits)
2453 *out++= TO_BASE64(base64buffer << (6-base64bits) );
2454 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002455 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002456 if (_PyBytes_Resize(&v, out - start) < 0)
2457 return NULL;
2458 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002459}
2460
Antoine Pitrou244651a2009-05-04 18:56:13 +00002461#undef IS_BASE64
2462#undef FROM_BASE64
2463#undef TO_BASE64
2464#undef DECODE_DIRECT
2465#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002466
Guido van Rossumd57fd912000-03-10 22:53:23 +00002467/* --- UTF-8 Codec -------------------------------------------------------- */
2468
Tim Petersced69f82003-09-16 20:30:58 +00002469static
Guido van Rossumd57fd912000-03-10 22:53:23 +00002470char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00002471 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
2472 illegal prefix. See RFC 3629 for details */
2473 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
2474 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002475 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00002476 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2477 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2478 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2479 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00002480 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
2481 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 +00002482 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2483 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00002484 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
2485 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
2486 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
2487 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
2488 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 +00002489};
2490
Guido van Rossumd57fd912000-03-10 22:53:23 +00002491PyObject *PyUnicode_DecodeUTF8(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002492 Py_ssize_t size,
2493 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002494{
Walter Dörwald69652032004-09-07 20:24:22 +00002495 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
2496}
2497
Antoine Pitrouab868312009-01-10 15:40:25 +00002498/* Mask to check or force alignment of a pointer to C 'long' boundaries */
2499#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
2500
2501/* Mask to quickly check whether a C 'long' contains a
2502 non-ASCII, UTF8-encoded char. */
2503#if (SIZEOF_LONG == 8)
2504# define ASCII_CHAR_MASK 0x8080808080808080L
2505#elif (SIZEOF_LONG == 4)
2506# define ASCII_CHAR_MASK 0x80808080L
2507#else
2508# error C 'long' size should be either 4 or 8!
2509#endif
2510
Walter Dörwald69652032004-09-07 20:24:22 +00002511PyObject *PyUnicode_DecodeUTF8Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002512 Py_ssize_t size,
2513 const char *errors,
2514 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00002515{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002516 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002517 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00002518 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002519 Py_ssize_t startinpos;
2520 Py_ssize_t endinpos;
2521 Py_ssize_t outpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00002522 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002523 PyUnicodeObject *unicode;
2524 Py_UNICODE *p;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002525 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002526 PyObject *errorHandler = NULL;
2527 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002528
2529 /* Note: size will always be longer than the resulting Unicode
2530 character count */
2531 unicode = _PyUnicode_New(size);
2532 if (!unicode)
2533 return NULL;
Walter Dörwald69652032004-09-07 20:24:22 +00002534 if (size == 0) {
2535 if (consumed)
2536 *consumed = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002537 return (PyObject *)unicode;
Walter Dörwald69652032004-09-07 20:24:22 +00002538 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002539
2540 /* Unpack UTF-8 encoded data */
2541 p = unicode->str;
2542 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00002543 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002544
2545 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002546 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002547
2548 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00002549 /* Fast path for runs of ASCII characters. Given that common UTF-8
2550 input will consist of an overwhelming majority of ASCII
2551 characters, we try to optimize for this case by checking
2552 as many characters as a C 'long' can contain.
2553 First, check if we can do an aligned read, as most CPUs have
2554 a penalty for unaligned reads.
2555 */
2556 if (!((size_t) s & LONG_PTR_MASK)) {
2557 /* Help register allocation */
2558 register const char *_s = s;
2559 register Py_UNICODE *_p = p;
2560 while (_s < aligned_end) {
2561 /* Read a whole long at a time (either 4 or 8 bytes),
2562 and do a fast unrolled copy if it only contains ASCII
2563 characters. */
2564 unsigned long data = *(unsigned long *) _s;
2565 if (data & ASCII_CHAR_MASK)
2566 break;
2567 _p[0] = (unsigned char) _s[0];
2568 _p[1] = (unsigned char) _s[1];
2569 _p[2] = (unsigned char) _s[2];
2570 _p[3] = (unsigned char) _s[3];
2571#if (SIZEOF_LONG == 8)
2572 _p[4] = (unsigned char) _s[4];
2573 _p[5] = (unsigned char) _s[5];
2574 _p[6] = (unsigned char) _s[6];
2575 _p[7] = (unsigned char) _s[7];
2576#endif
2577 _s += SIZEOF_LONG;
2578 _p += SIZEOF_LONG;
2579 }
2580 s = _s;
2581 p = _p;
2582 if (s == e)
2583 break;
2584 ch = (unsigned char)*s;
2585 }
2586 }
2587
2588 if (ch < 0x80) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002589 *p++ = (Py_UNICODE)ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002590 s++;
2591 continue;
2592 }
2593
2594 n = utf8_code_length[ch];
2595
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002596 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002597 if (consumed)
2598 break;
2599 else {
2600 errmsg = "unexpected end of data";
2601 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002602 endinpos = startinpos+1;
2603 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
2604 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00002605 goto utf8Error;
2606 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002607 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002608
2609 switch (n) {
2610
2611 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00002612 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002613 startinpos = s-starts;
2614 endinpos = startinpos+1;
2615 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002616
2617 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002618 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00002619 startinpos = s-starts;
2620 endinpos = startinpos+1;
2621 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002622
2623 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002624 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00002625 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002626 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002627 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00002628 goto utf8Error;
2629 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002630 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00002631 assert ((ch > 0x007F) && (ch <= 0x07FF));
2632 *p++ = (Py_UNICODE)ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002633 break;
2634
2635 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00002636 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
2637 will result in surrogates in range d800-dfff. Surrogates are
2638 not valid UTF-8 so they are rejected.
2639 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
2640 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00002641 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00002642 (s[2] & 0xc0) != 0x80 ||
2643 ((unsigned char)s[0] == 0xE0 &&
2644 (unsigned char)s[1] < 0xA0) ||
2645 ((unsigned char)s[0] == 0xED &&
2646 (unsigned char)s[1] > 0x9F)) {
2647 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002648 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002649 endinpos = startinpos + 1;
2650
2651 /* if s[1] first two bits are 1 and 0, then the invalid
2652 continuation byte is s[2], so increment endinpos by 1,
2653 if not, s[1] is invalid and endinpos doesn't need to
2654 be incremented. */
2655 if ((s[1] & 0xC0) == 0x80)
2656 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00002657 goto utf8Error;
2658 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002659 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00002660 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
2661 *p++ = (Py_UNICODE)ch;
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002662 break;
2663
2664 case 4:
2665 if ((s[1] & 0xc0) != 0x80 ||
2666 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00002667 (s[3] & 0xc0) != 0x80 ||
2668 ((unsigned char)s[0] == 0xF0 &&
2669 (unsigned char)s[1] < 0x90) ||
2670 ((unsigned char)s[0] == 0xF4 &&
2671 (unsigned char)s[1] > 0x8F)) {
2672 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002673 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002674 endinpos = startinpos + 1;
2675 if ((s[1] & 0xC0) == 0x80) {
2676 endinpos++;
2677 if ((s[2] & 0xC0) == 0x80)
2678 endinpos++;
2679 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002680 goto utf8Error;
2681 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002682 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00002683 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
2684 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
2685
Fredrik Lundh8f455852001-06-27 18:59:43 +00002686#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00002687 *p++ = (Py_UNICODE)ch;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002688#else
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002689 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00002690
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002691 /* translate from 10000..10FFFF to 0..FFFF */
2692 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00002693
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002694 /* high surrogate = top 10 bits added to D800 */
2695 *p++ = (Py_UNICODE)(0xD800 + (ch >> 10));
Tim Petersced69f82003-09-16 20:30:58 +00002696
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002697 /* low surrogate = bottom 10 bits added to DC00 */
Fredrik Lundh45714e92001-06-26 16:39:36 +00002698 *p++ = (Py_UNICODE)(0xDC00 + (ch & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002699#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00002700 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002701 }
2702 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00002703 continue;
Tim Petersced69f82003-09-16 20:30:58 +00002704
Benjamin Peterson29060642009-01-31 22:14:21 +00002705 utf8Error:
2706 outpos = p-PyUnicode_AS_UNICODE(unicode);
2707 if (unicode_decode_call_errorhandler(
2708 errors, &errorHandler,
2709 "utf8", errmsg,
2710 &starts, &e, &startinpos, &endinpos, &exc, &s,
2711 &unicode, &outpos, &p))
2712 goto onError;
2713 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002714 }
Walter Dörwald69652032004-09-07 20:24:22 +00002715 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00002716 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002717
2718 /* Adjust length */
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00002719 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002720 goto onError;
2721
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002722 Py_XDECREF(errorHandler);
2723 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002724 return (PyObject *)unicode;
2725
Benjamin Peterson29060642009-01-31 22:14:21 +00002726 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002727 Py_XDECREF(errorHandler);
2728 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002729 Py_DECREF(unicode);
2730 return NULL;
2731}
2732
Antoine Pitrouab868312009-01-10 15:40:25 +00002733#undef ASCII_CHAR_MASK
2734
Victor Stinnerf933e1a2010-10-20 22:58:25 +00002735#ifdef __APPLE__
2736
2737/* Simplified UTF-8 decoder using surrogateescape error handler,
2738 used to decode the command line arguments on Mac OS X. */
2739
2740wchar_t*
2741_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
2742{
2743 int n;
2744 const char *e;
2745 wchar_t *unicode, *p;
2746
2747 /* Note: size will always be longer than the resulting Unicode
2748 character count */
2749 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
2750 PyErr_NoMemory();
2751 return NULL;
2752 }
2753 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
2754 if (!unicode)
2755 return NULL;
2756
2757 /* Unpack UTF-8 encoded data */
2758 p = unicode;
2759 e = s + size;
2760 while (s < e) {
2761 Py_UCS4 ch = (unsigned char)*s;
2762
2763 if (ch < 0x80) {
2764 *p++ = (wchar_t)ch;
2765 s++;
2766 continue;
2767 }
2768
2769 n = utf8_code_length[ch];
2770 if (s + n > e) {
2771 goto surrogateescape;
2772 }
2773
2774 switch (n) {
2775 case 0:
2776 case 1:
2777 goto surrogateescape;
2778
2779 case 2:
2780 if ((s[1] & 0xc0) != 0x80)
2781 goto surrogateescape;
2782 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
2783 assert ((ch > 0x007F) && (ch <= 0x07FF));
2784 *p++ = (wchar_t)ch;
2785 break;
2786
2787 case 3:
2788 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
2789 will result in surrogates in range d800-dfff. Surrogates are
2790 not valid UTF-8 so they are rejected.
2791 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
2792 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
2793 if ((s[1] & 0xc0) != 0x80 ||
2794 (s[2] & 0xc0) != 0x80 ||
2795 ((unsigned char)s[0] == 0xE0 &&
2796 (unsigned char)s[1] < 0xA0) ||
2797 ((unsigned char)s[0] == 0xED &&
2798 (unsigned char)s[1] > 0x9F)) {
2799
2800 goto surrogateescape;
2801 }
2802 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
2803 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
2804 *p++ = (Py_UNICODE)ch;
2805 break;
2806
2807 case 4:
2808 if ((s[1] & 0xc0) != 0x80 ||
2809 (s[2] & 0xc0) != 0x80 ||
2810 (s[3] & 0xc0) != 0x80 ||
2811 ((unsigned char)s[0] == 0xF0 &&
2812 (unsigned char)s[1] < 0x90) ||
2813 ((unsigned char)s[0] == 0xF4 &&
2814 (unsigned char)s[1] > 0x8F)) {
2815 goto surrogateescape;
2816 }
2817 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
2818 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
2819 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
2820
2821#if SIZEOF_WCHAR_T == 4
2822 *p++ = (wchar_t)ch;
2823#else
2824 /* compute and append the two surrogates: */
2825
2826 /* translate from 10000..10FFFF to 0..FFFF */
2827 ch -= 0x10000;
2828
2829 /* high surrogate = top 10 bits added to D800 */
2830 *p++ = (wchar_t)(0xD800 + (ch >> 10));
2831
2832 /* low surrogate = bottom 10 bits added to DC00 */
2833 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
2834#endif
2835 break;
2836 }
2837 s += n;
2838 continue;
2839
2840 surrogateescape:
2841 *p++ = 0xDC00 + ch;
2842 s++;
2843 }
2844 *p = L'\0';
2845 return unicode;
2846}
2847
2848#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00002849
Tim Peters602f7402002-04-27 18:03:26 +00002850/* Allocation strategy: if the string is short, convert into a stack buffer
2851 and allocate exactly as much space needed at the end. Else allocate the
2852 maximum possible needed (4 result bytes per Unicode character), and return
2853 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002854*/
Tim Peters7e3d9612002-04-21 03:26:37 +00002855PyObject *
2856PyUnicode_EncodeUTF8(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002857 Py_ssize_t size,
2858 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002859{
Tim Peters602f7402002-04-27 18:03:26 +00002860#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00002861
Guido van Rossum98297ee2007-11-06 21:34:58 +00002862 Py_ssize_t i; /* index into s of next input byte */
2863 PyObject *result; /* result string object */
2864 char *p; /* next free byte in output buffer */
2865 Py_ssize_t nallocated; /* number of result bytes allocated */
2866 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00002867 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002868 PyObject *errorHandler = NULL;
2869 PyObject *exc = NULL;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00002870
Tim Peters602f7402002-04-27 18:03:26 +00002871 assert(s != NULL);
2872 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002873
Tim Peters602f7402002-04-27 18:03:26 +00002874 if (size <= MAX_SHORT_UNICHARS) {
2875 /* Write into the stack buffer; nallocated can't overflow.
2876 * At the end, we'll allocate exactly as much heap space as it
2877 * turns out we need.
2878 */
2879 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002880 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00002881 p = stackbuf;
2882 }
2883 else {
2884 /* Overallocate on the heap, and give the excess back at the end. */
2885 nallocated = size * 4;
2886 if (nallocated / 4 != size) /* overflow! */
2887 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00002888 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002889 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00002890 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00002891 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00002892 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002893
Tim Peters602f7402002-04-27 18:03:26 +00002894 for (i = 0; i < size;) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002895 Py_UCS4 ch = s[i++];
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002896
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002897 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00002898 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002899 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002900
Guido van Rossumd57fd912000-03-10 22:53:23 +00002901 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00002902 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00002903 *p++ = (char)(0xc0 | (ch >> 6));
2904 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00002905 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002906#ifndef Py_UNICODE_WIDE
Victor Stinner31be90b2010-04-22 19:38:16 +00002907 /* Special case: check for high and low surrogate */
2908 if (ch <= 0xDBFF && i != size && 0xDC00 <= s[i] && s[i] <= 0xDFFF) {
2909 Py_UCS4 ch2 = s[i];
2910 /* Combine the two surrogates to form a UCS4 value */
2911 ch = ((ch - 0xD800) << 10 | (ch2 - 0xDC00)) + 0x10000;
2912 i++;
2913
2914 /* Encode UCS4 Unicode ordinals */
2915 *p++ = (char)(0xf0 | (ch >> 18));
2916 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
Tim Peters602f7402002-04-27 18:03:26 +00002917 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2918 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00002919 } else {
Victor Stinner445a6232010-04-22 20:01:57 +00002920#endif
Victor Stinner31be90b2010-04-22 19:38:16 +00002921 Py_ssize_t newpos;
2922 PyObject *rep;
2923 Py_ssize_t repsize, k;
2924 rep = unicode_encode_call_errorhandler
2925 (errors, &errorHandler, "utf-8", "surrogates not allowed",
2926 s, size, &exc, i-1, i, &newpos);
2927 if (!rep)
2928 goto error;
2929
2930 if (PyBytes_Check(rep))
2931 repsize = PyBytes_GET_SIZE(rep);
2932 else
2933 repsize = PyUnicode_GET_SIZE(rep);
2934
2935 if (repsize > 4) {
2936 Py_ssize_t offset;
2937
2938 if (result == NULL)
2939 offset = p - stackbuf;
2940 else
2941 offset = p - PyBytes_AS_STRING(result);
2942
2943 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
2944 /* integer overflow */
2945 PyErr_NoMemory();
2946 goto error;
2947 }
2948 nallocated += repsize - 4;
2949 if (result != NULL) {
2950 if (_PyBytes_Resize(&result, nallocated) < 0)
2951 goto error;
2952 } else {
2953 result = PyBytes_FromStringAndSize(NULL, nallocated);
2954 if (result == NULL)
2955 goto error;
2956 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
2957 }
2958 p = PyBytes_AS_STRING(result) + offset;
2959 }
2960
2961 if (PyBytes_Check(rep)) {
2962 char *prep = PyBytes_AS_STRING(rep);
2963 for(k = repsize; k > 0; k--)
2964 *p++ = *prep++;
2965 } else /* rep is unicode */ {
2966 Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
2967 Py_UNICODE c;
2968
2969 for(k=0; k<repsize; k++) {
2970 c = prep[k];
2971 if (0x80 <= c) {
2972 raise_encode_exception(&exc, "utf-8", s, size,
2973 i-1, i, "surrogates not allowed");
2974 goto error;
2975 }
2976 *p++ = (char)prep[k];
2977 }
2978 }
2979 Py_DECREF(rep);
Victor Stinner445a6232010-04-22 20:01:57 +00002980#ifndef Py_UNICODE_WIDE
Victor Stinner31be90b2010-04-22 19:38:16 +00002981 }
Victor Stinner445a6232010-04-22 20:01:57 +00002982#endif
Victor Stinner31be90b2010-04-22 19:38:16 +00002983 } else if (ch < 0x10000) {
2984 *p++ = (char)(0xe0 | (ch >> 12));
2985 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2986 *p++ = (char)(0x80 | (ch & 0x3f));
2987 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00002988 /* Encode UCS4 Unicode ordinals */
2989 *p++ = (char)(0xf0 | (ch >> 18));
2990 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
2991 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2992 *p++ = (char)(0x80 | (ch & 0x3f));
2993 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002994 }
Tim Peters0eca65c2002-04-21 17:28:06 +00002995
Guido van Rossum98297ee2007-11-06 21:34:58 +00002996 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00002997 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002998 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00002999 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00003000 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00003001 }
3002 else {
Christian Heimesf3863112007-11-22 07:46:41 +00003003 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00003004 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00003005 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00003006 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00003007 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00003008 Py_XDECREF(errorHandler);
3009 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003010 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00003011 error:
3012 Py_XDECREF(errorHandler);
3013 Py_XDECREF(exc);
3014 Py_XDECREF(result);
3015 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00003016
Tim Peters602f7402002-04-27 18:03:26 +00003017#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00003018}
3019
Guido van Rossumd57fd912000-03-10 22:53:23 +00003020PyObject *PyUnicode_AsUTF8String(PyObject *unicode)
3021{
Guido van Rossumd57fd912000-03-10 22:53:23 +00003022 if (!PyUnicode_Check(unicode)) {
3023 PyErr_BadArgument();
3024 return NULL;
3025 }
Barry Warsaw2dd4abf2000-08-18 06:58:15 +00003026 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003027 PyUnicode_GET_SIZE(unicode),
3028 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003029}
3030
Walter Dörwald41980ca2007-08-16 21:55:45 +00003031/* --- UTF-32 Codec ------------------------------------------------------- */
3032
3033PyObject *
3034PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003035 Py_ssize_t size,
3036 const char *errors,
3037 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00003038{
3039 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
3040}
3041
3042PyObject *
3043PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003044 Py_ssize_t size,
3045 const char *errors,
3046 int *byteorder,
3047 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00003048{
3049 const char *starts = s;
3050 Py_ssize_t startinpos;
3051 Py_ssize_t endinpos;
3052 Py_ssize_t outpos;
3053 PyUnicodeObject *unicode;
3054 Py_UNICODE *p;
3055#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00003056 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00003057 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003058#else
3059 const int pairs = 0;
3060#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00003061 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003062 int bo = 0; /* assume native ordering by default */
3063 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00003064 /* Offsets from q for retrieving bytes in the right order. */
3065#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3066 int iorder[] = {0, 1, 2, 3};
3067#else
3068 int iorder[] = {3, 2, 1, 0};
3069#endif
3070 PyObject *errorHandler = NULL;
3071 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00003072
Walter Dörwald41980ca2007-08-16 21:55:45 +00003073 q = (unsigned char *)s;
3074 e = q + size;
3075
3076 if (byteorder)
3077 bo = *byteorder;
3078
3079 /* Check for BOM marks (U+FEFF) in the input and adjust current
3080 byte order setting accordingly. In native mode, the leading BOM
3081 mark is skipped, in all other modes, it is copied to the output
3082 stream as-is (giving a ZWNBSP character). */
3083 if (bo == 0) {
3084 if (size >= 4) {
3085 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00003086 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00003087#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00003088 if (bom == 0x0000FEFF) {
3089 q += 4;
3090 bo = -1;
3091 }
3092 else if (bom == 0xFFFE0000) {
3093 q += 4;
3094 bo = 1;
3095 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003096#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003097 if (bom == 0x0000FEFF) {
3098 q += 4;
3099 bo = 1;
3100 }
3101 else if (bom == 0xFFFE0000) {
3102 q += 4;
3103 bo = -1;
3104 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003105#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003106 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003107 }
3108
3109 if (bo == -1) {
3110 /* force LE */
3111 iorder[0] = 0;
3112 iorder[1] = 1;
3113 iorder[2] = 2;
3114 iorder[3] = 3;
3115 }
3116 else if (bo == 1) {
3117 /* force BE */
3118 iorder[0] = 3;
3119 iorder[1] = 2;
3120 iorder[2] = 1;
3121 iorder[3] = 0;
3122 }
3123
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00003124 /* On narrow builds we split characters outside the BMP into two
3125 codepoints => count how much extra space we need. */
3126#ifndef Py_UNICODE_WIDE
3127 for (qq = q; qq < e; qq += 4)
3128 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
3129 pairs++;
3130#endif
3131
3132 /* This might be one to much, because of a BOM */
3133 unicode = _PyUnicode_New((size+3)/4+pairs);
3134 if (!unicode)
3135 return NULL;
3136 if (size == 0)
3137 return (PyObject *)unicode;
3138
3139 /* Unpack UTF-32 encoded data */
3140 p = unicode->str;
3141
Walter Dörwald41980ca2007-08-16 21:55:45 +00003142 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003143 Py_UCS4 ch;
3144 /* remaining bytes at the end? (size should be divisible by 4) */
3145 if (e-q<4) {
3146 if (consumed)
3147 break;
3148 errmsg = "truncated data";
3149 startinpos = ((const char *)q)-starts;
3150 endinpos = ((const char *)e)-starts;
3151 goto utf32Error;
3152 /* The remaining input chars are ignored if the callback
3153 chooses to skip the input */
3154 }
3155 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
3156 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00003157
Benjamin Peterson29060642009-01-31 22:14:21 +00003158 if (ch >= 0x110000)
3159 {
3160 errmsg = "codepoint not in range(0x110000)";
3161 startinpos = ((const char *)q)-starts;
3162 endinpos = startinpos+4;
3163 goto utf32Error;
3164 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003165#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003166 if (ch >= 0x10000)
3167 {
3168 *p++ = 0xD800 | ((ch-0x10000) >> 10);
3169 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
3170 }
3171 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00003172#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003173 *p++ = ch;
3174 q += 4;
3175 continue;
3176 utf32Error:
3177 outpos = p-PyUnicode_AS_UNICODE(unicode);
3178 if (unicode_decode_call_errorhandler(
3179 errors, &errorHandler,
3180 "utf32", errmsg,
3181 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
3182 &unicode, &outpos, &p))
3183 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003184 }
3185
3186 if (byteorder)
3187 *byteorder = bo;
3188
3189 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00003190 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003191
3192 /* Adjust length */
3193 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
3194 goto onError;
3195
3196 Py_XDECREF(errorHandler);
3197 Py_XDECREF(exc);
3198 return (PyObject *)unicode;
3199
Benjamin Peterson29060642009-01-31 22:14:21 +00003200 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00003201 Py_DECREF(unicode);
3202 Py_XDECREF(errorHandler);
3203 Py_XDECREF(exc);
3204 return NULL;
3205}
3206
3207PyObject *
3208PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003209 Py_ssize_t size,
3210 const char *errors,
3211 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00003212{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003213 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003214 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003215 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003216#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003217 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003218#else
3219 const int pairs = 0;
3220#endif
3221 /* Offsets from p for storing byte pairs in the right order. */
3222#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3223 int iorder[] = {0, 1, 2, 3};
3224#else
3225 int iorder[] = {3, 2, 1, 0};
3226#endif
3227
Benjamin Peterson29060642009-01-31 22:14:21 +00003228#define STORECHAR(CH) \
3229 do { \
3230 p[iorder[3]] = ((CH) >> 24) & 0xff; \
3231 p[iorder[2]] = ((CH) >> 16) & 0xff; \
3232 p[iorder[1]] = ((CH) >> 8) & 0xff; \
3233 p[iorder[0]] = (CH) & 0xff; \
3234 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00003235 } while(0)
3236
3237 /* In narrow builds we can output surrogate pairs as one codepoint,
3238 so we need less space. */
3239#ifndef Py_UNICODE_WIDE
3240 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00003241 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
3242 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
3243 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003244#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003245 nsize = (size - pairs + (byteorder == 0));
3246 bytesize = nsize * 4;
3247 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003248 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003249 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003250 if (v == NULL)
3251 return NULL;
3252
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003253 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003254 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003255 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003256 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00003257 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003258
3259 if (byteorder == -1) {
3260 /* force LE */
3261 iorder[0] = 0;
3262 iorder[1] = 1;
3263 iorder[2] = 2;
3264 iorder[3] = 3;
3265 }
3266 else if (byteorder == 1) {
3267 /* force BE */
3268 iorder[0] = 3;
3269 iorder[1] = 2;
3270 iorder[2] = 1;
3271 iorder[3] = 0;
3272 }
3273
3274 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003275 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003276#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003277 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
3278 Py_UCS4 ch2 = *s;
3279 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
3280 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
3281 s++;
3282 size--;
3283 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00003284 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003285#endif
3286 STORECHAR(ch);
3287 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003288
3289 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003290 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003291#undef STORECHAR
3292}
3293
3294PyObject *PyUnicode_AsUTF32String(PyObject *unicode)
3295{
3296 if (!PyUnicode_Check(unicode)) {
3297 PyErr_BadArgument();
3298 return NULL;
3299 }
3300 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003301 PyUnicode_GET_SIZE(unicode),
3302 NULL,
3303 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003304}
3305
Guido van Rossumd57fd912000-03-10 22:53:23 +00003306/* --- UTF-16 Codec ------------------------------------------------------- */
3307
Tim Peters772747b2001-08-09 22:21:55 +00003308PyObject *
3309PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003310 Py_ssize_t size,
3311 const char *errors,
3312 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003313{
Walter Dörwald69652032004-09-07 20:24:22 +00003314 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
3315}
3316
Antoine Pitrouab868312009-01-10 15:40:25 +00003317/* Two masks for fast checking of whether a C 'long' may contain
3318 UTF16-encoded surrogate characters. This is an efficient heuristic,
3319 assuming that non-surrogate characters with a code point >= 0x8000 are
3320 rare in most input.
3321 FAST_CHAR_MASK is used when the input is in native byte ordering,
3322 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00003323*/
Antoine Pitrouab868312009-01-10 15:40:25 +00003324#if (SIZEOF_LONG == 8)
3325# define FAST_CHAR_MASK 0x8000800080008000L
3326# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
3327#elif (SIZEOF_LONG == 4)
3328# define FAST_CHAR_MASK 0x80008000L
3329# define SWAPPED_FAST_CHAR_MASK 0x00800080L
3330#else
3331# error C 'long' size should be either 4 or 8!
3332#endif
3333
Walter Dörwald69652032004-09-07 20:24:22 +00003334PyObject *
3335PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003336 Py_ssize_t size,
3337 const char *errors,
3338 int *byteorder,
3339 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00003340{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003341 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003342 Py_ssize_t startinpos;
3343 Py_ssize_t endinpos;
3344 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003345 PyUnicodeObject *unicode;
3346 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00003347 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00003348 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00003349 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003350 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00003351 /* Offsets from q for retrieving byte pairs in the right order. */
3352#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3353 int ihi = 1, ilo = 0;
3354#else
3355 int ihi = 0, ilo = 1;
3356#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003357 PyObject *errorHandler = NULL;
3358 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003359
3360 /* Note: size will always be longer than the resulting Unicode
3361 character count */
3362 unicode = _PyUnicode_New(size);
3363 if (!unicode)
3364 return NULL;
3365 if (size == 0)
3366 return (PyObject *)unicode;
3367
3368 /* Unpack UTF-16 encoded data */
3369 p = unicode->str;
Tim Peters772747b2001-08-09 22:21:55 +00003370 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00003371 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003372
3373 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00003374 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003375
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003376 /* Check for BOM marks (U+FEFF) in the input and adjust current
3377 byte order setting accordingly. In native mode, the leading BOM
3378 mark is skipped, in all other modes, it is copied to the output
3379 stream as-is (giving a ZWNBSP character). */
3380 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00003381 if (size >= 2) {
3382 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003383#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00003384 if (bom == 0xFEFF) {
3385 q += 2;
3386 bo = -1;
3387 }
3388 else if (bom == 0xFFFE) {
3389 q += 2;
3390 bo = 1;
3391 }
Tim Petersced69f82003-09-16 20:30:58 +00003392#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003393 if (bom == 0xFEFF) {
3394 q += 2;
3395 bo = 1;
3396 }
3397 else if (bom == 0xFFFE) {
3398 q += 2;
3399 bo = -1;
3400 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003401#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003402 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003403 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003404
Tim Peters772747b2001-08-09 22:21:55 +00003405 if (bo == -1) {
3406 /* force LE */
3407 ihi = 1;
3408 ilo = 0;
3409 }
3410 else if (bo == 1) {
3411 /* force BE */
3412 ihi = 0;
3413 ilo = 1;
3414 }
Antoine Pitrouab868312009-01-10 15:40:25 +00003415#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3416 native_ordering = ilo < ihi;
3417#else
3418 native_ordering = ilo > ihi;
3419#endif
Tim Peters772747b2001-08-09 22:21:55 +00003420
Antoine Pitrouab868312009-01-10 15:40:25 +00003421 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00003422 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003423 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00003424 /* First check for possible aligned read of a C 'long'. Unaligned
3425 reads are more expensive, better to defer to another iteration. */
3426 if (!((size_t) q & LONG_PTR_MASK)) {
3427 /* Fast path for runs of non-surrogate chars. */
3428 register const unsigned char *_q = q;
3429 Py_UNICODE *_p = p;
3430 if (native_ordering) {
3431 /* Native ordering is simple: as long as the input cannot
3432 possibly contain a surrogate char, do an unrolled copy
3433 of several 16-bit code points to the target object.
3434 The non-surrogate check is done on several input bytes
3435 at a time (as many as a C 'long' can contain). */
3436 while (_q < aligned_end) {
3437 unsigned long data = * (unsigned long *) _q;
3438 if (data & FAST_CHAR_MASK)
3439 break;
3440 _p[0] = ((unsigned short *) _q)[0];
3441 _p[1] = ((unsigned short *) _q)[1];
3442#if (SIZEOF_LONG == 8)
3443 _p[2] = ((unsigned short *) _q)[2];
3444 _p[3] = ((unsigned short *) _q)[3];
3445#endif
3446 _q += SIZEOF_LONG;
3447 _p += SIZEOF_LONG / 2;
3448 }
3449 }
3450 else {
3451 /* Byteswapped ordering is similar, but we must decompose
3452 the copy bytewise, and take care of zero'ing out the
3453 upper bytes if the target object is in 32-bit units
3454 (that is, in UCS-4 builds). */
3455 while (_q < aligned_end) {
3456 unsigned long data = * (unsigned long *) _q;
3457 if (data & SWAPPED_FAST_CHAR_MASK)
3458 break;
3459 /* Zero upper bytes in UCS-4 builds */
3460#if (Py_UNICODE_SIZE > 2)
3461 _p[0] = 0;
3462 _p[1] = 0;
3463#if (SIZEOF_LONG == 8)
3464 _p[2] = 0;
3465 _p[3] = 0;
3466#endif
3467#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00003468 /* Issue #4916; UCS-4 builds on big endian machines must
3469 fill the two last bytes of each 4-byte unit. */
3470#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
3471# define OFF 2
3472#else
3473# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00003474#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00003475 ((unsigned char *) _p)[OFF + 1] = _q[0];
3476 ((unsigned char *) _p)[OFF + 0] = _q[1];
3477 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
3478 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
3479#if (SIZEOF_LONG == 8)
3480 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
3481 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
3482 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
3483 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
3484#endif
3485#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00003486 _q += SIZEOF_LONG;
3487 _p += SIZEOF_LONG / 2;
3488 }
3489 }
3490 p = _p;
3491 q = _q;
3492 if (q >= e)
3493 break;
3494 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003495 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003496
Benjamin Peterson14339b62009-01-31 16:36:08 +00003497 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00003498
3499 if (ch < 0xD800 || ch > 0xDFFF) {
3500 *p++ = ch;
3501 continue;
3502 }
3503
3504 /* UTF-16 code pair: */
3505 if (q > e) {
3506 errmsg = "unexpected end of data";
3507 startinpos = (((const char *)q) - 2) - starts;
3508 endinpos = ((const char *)e) + 1 - starts;
3509 goto utf16Error;
3510 }
3511 if (0xD800 <= ch && ch <= 0xDBFF) {
3512 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
3513 q += 2;
3514 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00003515#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003516 *p++ = ch;
3517 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003518#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003519 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003520#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003521 continue;
3522 }
3523 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003524 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00003525 startinpos = (((const char *)q)-4)-starts;
3526 endinpos = startinpos+2;
3527 goto utf16Error;
3528 }
3529
Benjamin Peterson14339b62009-01-31 16:36:08 +00003530 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003531 errmsg = "illegal encoding";
3532 startinpos = (((const char *)q)-2)-starts;
3533 endinpos = startinpos+2;
3534 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003535
Benjamin Peterson29060642009-01-31 22:14:21 +00003536 utf16Error:
3537 outpos = p - PyUnicode_AS_UNICODE(unicode);
3538 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00003539 errors,
3540 &errorHandler,
3541 "utf16", errmsg,
3542 &starts,
3543 (const char **)&e,
3544 &startinpos,
3545 &endinpos,
3546 &exc,
3547 (const char **)&q,
3548 &unicode,
3549 &outpos,
3550 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00003551 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003552 }
Antoine Pitrouab868312009-01-10 15:40:25 +00003553 /* remaining byte at the end? (size should be even) */
3554 if (e == q) {
3555 if (!consumed) {
3556 errmsg = "truncated data";
3557 startinpos = ((const char *)q) - starts;
3558 endinpos = ((const char *)e) + 1 - starts;
3559 outpos = p - PyUnicode_AS_UNICODE(unicode);
3560 if (unicode_decode_call_errorhandler(
3561 errors,
3562 &errorHandler,
3563 "utf16", errmsg,
3564 &starts,
3565 (const char **)&e,
3566 &startinpos,
3567 &endinpos,
3568 &exc,
3569 (const char **)&q,
3570 &unicode,
3571 &outpos,
3572 &p))
3573 goto onError;
3574 /* The remaining input chars are ignored if the callback
3575 chooses to skip the input */
3576 }
3577 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003578
3579 if (byteorder)
3580 *byteorder = bo;
3581
Walter Dörwald69652032004-09-07 20:24:22 +00003582 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00003583 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00003584
Guido van Rossumd57fd912000-03-10 22:53:23 +00003585 /* Adjust length */
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00003586 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003587 goto onError;
3588
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003589 Py_XDECREF(errorHandler);
3590 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003591 return (PyObject *)unicode;
3592
Benjamin Peterson29060642009-01-31 22:14:21 +00003593 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003594 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003595 Py_XDECREF(errorHandler);
3596 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003597 return NULL;
3598}
3599
Antoine Pitrouab868312009-01-10 15:40:25 +00003600#undef FAST_CHAR_MASK
3601#undef SWAPPED_FAST_CHAR_MASK
3602
Tim Peters772747b2001-08-09 22:21:55 +00003603PyObject *
3604PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003605 Py_ssize_t size,
3606 const char *errors,
3607 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003608{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003609 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00003610 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003611 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003612#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003613 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003614#else
3615 const int pairs = 0;
3616#endif
Tim Peters772747b2001-08-09 22:21:55 +00003617 /* Offsets from p for storing byte pairs in the right order. */
3618#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3619 int ihi = 1, ilo = 0;
3620#else
3621 int ihi = 0, ilo = 1;
3622#endif
3623
Benjamin Peterson29060642009-01-31 22:14:21 +00003624#define STORECHAR(CH) \
3625 do { \
3626 p[ihi] = ((CH) >> 8) & 0xff; \
3627 p[ilo] = (CH) & 0xff; \
3628 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00003629 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003630
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003631#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003632 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00003633 if (s[i] >= 0x10000)
3634 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003635#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003636 /* 2 * (size + pairs + (byteorder == 0)) */
3637 if (size > PY_SSIZE_T_MAX ||
3638 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00003639 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003640 nsize = size + pairs + (byteorder == 0);
3641 bytesize = nsize * 2;
3642 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003643 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003644 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003645 if (v == NULL)
3646 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003647
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003648 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003649 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003650 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00003651 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00003652 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00003653
3654 if (byteorder == -1) {
3655 /* force LE */
3656 ihi = 1;
3657 ilo = 0;
3658 }
3659 else if (byteorder == 1) {
3660 /* force BE */
3661 ihi = 0;
3662 ilo = 1;
3663 }
3664
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003665 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003666 Py_UNICODE ch = *s++;
3667 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003668#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003669 if (ch >= 0x10000) {
3670 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
3671 ch = 0xD800 | ((ch-0x10000) >> 10);
3672 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003673#endif
Tim Peters772747b2001-08-09 22:21:55 +00003674 STORECHAR(ch);
3675 if (ch2)
3676 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003677 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003678
3679 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003680 return v;
Tim Peters772747b2001-08-09 22:21:55 +00003681#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00003682}
3683
3684PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
3685{
3686 if (!PyUnicode_Check(unicode)) {
3687 PyErr_BadArgument();
3688 return NULL;
3689 }
3690 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003691 PyUnicode_GET_SIZE(unicode),
3692 NULL,
3693 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003694}
3695
3696/* --- Unicode Escape Codec ----------------------------------------------- */
3697
Fredrik Lundh06d12682001-01-24 07:59:11 +00003698static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00003699
Guido van Rossumd57fd912000-03-10 22:53:23 +00003700PyObject *PyUnicode_DecodeUnicodeEscape(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003701 Py_ssize_t size,
3702 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003703{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003704 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003705 Py_ssize_t startinpos;
3706 Py_ssize_t endinpos;
3707 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003708 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003709 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003710 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003711 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003712 char* message;
3713 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003714 PyObject *errorHandler = NULL;
3715 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003716
Guido van Rossumd57fd912000-03-10 22:53:23 +00003717 /* Escaped strings will always be longer than the resulting
3718 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003719 length after conversion to the true value.
3720 (but if the error callback returns a long replacement string
3721 we'll have to allocate more space) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003722 v = _PyUnicode_New(size);
3723 if (v == NULL)
3724 goto onError;
3725 if (size == 0)
3726 return (PyObject *)v;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003727
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003728 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003729 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003730
Guido van Rossumd57fd912000-03-10 22:53:23 +00003731 while (s < end) {
3732 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00003733 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003734 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003735
3736 /* Non-escape characters are interpreted as Unicode ordinals */
3737 if (*s != '\\') {
Fredrik Lundhccc74732001-02-18 22:13:49 +00003738 *p++ = (unsigned char) *s++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003739 continue;
3740 }
3741
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003742 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003743 /* \ - Escapes */
3744 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003745 c = *s++;
3746 if (s > end)
3747 c = '\0'; /* Invalid after \ */
3748 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003749
Benjamin Peterson29060642009-01-31 22:14:21 +00003750 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003751 case '\n': break;
3752 case '\\': *p++ = '\\'; break;
3753 case '\'': *p++ = '\''; break;
3754 case '\"': *p++ = '\"'; break;
3755 case 'b': *p++ = '\b'; break;
3756 case 'f': *p++ = '\014'; break; /* FF */
3757 case 't': *p++ = '\t'; break;
3758 case 'n': *p++ = '\n'; break;
3759 case 'r': *p++ = '\r'; break;
3760 case 'v': *p++ = '\013'; break; /* VT */
3761 case 'a': *p++ = '\007'; break; /* BEL, not classic C */
3762
Benjamin Peterson29060642009-01-31 22:14:21 +00003763 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003764 case '0': case '1': case '2': case '3':
3765 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003766 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003767 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003768 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003769 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003770 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00003771 }
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003772 *p++ = x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003773 break;
3774
Benjamin Peterson29060642009-01-31 22:14:21 +00003775 /* hex escapes */
3776 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003777 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003778 digits = 2;
3779 message = "truncated \\xXX escape";
3780 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003781
Benjamin Peterson29060642009-01-31 22:14:21 +00003782 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003783 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003784 digits = 4;
3785 message = "truncated \\uXXXX escape";
3786 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003787
Benjamin Peterson29060642009-01-31 22:14:21 +00003788 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00003789 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003790 digits = 8;
3791 message = "truncated \\UXXXXXXXX escape";
3792 hexescape:
3793 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003794 outpos = p-PyUnicode_AS_UNICODE(v);
3795 if (s+digits>end) {
3796 endinpos = size;
3797 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003798 errors, &errorHandler,
3799 "unicodeescape", "end of string in escape sequence",
3800 &starts, &end, &startinpos, &endinpos, &exc, &s,
3801 &v, &outpos, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003802 goto onError;
3803 goto nextByte;
3804 }
3805 for (i = 0; i < digits; ++i) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00003806 c = (unsigned char) s[i];
David Malcolm96960882010-11-05 17:23:41 +00003807 if (!Py_ISXDIGIT(c)) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003808 endinpos = (s+i+1)-starts;
3809 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003810 errors, &errorHandler,
3811 "unicodeescape", message,
3812 &starts, &end, &startinpos, &endinpos, &exc, &s,
3813 &v, &outpos, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00003814 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003815 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00003816 }
3817 chr = (chr<<4) & ~0xF;
3818 if (c >= '0' && c <= '9')
3819 chr += c - '0';
3820 else if (c >= 'a' && c <= 'f')
3821 chr += 10 + c - 'a';
3822 else
3823 chr += 10 + c - 'A';
3824 }
3825 s += i;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00003826 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003827 /* _decoding_error will have already written into the
3828 target buffer. */
3829 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003830 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00003831 /* when we get here, chr is a 32-bit unicode character */
3832 if (chr <= 0xffff)
3833 /* UCS-2 character */
3834 *p++ = (Py_UNICODE) chr;
3835 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00003836 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00003837 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00003838#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003839 *p++ = chr;
3840#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00003841 chr -= 0x10000L;
3842 *p++ = 0xD800 + (Py_UNICODE) (chr >> 10);
Fredrik Lundh45714e92001-06-26 16:39:36 +00003843 *p++ = 0xDC00 + (Py_UNICODE) (chr & 0x03FF);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003844#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00003845 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003846 endinpos = s-starts;
3847 outpos = p-PyUnicode_AS_UNICODE(v);
3848 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003849 errors, &errorHandler,
3850 "unicodeescape", "illegal Unicode character",
3851 &starts, &end, &startinpos, &endinpos, &exc, &s,
3852 &v, &outpos, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00003853 goto onError;
3854 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00003855 break;
3856
Benjamin Peterson29060642009-01-31 22:14:21 +00003857 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00003858 case 'N':
3859 message = "malformed \\N character escape";
3860 if (ucnhash_CAPI == NULL) {
3861 /* load the unicode data module */
Benjamin Petersonb173f782009-05-05 22:31:58 +00003862 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00003863 if (ucnhash_CAPI == NULL)
3864 goto ucnhashError;
3865 }
3866 if (*s == '{') {
3867 const char *start = s+1;
3868 /* look for the closing brace */
3869 while (*s != '}' && s < end)
3870 s++;
3871 if (s > start && s < end && *s == '}') {
3872 /* found a name. look it up in the unicode database */
3873 message = "unknown Unicode character name";
3874 s++;
Martin v. Löwis480f1bb2006-03-09 23:38:20 +00003875 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1), &chr))
Fredrik Lundhccc74732001-02-18 22:13:49 +00003876 goto store;
3877 }
3878 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003879 endinpos = s-starts;
3880 outpos = p-PyUnicode_AS_UNICODE(v);
3881 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003882 errors, &errorHandler,
3883 "unicodeescape", message,
3884 &starts, &end, &startinpos, &endinpos, &exc, &s,
3885 &v, &outpos, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00003886 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003887 break;
3888
3889 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00003890 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003891 message = "\\ at end of string";
3892 s--;
3893 endinpos = s-starts;
3894 outpos = p-PyUnicode_AS_UNICODE(v);
3895 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003896 errors, &errorHandler,
3897 "unicodeescape", message,
3898 &starts, &end, &startinpos, &endinpos, &exc, &s,
3899 &v, &outpos, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00003900 goto onError;
3901 }
3902 else {
3903 *p++ = '\\';
3904 *p++ = (unsigned char)s[-1];
3905 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00003906 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003907 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003908 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003909 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003910 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003911 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003912 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00003913 Py_XDECREF(errorHandler);
3914 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003915 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00003916
Benjamin Peterson29060642009-01-31 22:14:21 +00003917 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00003918 PyErr_SetString(
3919 PyExc_UnicodeError,
3920 "\\N escapes not supported (can't load unicodedata module)"
3921 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003922 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003923 Py_XDECREF(errorHandler);
3924 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00003925 return NULL;
3926
Benjamin Peterson29060642009-01-31 22:14:21 +00003927 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003928 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003929 Py_XDECREF(errorHandler);
3930 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003931 return NULL;
3932}
3933
3934/* Return a Unicode-Escape string version of the Unicode object.
3935
3936 If quotes is true, the string is enclosed in u"" or u'' quotes as
3937 appropriate.
3938
3939*/
3940
Thomas Wouters477c8d52006-05-27 19:21:47 +00003941Py_LOCAL_INLINE(const Py_UNICODE *) findchar(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003942 Py_ssize_t size,
3943 Py_UNICODE ch)
Thomas Wouters477c8d52006-05-27 19:21:47 +00003944{
3945 /* like wcschr, but doesn't stop at NULL characters */
3946
3947 while (size-- > 0) {
3948 if (*s == ch)
3949 return s;
3950 s++;
3951 }
3952
3953 return NULL;
3954}
Barry Warsaw51ac5802000-03-20 16:36:48 +00003955
Walter Dörwald79e913e2007-05-12 11:08:06 +00003956static const char *hexdigits = "0123456789abcdef";
3957
3958PyObject *PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003959 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003960{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003961 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003962 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003963
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003964#ifdef Py_UNICODE_WIDE
3965 const Py_ssize_t expandsize = 10;
3966#else
3967 const Py_ssize_t expandsize = 6;
3968#endif
3969
Thomas Wouters89f507f2006-12-13 04:49:30 +00003970 /* XXX(nnorwitz): rather than over-allocating, it would be
3971 better to choose a different scheme. Perhaps scan the
3972 first N-chars of the string and allocate based on that size.
3973 */
3974 /* Initial allocation is based on the longest-possible unichr
3975 escape.
3976
3977 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
3978 unichr, so in this case it's the longest unichr escape. In
3979 narrow (UTF-16) builds this is five chars per source unichr
3980 since there are two unichrs in the surrogate pair, so in narrow
3981 (UTF-16) builds it's not the longest unichr escape.
3982
3983 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
3984 so in the narrow (UTF-16) build case it's the longest unichr
3985 escape.
3986 */
3987
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003988 if (size == 0)
3989 return PyBytes_FromStringAndSize(NULL, 0);
3990
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003991 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003992 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003993
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003994 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00003995 2
3996 + expandsize*size
3997 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003998 if (repr == NULL)
3999 return NULL;
4000
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004001 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004002
Guido van Rossumd57fd912000-03-10 22:53:23 +00004003 while (size-- > 0) {
4004 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004005
Walter Dörwald79e913e2007-05-12 11:08:06 +00004006 /* Escape backslashes */
4007 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004008 *p++ = '\\';
4009 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00004010 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004011 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004012
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00004013#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004014 /* Map 21-bit characters to '\U00xxxxxx' */
4015 else if (ch >= 0x10000) {
4016 *p++ = '\\';
4017 *p++ = 'U';
Walter Dörwald79e913e2007-05-12 11:08:06 +00004018 *p++ = hexdigits[(ch >> 28) & 0x0000000F];
4019 *p++ = hexdigits[(ch >> 24) & 0x0000000F];
4020 *p++ = hexdigits[(ch >> 20) & 0x0000000F];
4021 *p++ = hexdigits[(ch >> 16) & 0x0000000F];
4022 *p++ = hexdigits[(ch >> 12) & 0x0000000F];
4023 *p++ = hexdigits[(ch >> 8) & 0x0000000F];
4024 *p++ = hexdigits[(ch >> 4) & 0x0000000F];
4025 *p++ = hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00004026 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004027 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00004028#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004029 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
4030 else if (ch >= 0xD800 && ch < 0xDC00) {
4031 Py_UNICODE ch2;
4032 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00004033
Benjamin Peterson29060642009-01-31 22:14:21 +00004034 ch2 = *s++;
4035 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00004036 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004037 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
4038 *p++ = '\\';
4039 *p++ = 'U';
4040 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
4041 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
4042 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
4043 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
4044 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
4045 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
4046 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
4047 *p++ = hexdigits[ucs & 0x0000000F];
4048 continue;
4049 }
4050 /* Fall through: isolated surrogates are copied as-is */
4051 s--;
4052 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004053 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00004054#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00004055
Guido van Rossumd57fd912000-03-10 22:53:23 +00004056 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00004057 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004058 *p++ = '\\';
4059 *p++ = 'u';
Walter Dörwald79e913e2007-05-12 11:08:06 +00004060 *p++ = hexdigits[(ch >> 12) & 0x000F];
4061 *p++ = hexdigits[(ch >> 8) & 0x000F];
4062 *p++ = hexdigits[(ch >> 4) & 0x000F];
4063 *p++ = hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00004064 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004065
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00004066 /* Map special whitespace to '\t', \n', '\r' */
4067 else if (ch == '\t') {
4068 *p++ = '\\';
4069 *p++ = 't';
4070 }
4071 else if (ch == '\n') {
4072 *p++ = '\\';
4073 *p++ = 'n';
4074 }
4075 else if (ch == '\r') {
4076 *p++ = '\\';
4077 *p++ = 'r';
4078 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004079
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00004080 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00004081 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004082 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00004083 *p++ = 'x';
Walter Dörwald79e913e2007-05-12 11:08:06 +00004084 *p++ = hexdigits[(ch >> 4) & 0x000F];
4085 *p++ = hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00004086 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004087
Guido van Rossumd57fd912000-03-10 22:53:23 +00004088 /* Copy everything else as-is */
4089 else
4090 *p++ = (char) ch;
4091 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004092
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004093 assert(p - PyBytes_AS_STRING(repr) > 0);
4094 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
4095 return NULL;
4096 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004097}
4098
Alexandre Vassalotti2056bed2008-12-27 19:46:35 +00004099PyObject *PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004100{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004101 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004102 if (!PyUnicode_Check(unicode)) {
4103 PyErr_BadArgument();
4104 return NULL;
4105 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00004106 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
4107 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004108 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004109}
4110
4111/* --- Raw Unicode Escape Codec ------------------------------------------- */
4112
4113PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004114 Py_ssize_t size,
4115 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004116{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004117 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004118 Py_ssize_t startinpos;
4119 Py_ssize_t endinpos;
4120 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004121 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004122 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004123 const char *end;
4124 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004125 PyObject *errorHandler = NULL;
4126 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00004127
Guido van Rossumd57fd912000-03-10 22:53:23 +00004128 /* Escaped strings will always be longer than the resulting
4129 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004130 length after conversion to the true value. (But decoding error
4131 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004132 v = _PyUnicode_New(size);
4133 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004134 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004135 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004136 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004137 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004138 end = s + size;
4139 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004140 unsigned char c;
4141 Py_UCS4 x;
4142 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004143 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004144
Benjamin Peterson29060642009-01-31 22:14:21 +00004145 /* Non-escape characters are interpreted as Unicode ordinals */
4146 if (*s != '\\') {
4147 *p++ = (unsigned char)*s++;
4148 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004149 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004150 startinpos = s-starts;
4151
4152 /* \u-escapes are only interpreted iff the number of leading
4153 backslashes if odd */
4154 bs = s;
4155 for (;s < end;) {
4156 if (*s != '\\')
4157 break;
4158 *p++ = (unsigned char)*s++;
4159 }
4160 if (((s - bs) & 1) == 0 ||
4161 s >= end ||
4162 (*s != 'u' && *s != 'U')) {
4163 continue;
4164 }
4165 p--;
4166 count = *s=='u' ? 4 : 8;
4167 s++;
4168
4169 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
4170 outpos = p-PyUnicode_AS_UNICODE(v);
4171 for (x = 0, i = 0; i < count; ++i, ++s) {
4172 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00004173 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004174 endinpos = s-starts;
4175 if (unicode_decode_call_errorhandler(
4176 errors, &errorHandler,
4177 "rawunicodeescape", "truncated \\uXXXX",
4178 &starts, &end, &startinpos, &endinpos, &exc, &s,
4179 &v, &outpos, &p))
4180 goto onError;
4181 goto nextByte;
4182 }
4183 x = (x<<4) & ~0xF;
4184 if (c >= '0' && c <= '9')
4185 x += c - '0';
4186 else if (c >= 'a' && c <= 'f')
4187 x += 10 + c - 'a';
4188 else
4189 x += 10 + c - 'A';
4190 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00004191 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00004192 /* UCS-2 character */
4193 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004194 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004195 /* UCS-4 character. Either store directly, or as
4196 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00004197#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004198 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004199#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004200 x -= 0x10000L;
4201 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
4202 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00004203#endif
4204 } else {
4205 endinpos = s-starts;
4206 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004207 if (unicode_decode_call_errorhandler(
4208 errors, &errorHandler,
4209 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00004210 &starts, &end, &startinpos, &endinpos, &exc, &s,
4211 &v, &outpos, &p))
4212 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004213 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004214 nextByte:
4215 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004216 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004217 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004218 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004219 Py_XDECREF(errorHandler);
4220 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004221 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004222
Benjamin Peterson29060642009-01-31 22:14:21 +00004223 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004224 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004225 Py_XDECREF(errorHandler);
4226 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004227 return NULL;
4228}
4229
4230PyObject *PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004231 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004232{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004233 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004234 char *p;
4235 char *q;
4236
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004237#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004238 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004239#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004240 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004241#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00004242
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004243 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00004244 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00004245
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004246 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004247 if (repr == NULL)
4248 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00004249 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004250 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004251
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004252 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004253 while (size-- > 0) {
4254 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004255#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004256 /* Map 32-bit characters to '\Uxxxxxxxx' */
4257 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004258 *p++ = '\\';
4259 *p++ = 'U';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00004260 *p++ = hexdigits[(ch >> 28) & 0xf];
4261 *p++ = hexdigits[(ch >> 24) & 0xf];
4262 *p++ = hexdigits[(ch >> 20) & 0xf];
4263 *p++ = hexdigits[(ch >> 16) & 0xf];
4264 *p++ = hexdigits[(ch >> 12) & 0xf];
4265 *p++ = hexdigits[(ch >> 8) & 0xf];
4266 *p++ = hexdigits[(ch >> 4) & 0xf];
4267 *p++ = hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00004268 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004269 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00004270#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004271 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
4272 if (ch >= 0xD800 && ch < 0xDC00) {
4273 Py_UNICODE ch2;
4274 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004275
Benjamin Peterson29060642009-01-31 22:14:21 +00004276 ch2 = *s++;
4277 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00004278 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004279 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
4280 *p++ = '\\';
4281 *p++ = 'U';
4282 *p++ = hexdigits[(ucs >> 28) & 0xf];
4283 *p++ = hexdigits[(ucs >> 24) & 0xf];
4284 *p++ = hexdigits[(ucs >> 20) & 0xf];
4285 *p++ = hexdigits[(ucs >> 16) & 0xf];
4286 *p++ = hexdigits[(ucs >> 12) & 0xf];
4287 *p++ = hexdigits[(ucs >> 8) & 0xf];
4288 *p++ = hexdigits[(ucs >> 4) & 0xf];
4289 *p++ = hexdigits[ucs & 0xf];
4290 continue;
4291 }
4292 /* Fall through: isolated surrogates are copied as-is */
4293 s--;
4294 size++;
4295 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004296#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004297 /* Map 16-bit characters to '\uxxxx' */
4298 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004299 *p++ = '\\';
4300 *p++ = 'u';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00004301 *p++ = hexdigits[(ch >> 12) & 0xf];
4302 *p++ = hexdigits[(ch >> 8) & 0xf];
4303 *p++ = hexdigits[(ch >> 4) & 0xf];
4304 *p++ = hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00004305 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004306 /* Copy everything else as-is */
4307 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00004308 *p++ = (char) ch;
4309 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00004310 size = p - q;
4311
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004312 assert(size > 0);
4313 if (_PyBytes_Resize(&repr, size) < 0)
4314 return NULL;
4315 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004316}
4317
4318PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
4319{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004320 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004321 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00004322 PyErr_BadArgument();
4323 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004324 }
Walter Dörwald711005d2007-05-12 12:03:26 +00004325 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
4326 PyUnicode_GET_SIZE(unicode));
4327
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004328 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004329}
4330
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004331/* --- Unicode Internal Codec ------------------------------------------- */
4332
4333PyObject *_PyUnicode_DecodeUnicodeInternal(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004334 Py_ssize_t size,
4335 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004336{
4337 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004338 Py_ssize_t startinpos;
4339 Py_ssize_t endinpos;
4340 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004341 PyUnicodeObject *v;
4342 Py_UNICODE *p;
4343 const char *end;
4344 const char *reason;
4345 PyObject *errorHandler = NULL;
4346 PyObject *exc = NULL;
4347
Neal Norwitzd43069c2006-01-08 01:12:10 +00004348#ifdef Py_UNICODE_WIDE
4349 Py_UNICODE unimax = PyUnicode_GetMax();
4350#endif
4351
Thomas Wouters89f507f2006-12-13 04:49:30 +00004352 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004353 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
4354 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004355 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004356 if (PyUnicode_GetSize((PyObject *)v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004357 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004358 p = PyUnicode_AS_UNICODE(v);
4359 end = s + size;
4360
4361 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00004362 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004363 /* We have to sanity check the raw data, otherwise doom looms for
4364 some malformed UCS-4 data. */
4365 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00004366#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004367 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00004368#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004369 end-s < Py_UNICODE_SIZE
4370 )
Benjamin Peterson29060642009-01-31 22:14:21 +00004371 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004372 startinpos = s - starts;
4373 if (end-s < Py_UNICODE_SIZE) {
4374 endinpos = end-starts;
4375 reason = "truncated input";
4376 }
4377 else {
4378 endinpos = s - starts + Py_UNICODE_SIZE;
4379 reason = "illegal code point (> 0x10FFFF)";
4380 }
4381 outpos = p - PyUnicode_AS_UNICODE(v);
4382 if (unicode_decode_call_errorhandler(
4383 errors, &errorHandler,
4384 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00004385 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00004386 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004387 goto onError;
4388 }
4389 }
4390 else {
4391 p++;
4392 s += Py_UNICODE_SIZE;
4393 }
4394 }
4395
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004396 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004397 goto onError;
4398 Py_XDECREF(errorHandler);
4399 Py_XDECREF(exc);
4400 return (PyObject *)v;
4401
Benjamin Peterson29060642009-01-31 22:14:21 +00004402 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004403 Py_XDECREF(v);
4404 Py_XDECREF(errorHandler);
4405 Py_XDECREF(exc);
4406 return NULL;
4407}
4408
Guido van Rossumd57fd912000-03-10 22:53:23 +00004409/* --- Latin-1 Codec ------------------------------------------------------ */
4410
4411PyObject *PyUnicode_DecodeLatin1(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004412 Py_ssize_t size,
4413 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004414{
4415 PyUnicodeObject *v;
4416 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00004417 const char *e, *unrolled_end;
Tim Petersced69f82003-09-16 20:30:58 +00004418
Guido van Rossumd57fd912000-03-10 22:53:23 +00004419 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004420 if (size == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004421 Py_UNICODE r = *(unsigned char*)s;
4422 return PyUnicode_FromUnicode(&r, 1);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004423 }
4424
Guido van Rossumd57fd912000-03-10 22:53:23 +00004425 v = _PyUnicode_New(size);
4426 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004427 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004428 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004429 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004430 p = PyUnicode_AS_UNICODE(v);
Antoine Pitrouab868312009-01-10 15:40:25 +00004431 e = s + size;
4432 /* Unrolling the copy makes it much faster by reducing the looping
4433 overhead. This is similar to what many memcpy() implementations do. */
4434 unrolled_end = e - 4;
4435 while (s < unrolled_end) {
4436 p[0] = (unsigned char) s[0];
4437 p[1] = (unsigned char) s[1];
4438 p[2] = (unsigned char) s[2];
4439 p[3] = (unsigned char) s[3];
4440 s += 4;
4441 p += 4;
4442 }
4443 while (s < e)
4444 *p++ = (unsigned char) *s++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004445 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004446
Benjamin Peterson29060642009-01-31 22:14:21 +00004447 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004448 Py_XDECREF(v);
4449 return NULL;
4450}
4451
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004452/* create or adjust a UnicodeEncodeError */
4453static void make_encode_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004454 const char *encoding,
4455 const Py_UNICODE *unicode, Py_ssize_t size,
4456 Py_ssize_t startpos, Py_ssize_t endpos,
4457 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004458{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004459 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004460 *exceptionObject = PyUnicodeEncodeError_Create(
4461 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004462 }
4463 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004464 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
4465 goto onError;
4466 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
4467 goto onError;
4468 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
4469 goto onError;
4470 return;
4471 onError:
4472 Py_DECREF(*exceptionObject);
4473 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004474 }
4475}
4476
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004477/* raises a UnicodeEncodeError */
4478static void raise_encode_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004479 const char *encoding,
4480 const Py_UNICODE *unicode, Py_ssize_t size,
4481 Py_ssize_t startpos, Py_ssize_t endpos,
4482 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004483{
4484 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004485 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004486 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004487 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004488}
4489
4490/* error handling callback helper:
4491 build arguments, call the callback and check the arguments,
4492 put the result into newpos and return the replacement string, which
4493 has to be freed by the caller */
4494static PyObject *unicode_encode_call_errorhandler(const char *errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00004495 PyObject **errorHandler,
4496 const char *encoding, const char *reason,
4497 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
4498 Py_ssize_t startpos, Py_ssize_t endpos,
4499 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004500{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004501 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004502
4503 PyObject *restuple;
4504 PyObject *resunicode;
4505
4506 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004507 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004508 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004509 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004510 }
4511
4512 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004513 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004514 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004515 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004516
4517 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00004518 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004519 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004520 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004521 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004522 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004523 Py_DECREF(restuple);
4524 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004525 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004526 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00004527 &resunicode, newpos)) {
4528 Py_DECREF(restuple);
4529 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004530 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004531 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
4532 PyErr_SetString(PyExc_TypeError, &argparse[3]);
4533 Py_DECREF(restuple);
4534 return NULL;
4535 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004536 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004537 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004538 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004539 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
4540 Py_DECREF(restuple);
4541 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004542 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004543 Py_INCREF(resunicode);
4544 Py_DECREF(restuple);
4545 return resunicode;
4546}
4547
4548static PyObject *unicode_encode_ucs1(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004549 Py_ssize_t size,
4550 const char *errors,
4551 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004552{
4553 /* output object */
4554 PyObject *res;
4555 /* pointers to the beginning and end+1 of input */
4556 const Py_UNICODE *startp = p;
4557 const Py_UNICODE *endp = p + size;
4558 /* pointer to the beginning of the unencodable characters */
4559 /* const Py_UNICODE *badp = NULL; */
4560 /* pointer into the output */
4561 char *str;
4562 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00004563 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004564 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
4565 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004566 PyObject *errorHandler = NULL;
4567 PyObject *exc = NULL;
4568 /* the following variable is used for caching string comparisons
4569 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
4570 int known_errorHandler = -1;
4571
4572 /* allocate enough for a simple encoding without
4573 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00004574 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00004575 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004576 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004577 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00004578 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004579 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004580 ressize = size;
4581
4582 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004583 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004584
Benjamin Peterson29060642009-01-31 22:14:21 +00004585 /* can we encode this? */
4586 if (c<limit) {
4587 /* no overflow check, because we know that the space is enough */
4588 *str++ = (char)c;
4589 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004590 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004591 else {
4592 Py_ssize_t unicodepos = p-startp;
4593 Py_ssize_t requiredsize;
4594 PyObject *repunicode;
4595 Py_ssize_t repsize;
4596 Py_ssize_t newpos;
4597 Py_ssize_t respos;
4598 Py_UNICODE *uni2;
4599 /* startpos for collecting unencodable chars */
4600 const Py_UNICODE *collstart = p;
4601 const Py_UNICODE *collend = p;
4602 /* find all unecodable characters */
4603 while ((collend < endp) && ((*collend)>=limit))
4604 ++collend;
4605 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
4606 if (known_errorHandler==-1) {
4607 if ((errors==NULL) || (!strcmp(errors, "strict")))
4608 known_errorHandler = 1;
4609 else if (!strcmp(errors, "replace"))
4610 known_errorHandler = 2;
4611 else if (!strcmp(errors, "ignore"))
4612 known_errorHandler = 3;
4613 else if (!strcmp(errors, "xmlcharrefreplace"))
4614 known_errorHandler = 4;
4615 else
4616 known_errorHandler = 0;
4617 }
4618 switch (known_errorHandler) {
4619 case 1: /* strict */
4620 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
4621 goto onError;
4622 case 2: /* replace */
4623 while (collstart++<collend)
4624 *str++ = '?'; /* fall through */
4625 case 3: /* ignore */
4626 p = collend;
4627 break;
4628 case 4: /* xmlcharrefreplace */
4629 respos = str - PyBytes_AS_STRING(res);
4630 /* determine replacement size (temporarily (mis)uses p) */
4631 for (p = collstart, repsize = 0; p < collend; ++p) {
4632 if (*p<10)
4633 repsize += 2+1+1;
4634 else if (*p<100)
4635 repsize += 2+2+1;
4636 else if (*p<1000)
4637 repsize += 2+3+1;
4638 else if (*p<10000)
4639 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00004640#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004641 else
4642 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00004643#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004644 else if (*p<100000)
4645 repsize += 2+5+1;
4646 else if (*p<1000000)
4647 repsize += 2+6+1;
4648 else
4649 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004650#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004651 }
4652 requiredsize = respos+repsize+(endp-collend);
4653 if (requiredsize > ressize) {
4654 if (requiredsize<2*ressize)
4655 requiredsize = 2*ressize;
4656 if (_PyBytes_Resize(&res, requiredsize))
4657 goto onError;
4658 str = PyBytes_AS_STRING(res) + respos;
4659 ressize = requiredsize;
4660 }
4661 /* generate replacement (temporarily (mis)uses p) */
4662 for (p = collstart; p < collend; ++p) {
4663 str += sprintf(str, "&#%d;", (int)*p);
4664 }
4665 p = collend;
4666 break;
4667 default:
4668 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
4669 encoding, reason, startp, size, &exc,
4670 collstart-startp, collend-startp, &newpos);
4671 if (repunicode == NULL)
4672 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004673 if (PyBytes_Check(repunicode)) {
4674 /* Directly copy bytes result to output. */
4675 repsize = PyBytes_Size(repunicode);
4676 if (repsize > 1) {
4677 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00004678 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00004679 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
4680 Py_DECREF(repunicode);
4681 goto onError;
4682 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00004683 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004684 ressize += repsize-1;
4685 }
4686 memcpy(str, PyBytes_AsString(repunicode), repsize);
4687 str += repsize;
4688 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004689 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00004690 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004691 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004692 /* need more space? (at least enough for what we
4693 have+the replacement+the rest of the string, so
4694 we won't have to check space for encodable characters) */
4695 respos = str - PyBytes_AS_STRING(res);
4696 repsize = PyUnicode_GET_SIZE(repunicode);
4697 requiredsize = respos+repsize+(endp-collend);
4698 if (requiredsize > ressize) {
4699 if (requiredsize<2*ressize)
4700 requiredsize = 2*ressize;
4701 if (_PyBytes_Resize(&res, requiredsize)) {
4702 Py_DECREF(repunicode);
4703 goto onError;
4704 }
4705 str = PyBytes_AS_STRING(res) + respos;
4706 ressize = requiredsize;
4707 }
4708 /* check if there is anything unencodable in the replacement
4709 and copy it to the output */
4710 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
4711 c = *uni2;
4712 if (c >= limit) {
4713 raise_encode_exception(&exc, encoding, startp, size,
4714 unicodepos, unicodepos+1, reason);
4715 Py_DECREF(repunicode);
4716 goto onError;
4717 }
4718 *str = (char)c;
4719 }
4720 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004721 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00004722 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004723 }
4724 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004725 /* Resize if we allocated to much */
4726 size = str - PyBytes_AS_STRING(res);
4727 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00004728 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004729 if (_PyBytes_Resize(&res, size) < 0)
4730 goto onError;
4731 }
4732
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004733 Py_XDECREF(errorHandler);
4734 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004735 return res;
4736
4737 onError:
4738 Py_XDECREF(res);
4739 Py_XDECREF(errorHandler);
4740 Py_XDECREF(exc);
4741 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004742}
4743
Guido van Rossumd57fd912000-03-10 22:53:23 +00004744PyObject *PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004745 Py_ssize_t size,
4746 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004747{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004748 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004749}
4750
4751PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
4752{
4753 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004754 PyErr_BadArgument();
4755 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004756 }
4757 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004758 PyUnicode_GET_SIZE(unicode),
4759 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004760}
4761
4762/* --- 7-bit ASCII Codec -------------------------------------------------- */
4763
Guido van Rossumd57fd912000-03-10 22:53:23 +00004764PyObject *PyUnicode_DecodeASCII(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004765 Py_ssize_t size,
4766 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004767{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004768 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004769 PyUnicodeObject *v;
4770 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004771 Py_ssize_t startinpos;
4772 Py_ssize_t endinpos;
4773 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004774 const char *e;
4775 PyObject *errorHandler = NULL;
4776 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00004777
Guido van Rossumd57fd912000-03-10 22:53:23 +00004778 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004779 if (size == 1 && *(unsigned char*)s < 128) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004780 Py_UNICODE r = *(unsigned char*)s;
4781 return PyUnicode_FromUnicode(&r, 1);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004782 }
Tim Petersced69f82003-09-16 20:30:58 +00004783
Guido van Rossumd57fd912000-03-10 22:53:23 +00004784 v = _PyUnicode_New(size);
4785 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004786 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004787 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004788 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004789 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004790 e = s + size;
4791 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004792 register unsigned char c = (unsigned char)*s;
4793 if (c < 128) {
4794 *p++ = c;
4795 ++s;
4796 }
4797 else {
4798 startinpos = s-starts;
4799 endinpos = startinpos + 1;
4800 outpos = p - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
4801 if (unicode_decode_call_errorhandler(
4802 errors, &errorHandler,
4803 "ascii", "ordinal not in range(128)",
4804 &starts, &e, &startinpos, &endinpos, &exc, &s,
4805 &v, &outpos, &p))
4806 goto onError;
4807 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004808 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00004809 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00004810 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
4811 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004812 Py_XDECREF(errorHandler);
4813 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004814 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004815
Benjamin Peterson29060642009-01-31 22:14:21 +00004816 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004817 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004818 Py_XDECREF(errorHandler);
4819 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004820 return NULL;
4821}
4822
Guido van Rossumd57fd912000-03-10 22:53:23 +00004823PyObject *PyUnicode_EncodeASCII(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004824 Py_ssize_t size,
4825 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004826{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004827 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004828}
4829
4830PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
4831{
4832 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004833 PyErr_BadArgument();
4834 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004835 }
4836 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004837 PyUnicode_GET_SIZE(unicode),
4838 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004839}
4840
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004841#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004842
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004843/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004844
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00004845#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004846#define NEED_RETRY
4847#endif
4848
4849/* XXX This code is limited to "true" double-byte encodings, as
4850 a) it assumes an incomplete character consists of a single byte, and
4851 b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
Benjamin Peterson29060642009-01-31 22:14:21 +00004852 encodings, see IsDBCSLeadByteEx documentation. */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004853
4854static int is_dbcs_lead_byte(const char *s, int offset)
4855{
4856 const char *curr = s + offset;
4857
4858 if (IsDBCSLeadByte(*curr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004859 const char *prev = CharPrev(s, curr);
4860 return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004861 }
4862 return 0;
4863}
4864
4865/*
4866 * Decode MBCS string into unicode object. If 'final' is set, converts
4867 * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
4868 */
4869static int decode_mbcs(PyUnicodeObject **v,
Benjamin Peterson29060642009-01-31 22:14:21 +00004870 const char *s, /* MBCS string */
4871 int size, /* sizeof MBCS string */
Victor Stinner554f3f02010-06-16 23:33:54 +00004872 int final,
4873 const char *errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004874{
4875 Py_UNICODE *p;
Victor Stinner554f3f02010-06-16 23:33:54 +00004876 Py_ssize_t n;
4877 DWORD usize;
4878 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004879
4880 assert(size >= 0);
4881
Victor Stinner554f3f02010-06-16 23:33:54 +00004882 /* check and handle 'errors' arg */
4883 if (errors==NULL || strcmp(errors, "strict")==0)
4884 flags = MB_ERR_INVALID_CHARS;
4885 else if (strcmp(errors, "ignore")==0)
4886 flags = 0;
4887 else {
4888 PyErr_Format(PyExc_ValueError,
4889 "mbcs encoding does not support errors='%s'",
4890 errors);
4891 return -1;
4892 }
4893
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004894 /* Skip trailing lead-byte unless 'final' is set */
4895 if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
Benjamin Peterson29060642009-01-31 22:14:21 +00004896 --size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004897
4898 /* First get the size of the result */
4899 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00004900 usize = MultiByteToWideChar(CP_ACP, flags, s, size, NULL, 0);
4901 if (usize==0)
4902 goto mbcs_decode_error;
4903 } else
4904 usize = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004905
4906 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004907 /* Create unicode object */
4908 *v = _PyUnicode_New(usize);
4909 if (*v == NULL)
4910 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00004911 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004912 }
4913 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004914 /* Extend unicode object */
4915 n = PyUnicode_GET_SIZE(*v);
4916 if (_PyUnicode_Resize(v, n + usize) < 0)
4917 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004918 }
4919
4920 /* Do the conversion */
Victor Stinner554f3f02010-06-16 23:33:54 +00004921 if (usize > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004922 p = PyUnicode_AS_UNICODE(*v) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00004923 if (0 == MultiByteToWideChar(CP_ACP, flags, s, size, p, usize)) {
4924 goto mbcs_decode_error;
Benjamin Peterson29060642009-01-31 22:14:21 +00004925 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004926 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004927 return size;
Victor Stinner554f3f02010-06-16 23:33:54 +00004928
4929mbcs_decode_error:
4930 /* If the last error was ERROR_NO_UNICODE_TRANSLATION, then
4931 we raise a UnicodeDecodeError - else it is a 'generic'
4932 windows error
4933 */
4934 if (GetLastError()==ERROR_NO_UNICODE_TRANSLATION) {
4935 /* Ideally, we should get reason from FormatMessage - this
4936 is the Windows 2000 English version of the message
4937 */
4938 PyObject *exc = NULL;
4939 const char *reason = "No mapping for the Unicode character exists "
4940 "in the target multi-byte code page.";
4941 make_decode_exception(&exc, "mbcs", s, size, 0, 0, reason);
4942 if (exc != NULL) {
4943 PyCodec_StrictErrors(exc);
4944 Py_DECREF(exc);
4945 }
4946 } else {
4947 PyErr_SetFromWindowsErrWithFilename(0, NULL);
4948 }
4949 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004950}
4951
4952PyObject *PyUnicode_DecodeMBCSStateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004953 Py_ssize_t size,
4954 const char *errors,
4955 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004956{
4957 PyUnicodeObject *v = NULL;
4958 int done;
4959
4960 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004961 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004962
4963#ifdef NEED_RETRY
4964 retry:
4965 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00004966 done = decode_mbcs(&v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004967 else
4968#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00004969 done = decode_mbcs(&v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004970
4971 if (done < 0) {
4972 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00004973 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004974 }
4975
4976 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004977 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004978
4979#ifdef NEED_RETRY
4980 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004981 s += done;
4982 size -= done;
4983 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004984 }
4985#endif
4986
4987 return (PyObject *)v;
4988}
4989
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004990PyObject *PyUnicode_DecodeMBCS(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004991 Py_ssize_t size,
4992 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004993{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004994 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
4995}
4996
4997/*
4998 * Convert unicode into string object (MBCS).
4999 * Returns 0 if succeed, -1 otherwise.
5000 */
5001static int encode_mbcs(PyObject **repr,
Benjamin Peterson29060642009-01-31 22:14:21 +00005002 const Py_UNICODE *p, /* unicode */
Victor Stinner554f3f02010-06-16 23:33:54 +00005003 int size, /* size of unicode */
5004 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005005{
Victor Stinner554f3f02010-06-16 23:33:54 +00005006 BOOL usedDefaultChar = FALSE;
5007 BOOL *pusedDefaultChar;
5008 int mbcssize;
5009 Py_ssize_t n;
5010 PyObject *exc = NULL;
5011 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005012
5013 assert(size >= 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005014
Victor Stinner554f3f02010-06-16 23:33:54 +00005015 /* check and handle 'errors' arg */
5016 if (errors==NULL || strcmp(errors, "strict")==0) {
5017 flags = WC_NO_BEST_FIT_CHARS;
5018 pusedDefaultChar = &usedDefaultChar;
5019 } else if (strcmp(errors, "replace")==0) {
5020 flags = 0;
5021 pusedDefaultChar = NULL;
5022 } else {
5023 PyErr_Format(PyExc_ValueError,
5024 "mbcs encoding does not support errors='%s'",
5025 errors);
5026 return -1;
5027 }
5028
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005029 /* First get the size of the result */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005030 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00005031 mbcssize = WideCharToMultiByte(CP_ACP, flags, p, size, NULL, 0,
5032 NULL, pusedDefaultChar);
Benjamin Peterson29060642009-01-31 22:14:21 +00005033 if (mbcssize == 0) {
5034 PyErr_SetFromWindowsErrWithFilename(0, NULL);
5035 return -1;
5036 }
Victor Stinner554f3f02010-06-16 23:33:54 +00005037 /* If we used a default char, then we failed! */
5038 if (pusedDefaultChar && *pusedDefaultChar)
5039 goto mbcs_encode_error;
5040 } else {
5041 mbcssize = 0;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005042 }
5043
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005044 if (*repr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005045 /* Create string object */
5046 *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
5047 if (*repr == NULL)
5048 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00005049 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005050 }
5051 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005052 /* Extend string object */
5053 n = PyBytes_Size(*repr);
5054 if (_PyBytes_Resize(repr, n + mbcssize) < 0)
5055 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005056 }
5057
5058 /* Do the conversion */
5059 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005060 char *s = PyBytes_AS_STRING(*repr) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00005061 if (0 == WideCharToMultiByte(CP_ACP, flags, p, size, s, mbcssize,
5062 NULL, pusedDefaultChar)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005063 PyErr_SetFromWindowsErrWithFilename(0, NULL);
5064 return -1;
5065 }
Victor Stinner554f3f02010-06-16 23:33:54 +00005066 if (pusedDefaultChar && *pusedDefaultChar)
5067 goto mbcs_encode_error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005068 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005069 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00005070
5071mbcs_encode_error:
5072 raise_encode_exception(&exc, "mbcs", p, size, 0, 0, "invalid character");
5073 Py_XDECREF(exc);
5074 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005075}
5076
5077PyObject *PyUnicode_EncodeMBCS(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00005078 Py_ssize_t size,
5079 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005080{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005081 PyObject *repr = NULL;
5082 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00005083
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005084#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00005085 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005086 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00005087 ret = encode_mbcs(&repr, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005088 else
5089#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00005090 ret = encode_mbcs(&repr, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005091
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005092 if (ret < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005093 Py_XDECREF(repr);
5094 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005095 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005096
5097#ifdef NEED_RETRY
5098 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005099 p += INT_MAX;
5100 size -= INT_MAX;
5101 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005102 }
5103#endif
5104
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005105 return repr;
5106}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00005107
Mark Hammond0ccda1e2003-07-01 00:13:27 +00005108PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
5109{
5110 if (!PyUnicode_Check(unicode)) {
5111 PyErr_BadArgument();
5112 return NULL;
5113 }
5114 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005115 PyUnicode_GET_SIZE(unicode),
5116 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00005117}
5118
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005119#undef NEED_RETRY
5120
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00005121#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005122
Guido van Rossumd57fd912000-03-10 22:53:23 +00005123/* --- Character Mapping Codec -------------------------------------------- */
5124
Guido van Rossumd57fd912000-03-10 22:53:23 +00005125PyObject *PyUnicode_DecodeCharmap(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005126 Py_ssize_t size,
5127 PyObject *mapping,
5128 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005129{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005130 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005131 Py_ssize_t startinpos;
5132 Py_ssize_t endinpos;
5133 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005134 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005135 PyUnicodeObject *v;
5136 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005137 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005138 PyObject *errorHandler = NULL;
5139 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005140 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005141 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00005142
Guido van Rossumd57fd912000-03-10 22:53:23 +00005143 /* Default to Latin-1 */
5144 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005145 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005146
5147 v = _PyUnicode_New(size);
5148 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005149 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005150 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005151 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005152 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005153 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005154 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005155 mapstring = PyUnicode_AS_UNICODE(mapping);
5156 maplen = PyUnicode_GET_SIZE(mapping);
5157 while (s < e) {
5158 unsigned char ch = *s;
5159 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005160
Benjamin Peterson29060642009-01-31 22:14:21 +00005161 if (ch < maplen)
5162 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005163
Benjamin Peterson29060642009-01-31 22:14:21 +00005164 if (x == 0xfffe) {
5165 /* undefined mapping */
5166 outpos = p-PyUnicode_AS_UNICODE(v);
5167 startinpos = s-starts;
5168 endinpos = startinpos+1;
5169 if (unicode_decode_call_errorhandler(
5170 errors, &errorHandler,
5171 "charmap", "character maps to <undefined>",
5172 &starts, &e, &startinpos, &endinpos, &exc, &s,
5173 &v, &outpos, &p)) {
5174 goto onError;
5175 }
5176 continue;
5177 }
5178 *p++ = x;
5179 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005180 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005181 }
5182 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005183 while (s < e) {
5184 unsigned char ch = *s;
5185 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005186
Benjamin Peterson29060642009-01-31 22:14:21 +00005187 /* Get mapping (char ordinal -> integer, Unicode char or None) */
5188 w = PyLong_FromLong((long)ch);
5189 if (w == NULL)
5190 goto onError;
5191 x = PyObject_GetItem(mapping, w);
5192 Py_DECREF(w);
5193 if (x == NULL) {
5194 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5195 /* No mapping found means: mapping is undefined. */
5196 PyErr_Clear();
5197 x = Py_None;
5198 Py_INCREF(x);
5199 } else
5200 goto onError;
5201 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005202
Benjamin Peterson29060642009-01-31 22:14:21 +00005203 /* Apply mapping */
5204 if (PyLong_Check(x)) {
5205 long value = PyLong_AS_LONG(x);
5206 if (value < 0 || value > 65535) {
5207 PyErr_SetString(PyExc_TypeError,
5208 "character mapping must be in range(65536)");
5209 Py_DECREF(x);
5210 goto onError;
5211 }
5212 *p++ = (Py_UNICODE)value;
5213 }
5214 else if (x == Py_None) {
5215 /* undefined mapping */
5216 outpos = p-PyUnicode_AS_UNICODE(v);
5217 startinpos = s-starts;
5218 endinpos = startinpos+1;
5219 if (unicode_decode_call_errorhandler(
5220 errors, &errorHandler,
5221 "charmap", "character maps to <undefined>",
5222 &starts, &e, &startinpos, &endinpos, &exc, &s,
5223 &v, &outpos, &p)) {
5224 Py_DECREF(x);
5225 goto onError;
5226 }
5227 Py_DECREF(x);
5228 continue;
5229 }
5230 else if (PyUnicode_Check(x)) {
5231 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005232
Benjamin Peterson29060642009-01-31 22:14:21 +00005233 if (targetsize == 1)
5234 /* 1-1 mapping */
5235 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005236
Benjamin Peterson29060642009-01-31 22:14:21 +00005237 else if (targetsize > 1) {
5238 /* 1-n mapping */
5239 if (targetsize > extrachars) {
5240 /* resize first */
5241 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
5242 Py_ssize_t needed = (targetsize - extrachars) + \
5243 (targetsize << 2);
5244 extrachars += needed;
5245 /* XXX overflow detection missing */
5246 if (_PyUnicode_Resize(&v,
5247 PyUnicode_GET_SIZE(v) + needed) < 0) {
5248 Py_DECREF(x);
5249 goto onError;
5250 }
5251 p = PyUnicode_AS_UNICODE(v) + oldpos;
5252 }
5253 Py_UNICODE_COPY(p,
5254 PyUnicode_AS_UNICODE(x),
5255 targetsize);
5256 p += targetsize;
5257 extrachars -= targetsize;
5258 }
5259 /* 1-0 mapping: skip the character */
5260 }
5261 else {
5262 /* wrong return value */
5263 PyErr_SetString(PyExc_TypeError,
5264 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00005265 Py_DECREF(x);
5266 goto onError;
5267 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005268 Py_DECREF(x);
5269 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005270 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005271 }
5272 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00005273 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
5274 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005275 Py_XDECREF(errorHandler);
5276 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005277 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00005278
Benjamin Peterson29060642009-01-31 22:14:21 +00005279 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005280 Py_XDECREF(errorHandler);
5281 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005282 Py_XDECREF(v);
5283 return NULL;
5284}
5285
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005286/* Charmap encoding: the lookup table */
5287
5288struct encoding_map{
Benjamin Peterson29060642009-01-31 22:14:21 +00005289 PyObject_HEAD
5290 unsigned char level1[32];
5291 int count2, count3;
5292 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005293};
5294
5295static PyObject*
5296encoding_map_size(PyObject *obj, PyObject* args)
5297{
5298 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005299 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00005300 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005301}
5302
5303static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005304 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00005305 PyDoc_STR("Return the size (in bytes) of this object") },
5306 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005307};
5308
5309static void
5310encoding_map_dealloc(PyObject* o)
5311{
Benjamin Peterson14339b62009-01-31 16:36:08 +00005312 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005313}
5314
5315static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005316 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005317 "EncodingMap", /*tp_name*/
5318 sizeof(struct encoding_map), /*tp_basicsize*/
5319 0, /*tp_itemsize*/
5320 /* methods */
5321 encoding_map_dealloc, /*tp_dealloc*/
5322 0, /*tp_print*/
5323 0, /*tp_getattr*/
5324 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00005325 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00005326 0, /*tp_repr*/
5327 0, /*tp_as_number*/
5328 0, /*tp_as_sequence*/
5329 0, /*tp_as_mapping*/
5330 0, /*tp_hash*/
5331 0, /*tp_call*/
5332 0, /*tp_str*/
5333 0, /*tp_getattro*/
5334 0, /*tp_setattro*/
5335 0, /*tp_as_buffer*/
5336 Py_TPFLAGS_DEFAULT, /*tp_flags*/
5337 0, /*tp_doc*/
5338 0, /*tp_traverse*/
5339 0, /*tp_clear*/
5340 0, /*tp_richcompare*/
5341 0, /*tp_weaklistoffset*/
5342 0, /*tp_iter*/
5343 0, /*tp_iternext*/
5344 encoding_map_methods, /*tp_methods*/
5345 0, /*tp_members*/
5346 0, /*tp_getset*/
5347 0, /*tp_base*/
5348 0, /*tp_dict*/
5349 0, /*tp_descr_get*/
5350 0, /*tp_descr_set*/
5351 0, /*tp_dictoffset*/
5352 0, /*tp_init*/
5353 0, /*tp_alloc*/
5354 0, /*tp_new*/
5355 0, /*tp_free*/
5356 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005357};
5358
5359PyObject*
5360PyUnicode_BuildEncodingMap(PyObject* string)
5361{
5362 Py_UNICODE *decode;
5363 PyObject *result;
5364 struct encoding_map *mresult;
5365 int i;
5366 int need_dict = 0;
5367 unsigned char level1[32];
5368 unsigned char level2[512];
5369 unsigned char *mlevel1, *mlevel2, *mlevel3;
5370 int count2 = 0, count3 = 0;
5371
5372 if (!PyUnicode_Check(string) || PyUnicode_GetSize(string) != 256) {
5373 PyErr_BadArgument();
5374 return NULL;
5375 }
5376 decode = PyUnicode_AS_UNICODE(string);
5377 memset(level1, 0xFF, sizeof level1);
5378 memset(level2, 0xFF, sizeof level2);
5379
5380 /* If there isn't a one-to-one mapping of NULL to \0,
5381 or if there are non-BMP characters, we need to use
5382 a mapping dictionary. */
5383 if (decode[0] != 0)
5384 need_dict = 1;
5385 for (i = 1; i < 256; i++) {
5386 int l1, l2;
5387 if (decode[i] == 0
Benjamin Peterson29060642009-01-31 22:14:21 +00005388#ifdef Py_UNICODE_WIDE
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005389 || decode[i] > 0xFFFF
Benjamin Peterson29060642009-01-31 22:14:21 +00005390#endif
5391 ) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005392 need_dict = 1;
5393 break;
5394 }
5395 if (decode[i] == 0xFFFE)
5396 /* unmapped character */
5397 continue;
5398 l1 = decode[i] >> 11;
5399 l2 = decode[i] >> 7;
5400 if (level1[l1] == 0xFF)
5401 level1[l1] = count2++;
5402 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00005403 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005404 }
5405
5406 if (count2 >= 0xFF || count3 >= 0xFF)
5407 need_dict = 1;
5408
5409 if (need_dict) {
5410 PyObject *result = PyDict_New();
5411 PyObject *key, *value;
5412 if (!result)
5413 return NULL;
5414 for (i = 0; i < 256; i++) {
5415 key = value = NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00005416 key = PyLong_FromLong(decode[i]);
5417 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005418 if (!key || !value)
5419 goto failed1;
5420 if (PyDict_SetItem(result, key, value) == -1)
5421 goto failed1;
5422 Py_DECREF(key);
5423 Py_DECREF(value);
5424 }
5425 return result;
5426 failed1:
5427 Py_XDECREF(key);
5428 Py_XDECREF(value);
5429 Py_DECREF(result);
5430 return NULL;
5431 }
5432
5433 /* Create a three-level trie */
5434 result = PyObject_MALLOC(sizeof(struct encoding_map) +
5435 16*count2 + 128*count3 - 1);
5436 if (!result)
5437 return PyErr_NoMemory();
5438 PyObject_Init(result, &EncodingMapType);
5439 mresult = (struct encoding_map*)result;
5440 mresult->count2 = count2;
5441 mresult->count3 = count3;
5442 mlevel1 = mresult->level1;
5443 mlevel2 = mresult->level23;
5444 mlevel3 = mresult->level23 + 16*count2;
5445 memcpy(mlevel1, level1, 32);
5446 memset(mlevel2, 0xFF, 16*count2);
5447 memset(mlevel3, 0, 128*count3);
5448 count3 = 0;
5449 for (i = 1; i < 256; i++) {
5450 int o1, o2, o3, i2, i3;
5451 if (decode[i] == 0xFFFE)
5452 /* unmapped character */
5453 continue;
5454 o1 = decode[i]>>11;
5455 o2 = (decode[i]>>7) & 0xF;
5456 i2 = 16*mlevel1[o1] + o2;
5457 if (mlevel2[i2] == 0xFF)
5458 mlevel2[i2] = count3++;
5459 o3 = decode[i] & 0x7F;
5460 i3 = 128*mlevel2[i2] + o3;
5461 mlevel3[i3] = i;
5462 }
5463 return result;
5464}
5465
5466static int
5467encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
5468{
5469 struct encoding_map *map = (struct encoding_map*)mapping;
5470 int l1 = c>>11;
5471 int l2 = (c>>7) & 0xF;
5472 int l3 = c & 0x7F;
5473 int i;
5474
5475#ifdef Py_UNICODE_WIDE
5476 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005477 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005478 }
5479#endif
5480 if (c == 0)
5481 return 0;
5482 /* level 1*/
5483 i = map->level1[l1];
5484 if (i == 0xFF) {
5485 return -1;
5486 }
5487 /* level 2*/
5488 i = map->level23[16*i+l2];
5489 if (i == 0xFF) {
5490 return -1;
5491 }
5492 /* level 3 */
5493 i = map->level23[16*map->count2 + 128*i + l3];
5494 if (i == 0) {
5495 return -1;
5496 }
5497 return i;
5498}
5499
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005500/* Lookup the character ch in the mapping. If the character
5501 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00005502 error occurred). */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005503static PyObject *charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005504{
Christian Heimes217cfd12007-12-02 14:31:20 +00005505 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005506 PyObject *x;
5507
5508 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005509 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005510 x = PyObject_GetItem(mapping, w);
5511 Py_DECREF(w);
5512 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005513 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5514 /* No mapping found means: mapping is undefined. */
5515 PyErr_Clear();
5516 x = Py_None;
5517 Py_INCREF(x);
5518 return x;
5519 } else
5520 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005521 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00005522 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00005523 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00005524 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005525 long value = PyLong_AS_LONG(x);
5526 if (value < 0 || value > 255) {
5527 PyErr_SetString(PyExc_TypeError,
5528 "character mapping must be in range(256)");
5529 Py_DECREF(x);
5530 return NULL;
5531 }
5532 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005533 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005534 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00005535 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005536 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005537 /* wrong return value */
5538 PyErr_Format(PyExc_TypeError,
5539 "character mapping must return integer, bytes or None, not %.400s",
5540 x->ob_type->tp_name);
5541 Py_DECREF(x);
5542 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005543 }
5544}
5545
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005546static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00005547charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005548{
Benjamin Peterson14339b62009-01-31 16:36:08 +00005549 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
5550 /* exponentially overallocate to minimize reallocations */
5551 if (requiredsize < 2*outsize)
5552 requiredsize = 2*outsize;
5553 if (_PyBytes_Resize(outobj, requiredsize))
5554 return -1;
5555 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005556}
5557
Benjamin Peterson14339b62009-01-31 16:36:08 +00005558typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00005559 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005560}charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005561/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00005562 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005563 space is available. Return a new reference to the object that
5564 was put in the output buffer, or Py_None, if the mapping was undefined
5565 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00005566 reallocation error occurred. The caller must decref the result */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005567static
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005568charmapencode_result charmapencode_output(Py_UNICODE c, PyObject *mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00005569 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005570{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005571 PyObject *rep;
5572 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00005573 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005574
Christian Heimes90aa7642007-12-19 02:45:37 +00005575 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005576 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00005577 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005578 if (res == -1)
5579 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00005580 if (outsize<requiredsize)
5581 if (charmapencode_resize(outobj, outpos, requiredsize))
5582 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00005583 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005584 outstart[(*outpos)++] = (char)res;
5585 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005586 }
5587
5588 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005589 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005590 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005591 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005592 Py_DECREF(rep);
5593 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005594 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005595 if (PyLong_Check(rep)) {
5596 Py_ssize_t requiredsize = *outpos+1;
5597 if (outsize<requiredsize)
5598 if (charmapencode_resize(outobj, outpos, requiredsize)) {
5599 Py_DECREF(rep);
5600 return enc_EXCEPTION;
5601 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005602 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005603 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005604 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005605 else {
5606 const char *repchars = PyBytes_AS_STRING(rep);
5607 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
5608 Py_ssize_t requiredsize = *outpos+repsize;
5609 if (outsize<requiredsize)
5610 if (charmapencode_resize(outobj, outpos, requiredsize)) {
5611 Py_DECREF(rep);
5612 return enc_EXCEPTION;
5613 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005614 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005615 memcpy(outstart + *outpos, repchars, repsize);
5616 *outpos += repsize;
5617 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005618 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005619 Py_DECREF(rep);
5620 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005621}
5622
5623/* handle an error in PyUnicode_EncodeCharmap
5624 Return 0 on success, -1 on error */
5625static
5626int charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00005627 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005628 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00005629 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00005630 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005631{
5632 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005633 Py_ssize_t repsize;
5634 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005635 Py_UNICODE *uni2;
5636 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005637 Py_ssize_t collstartpos = *inpos;
5638 Py_ssize_t collendpos = *inpos+1;
5639 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005640 char *encoding = "charmap";
5641 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005642 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005643
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005644 /* find all unencodable characters */
5645 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005646 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00005647 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005648 int res = encoding_map_lookup(p[collendpos], mapping);
5649 if (res != -1)
5650 break;
5651 ++collendpos;
5652 continue;
5653 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005654
Benjamin Peterson29060642009-01-31 22:14:21 +00005655 rep = charmapencode_lookup(p[collendpos], mapping);
5656 if (rep==NULL)
5657 return -1;
5658 else if (rep!=Py_None) {
5659 Py_DECREF(rep);
5660 break;
5661 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005662 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00005663 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005664 }
5665 /* cache callback name lookup
5666 * (if not done yet, i.e. it's the first error) */
5667 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005668 if ((errors==NULL) || (!strcmp(errors, "strict")))
5669 *known_errorHandler = 1;
5670 else if (!strcmp(errors, "replace"))
5671 *known_errorHandler = 2;
5672 else if (!strcmp(errors, "ignore"))
5673 *known_errorHandler = 3;
5674 else if (!strcmp(errors, "xmlcharrefreplace"))
5675 *known_errorHandler = 4;
5676 else
5677 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005678 }
5679 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005680 case 1: /* strict */
5681 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5682 return -1;
5683 case 2: /* replace */
5684 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005685 x = charmapencode_output('?', mapping, res, respos);
5686 if (x==enc_EXCEPTION) {
5687 return -1;
5688 }
5689 else if (x==enc_FAILED) {
5690 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5691 return -1;
5692 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005693 }
5694 /* fall through */
5695 case 3: /* ignore */
5696 *inpos = collendpos;
5697 break;
5698 case 4: /* xmlcharrefreplace */
5699 /* generate replacement (temporarily (mis)uses p) */
5700 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005701 char buffer[2+29+1+1];
5702 char *cp;
5703 sprintf(buffer, "&#%d;", (int)p[collpos]);
5704 for (cp = buffer; *cp; ++cp) {
5705 x = charmapencode_output(*cp, mapping, res, respos);
5706 if (x==enc_EXCEPTION)
5707 return -1;
5708 else if (x==enc_FAILED) {
5709 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5710 return -1;
5711 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005712 }
5713 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005714 *inpos = collendpos;
5715 break;
5716 default:
5717 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00005718 encoding, reason, p, size, exceptionObject,
5719 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005720 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005721 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005722 if (PyBytes_Check(repunicode)) {
5723 /* Directly copy bytes result to output. */
5724 Py_ssize_t outsize = PyBytes_Size(*res);
5725 Py_ssize_t requiredsize;
5726 repsize = PyBytes_Size(repunicode);
5727 requiredsize = *respos + repsize;
5728 if (requiredsize > outsize)
5729 /* Make room for all additional bytes. */
5730 if (charmapencode_resize(res, respos, requiredsize)) {
5731 Py_DECREF(repunicode);
5732 return -1;
5733 }
5734 memcpy(PyBytes_AsString(*res) + *respos,
5735 PyBytes_AsString(repunicode), repsize);
5736 *respos += repsize;
5737 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005738 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00005739 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005740 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005741 /* generate replacement */
5742 repsize = PyUnicode_GET_SIZE(repunicode);
5743 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005744 x = charmapencode_output(*uni2, mapping, res, respos);
5745 if (x==enc_EXCEPTION) {
5746 return -1;
5747 }
5748 else if (x==enc_FAILED) {
5749 Py_DECREF(repunicode);
5750 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5751 return -1;
5752 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005753 }
5754 *inpos = newpos;
5755 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005756 }
5757 return 0;
5758}
5759
Guido van Rossumd57fd912000-03-10 22:53:23 +00005760PyObject *PyUnicode_EncodeCharmap(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00005761 Py_ssize_t size,
5762 PyObject *mapping,
5763 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005764{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005765 /* output object */
5766 PyObject *res = NULL;
5767 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005768 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005769 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005770 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005771 PyObject *errorHandler = NULL;
5772 PyObject *exc = NULL;
5773 /* the following variable is used for caching string comparisons
5774 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
5775 * 3=ignore, 4=xmlcharrefreplace */
5776 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005777
5778 /* Default to Latin-1 */
5779 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005780 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005781
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005782 /* allocate enough for a simple encoding without
5783 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00005784 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005785 if (res == NULL)
5786 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00005787 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005788 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005789
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005790 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005791 /* try to encode it */
5792 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
5793 if (x==enc_EXCEPTION) /* error */
5794 goto onError;
5795 if (x==enc_FAILED) { /* unencodable character */
5796 if (charmap_encoding_error(p, size, &inpos, mapping,
5797 &exc,
5798 &known_errorHandler, &errorHandler, errors,
5799 &res, &respos)) {
5800 goto onError;
5801 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005802 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005803 else
5804 /* done with this character => adjust input position */
5805 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005806 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005807
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005808 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00005809 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005810 if (_PyBytes_Resize(&res, respos) < 0)
5811 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005812
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005813 Py_XDECREF(exc);
5814 Py_XDECREF(errorHandler);
5815 return res;
5816
Benjamin Peterson29060642009-01-31 22:14:21 +00005817 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005818 Py_XDECREF(res);
5819 Py_XDECREF(exc);
5820 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005821 return NULL;
5822}
5823
5824PyObject *PyUnicode_AsCharmapString(PyObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00005825 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005826{
5827 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005828 PyErr_BadArgument();
5829 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005830 }
5831 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005832 PyUnicode_GET_SIZE(unicode),
5833 mapping,
5834 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005835}
5836
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005837/* create or adjust a UnicodeTranslateError */
5838static void make_translate_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005839 const Py_UNICODE *unicode, Py_ssize_t size,
5840 Py_ssize_t startpos, Py_ssize_t endpos,
5841 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005842{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005843 if (*exceptionObject == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005844 *exceptionObject = PyUnicodeTranslateError_Create(
Benjamin Peterson29060642009-01-31 22:14:21 +00005845 unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005846 }
5847 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005848 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
5849 goto onError;
5850 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
5851 goto onError;
5852 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
5853 goto onError;
5854 return;
5855 onError:
5856 Py_DECREF(*exceptionObject);
5857 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005858 }
5859}
5860
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005861/* raises a UnicodeTranslateError */
5862static void raise_translate_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005863 const Py_UNICODE *unicode, Py_ssize_t size,
5864 Py_ssize_t startpos, Py_ssize_t endpos,
5865 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005866{
5867 make_translate_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005868 unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005869 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005870 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005871}
5872
5873/* error handling callback helper:
5874 build arguments, call the callback and check the arguments,
5875 put the result into newpos and return the replacement string, which
5876 has to be freed by the caller */
5877static PyObject *unicode_translate_call_errorhandler(const char *errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00005878 PyObject **errorHandler,
5879 const char *reason,
5880 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
5881 Py_ssize_t startpos, Py_ssize_t endpos,
5882 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005883{
Benjamin Peterson142957c2008-07-04 19:55:29 +00005884 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005885
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005886 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005887 PyObject *restuple;
5888 PyObject *resunicode;
5889
5890 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005891 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005892 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005893 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005894 }
5895
5896 make_translate_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005897 unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005898 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005899 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005900
5901 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00005902 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005903 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005904 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005905 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00005906 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00005907 Py_DECREF(restuple);
5908 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005909 }
5910 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00005911 &resunicode, &i_newpos)) {
5912 Py_DECREF(restuple);
5913 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005914 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00005915 if (i_newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005916 *newpos = size+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005917 else
5918 *newpos = i_newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005919 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005920 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
5921 Py_DECREF(restuple);
5922 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005923 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005924 Py_INCREF(resunicode);
5925 Py_DECREF(restuple);
5926 return resunicode;
5927}
5928
5929/* Lookup the character ch in the mapping and put the result in result,
5930 which must be decrefed by the caller.
5931 Return 0 on success, -1 on error */
5932static
5933int charmaptranslate_lookup(Py_UNICODE c, PyObject *mapping, PyObject **result)
5934{
Christian Heimes217cfd12007-12-02 14:31:20 +00005935 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005936 PyObject *x;
5937
5938 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005939 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005940 x = PyObject_GetItem(mapping, w);
5941 Py_DECREF(w);
5942 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005943 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5944 /* No mapping found means: use 1:1 mapping. */
5945 PyErr_Clear();
5946 *result = NULL;
5947 return 0;
5948 } else
5949 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005950 }
5951 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005952 *result = x;
5953 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005954 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005955 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005956 long value = PyLong_AS_LONG(x);
5957 long max = PyUnicode_GetMax();
5958 if (value < 0 || value > max) {
5959 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00005960 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00005961 Py_DECREF(x);
5962 return -1;
5963 }
5964 *result = x;
5965 return 0;
5966 }
5967 else if (PyUnicode_Check(x)) {
5968 *result = x;
5969 return 0;
5970 }
5971 else {
5972 /* wrong return value */
5973 PyErr_SetString(PyExc_TypeError,
5974 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00005975 Py_DECREF(x);
5976 return -1;
5977 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005978}
5979/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00005980 if not reallocate and adjust various state variables.
5981 Return 0 on success, -1 on error */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005982static
Walter Dörwald4894c302003-10-24 14:25:28 +00005983int charmaptranslate_makespace(PyObject **outobj, Py_UNICODE **outp,
Benjamin Peterson29060642009-01-31 22:14:21 +00005984 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005985{
Martin v. Löwis18e16552006-02-15 17:27:45 +00005986 Py_ssize_t oldsize = PyUnicode_GET_SIZE(*outobj);
Walter Dörwald4894c302003-10-24 14:25:28 +00005987 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005988 /* remember old output position */
5989 Py_ssize_t outpos = *outp-PyUnicode_AS_UNICODE(*outobj);
5990 /* exponentially overallocate to minimize reallocations */
5991 if (requiredsize < 2 * oldsize)
5992 requiredsize = 2 * oldsize;
5993 if (PyUnicode_Resize(outobj, requiredsize) < 0)
5994 return -1;
5995 *outp = PyUnicode_AS_UNICODE(*outobj) + outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005996 }
5997 return 0;
5998}
5999/* lookup the character, put the result in the output string and adjust
6000 various state variables. Return a new reference to the object that
6001 was put in the output buffer in *result, or Py_None, if the mapping was
6002 undefined (in which case no character was written).
6003 The called must decref result.
6004 Return 0 on success, -1 on error. */
6005static
Walter Dörwald4894c302003-10-24 14:25:28 +00006006int charmaptranslate_output(const Py_UNICODE *startinp, const Py_UNICODE *curinp,
Benjamin Peterson29060642009-01-31 22:14:21 +00006007 Py_ssize_t insize, PyObject *mapping, PyObject **outobj, Py_UNICODE **outp,
6008 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006009{
Walter Dörwald4894c302003-10-24 14:25:28 +00006010 if (charmaptranslate_lookup(*curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00006011 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006012 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006013 /* not found => default to 1:1 mapping */
6014 *(*outp)++ = *curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006015 }
6016 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00006017 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00006018 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006019 /* no overflow check, because we know that the space is enough */
6020 *(*outp)++ = (Py_UNICODE)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006021 }
6022 else if (PyUnicode_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006023 Py_ssize_t repsize = PyUnicode_GET_SIZE(*res);
6024 if (repsize==1) {
6025 /* no overflow check, because we know that the space is enough */
6026 *(*outp)++ = *PyUnicode_AS_UNICODE(*res);
6027 }
6028 else if (repsize!=0) {
6029 /* more than one character */
6030 Py_ssize_t requiredsize = (*outp-PyUnicode_AS_UNICODE(*outobj)) +
6031 (insize - (curinp-startinp)) +
6032 repsize - 1;
6033 if (charmaptranslate_makespace(outobj, outp, requiredsize))
6034 return -1;
6035 memcpy(*outp, PyUnicode_AS_UNICODE(*res), sizeof(Py_UNICODE)*repsize);
6036 *outp += repsize;
6037 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006038 }
6039 else
Benjamin Peterson29060642009-01-31 22:14:21 +00006040 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006041 return 0;
6042}
6043
6044PyObject *PyUnicode_TranslateCharmap(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00006045 Py_ssize_t size,
6046 PyObject *mapping,
6047 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006048{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006049 /* output object */
6050 PyObject *res = NULL;
6051 /* pointers to the beginning and end+1 of input */
6052 const Py_UNICODE *startp = p;
6053 const Py_UNICODE *endp = p + size;
6054 /* pointer into the output */
6055 Py_UNICODE *str;
6056 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006057 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006058 char *reason = "character maps to <undefined>";
6059 PyObject *errorHandler = NULL;
6060 PyObject *exc = NULL;
6061 /* the following variable is used for caching string comparisons
6062 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
6063 * 3=ignore, 4=xmlcharrefreplace */
6064 int known_errorHandler = -1;
6065
Guido van Rossumd57fd912000-03-10 22:53:23 +00006066 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006067 PyErr_BadArgument();
6068 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006069 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006070
6071 /* allocate enough for a simple 1:1 translation without
6072 replacements, if we need more, we'll resize */
6073 res = PyUnicode_FromUnicode(NULL, size);
6074 if (res == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006075 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006076 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006077 return res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006078 str = PyUnicode_AS_UNICODE(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006079
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006080 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006081 /* try to encode it */
6082 PyObject *x = NULL;
6083 if (charmaptranslate_output(startp, p, size, mapping, &res, &str, &x)) {
6084 Py_XDECREF(x);
6085 goto onError;
6086 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006087 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00006088 if (x!=Py_None) /* it worked => adjust input pointer */
6089 ++p;
6090 else { /* untranslatable character */
6091 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
6092 Py_ssize_t repsize;
6093 Py_ssize_t newpos;
6094 Py_UNICODE *uni2;
6095 /* startpos for collecting untranslatable chars */
6096 const Py_UNICODE *collstart = p;
6097 const Py_UNICODE *collend = p+1;
6098 const Py_UNICODE *coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006099
Benjamin Peterson29060642009-01-31 22:14:21 +00006100 /* find all untranslatable characters */
6101 while (collend < endp) {
6102 if (charmaptranslate_lookup(*collend, mapping, &x))
6103 goto onError;
6104 Py_XDECREF(x);
6105 if (x!=Py_None)
6106 break;
6107 ++collend;
6108 }
6109 /* cache callback name lookup
6110 * (if not done yet, i.e. it's the first error) */
6111 if (known_errorHandler==-1) {
6112 if ((errors==NULL) || (!strcmp(errors, "strict")))
6113 known_errorHandler = 1;
6114 else if (!strcmp(errors, "replace"))
6115 known_errorHandler = 2;
6116 else if (!strcmp(errors, "ignore"))
6117 known_errorHandler = 3;
6118 else if (!strcmp(errors, "xmlcharrefreplace"))
6119 known_errorHandler = 4;
6120 else
6121 known_errorHandler = 0;
6122 }
6123 switch (known_errorHandler) {
6124 case 1: /* strict */
6125 raise_translate_exception(&exc, startp, size, collstart-startp, collend-startp, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006126 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006127 case 2: /* replace */
6128 /* No need to check for space, this is a 1:1 replacement */
6129 for (coll = collstart; coll<collend; ++coll)
6130 *str++ = '?';
6131 /* fall through */
6132 case 3: /* ignore */
6133 p = collend;
6134 break;
6135 case 4: /* xmlcharrefreplace */
6136 /* generate replacement (temporarily (mis)uses p) */
6137 for (p = collstart; p < collend; ++p) {
6138 char buffer[2+29+1+1];
6139 char *cp;
6140 sprintf(buffer, "&#%d;", (int)*p);
6141 if (charmaptranslate_makespace(&res, &str,
6142 (str-PyUnicode_AS_UNICODE(res))+strlen(buffer)+(endp-collend)))
6143 goto onError;
6144 for (cp = buffer; *cp; ++cp)
6145 *str++ = *cp;
6146 }
6147 p = collend;
6148 break;
6149 default:
6150 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
6151 reason, startp, size, &exc,
6152 collstart-startp, collend-startp, &newpos);
6153 if (repunicode == NULL)
6154 goto onError;
6155 /* generate replacement */
6156 repsize = PyUnicode_GET_SIZE(repunicode);
6157 if (charmaptranslate_makespace(&res, &str,
6158 (str-PyUnicode_AS_UNICODE(res))+repsize+(endp-collend))) {
6159 Py_DECREF(repunicode);
6160 goto onError;
6161 }
6162 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2)
6163 *str++ = *uni2;
6164 p = startp + newpos;
6165 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006166 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006167 }
6168 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006169 /* Resize if we allocated to much */
6170 respos = str-PyUnicode_AS_UNICODE(res);
Walter Dörwald4894c302003-10-24 14:25:28 +00006171 if (respos<PyUnicode_GET_SIZE(res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006172 if (PyUnicode_Resize(&res, respos) < 0)
6173 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006174 }
6175 Py_XDECREF(exc);
6176 Py_XDECREF(errorHandler);
6177 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006178
Benjamin Peterson29060642009-01-31 22:14:21 +00006179 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006180 Py_XDECREF(res);
6181 Py_XDECREF(exc);
6182 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006183 return NULL;
6184}
6185
6186PyObject *PyUnicode_Translate(PyObject *str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006187 PyObject *mapping,
6188 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006189{
6190 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00006191
Guido van Rossumd57fd912000-03-10 22:53:23 +00006192 str = PyUnicode_FromObject(str);
6193 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006194 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006195 result = PyUnicode_TranslateCharmap(PyUnicode_AS_UNICODE(str),
Benjamin Peterson29060642009-01-31 22:14:21 +00006196 PyUnicode_GET_SIZE(str),
6197 mapping,
6198 errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006199 Py_DECREF(str);
6200 return result;
Tim Petersced69f82003-09-16 20:30:58 +00006201
Benjamin Peterson29060642009-01-31 22:14:21 +00006202 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006203 Py_XDECREF(str);
6204 return NULL;
6205}
Tim Petersced69f82003-09-16 20:30:58 +00006206
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00006207PyObject *
6208PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
6209 Py_ssize_t length)
6210{
6211 PyObject *result;
6212 Py_UNICODE *p; /* write pointer into result */
6213 Py_ssize_t i;
6214 /* Copy to a new string */
6215 result = (PyObject *)_PyUnicode_New(length);
6216 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
6217 if (result == NULL)
6218 return result;
6219 p = PyUnicode_AS_UNICODE(result);
6220 /* Iterate over code points */
6221 for (i = 0; i < length; i++) {
6222 Py_UNICODE ch =s[i];
6223 if (ch > 127) {
6224 int decimal = Py_UNICODE_TODECIMAL(ch);
6225 if (decimal >= 0)
6226 p[i] = '0' + decimal;
6227 }
6228 }
6229 return result;
6230}
Guido van Rossum9e896b32000-04-05 20:11:21 +00006231/* --- Decimal Encoder ---------------------------------------------------- */
6232
6233int PyUnicode_EncodeDecimal(Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00006234 Py_ssize_t length,
6235 char *output,
6236 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00006237{
6238 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006239 PyObject *errorHandler = NULL;
6240 PyObject *exc = NULL;
6241 const char *encoding = "decimal";
6242 const char *reason = "invalid decimal Unicode string";
6243 /* the following variable is used for caching string comparisons
6244 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6245 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00006246
6247 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006248 PyErr_BadArgument();
6249 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00006250 }
6251
6252 p = s;
6253 end = s + length;
6254 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006255 register Py_UNICODE ch = *p;
6256 int decimal;
6257 PyObject *repunicode;
6258 Py_ssize_t repsize;
6259 Py_ssize_t newpos;
6260 Py_UNICODE *uni2;
6261 Py_UNICODE *collstart;
6262 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00006263
Benjamin Peterson29060642009-01-31 22:14:21 +00006264 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006265 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00006266 ++p;
6267 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006268 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006269 decimal = Py_UNICODE_TODECIMAL(ch);
6270 if (decimal >= 0) {
6271 *output++ = '0' + decimal;
6272 ++p;
6273 continue;
6274 }
6275 if (0 < ch && ch < 256) {
6276 *output++ = (char)ch;
6277 ++p;
6278 continue;
6279 }
6280 /* All other characters are considered unencodable */
6281 collstart = p;
6282 collend = p+1;
6283 while (collend < end) {
6284 if ((0 < *collend && *collend < 256) ||
6285 !Py_UNICODE_ISSPACE(*collend) ||
6286 Py_UNICODE_TODECIMAL(*collend))
6287 break;
6288 }
6289 /* cache callback name lookup
6290 * (if not done yet, i.e. it's the first error) */
6291 if (known_errorHandler==-1) {
6292 if ((errors==NULL) || (!strcmp(errors, "strict")))
6293 known_errorHandler = 1;
6294 else if (!strcmp(errors, "replace"))
6295 known_errorHandler = 2;
6296 else if (!strcmp(errors, "ignore"))
6297 known_errorHandler = 3;
6298 else if (!strcmp(errors, "xmlcharrefreplace"))
6299 known_errorHandler = 4;
6300 else
6301 known_errorHandler = 0;
6302 }
6303 switch (known_errorHandler) {
6304 case 1: /* strict */
6305 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
6306 goto onError;
6307 case 2: /* replace */
6308 for (p = collstart; p < collend; ++p)
6309 *output++ = '?';
6310 /* fall through */
6311 case 3: /* ignore */
6312 p = collend;
6313 break;
6314 case 4: /* xmlcharrefreplace */
6315 /* generate replacement (temporarily (mis)uses p) */
6316 for (p = collstart; p < collend; ++p)
6317 output += sprintf(output, "&#%d;", (int)*p);
6318 p = collend;
6319 break;
6320 default:
6321 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
6322 encoding, reason, s, length, &exc,
6323 collstart-s, collend-s, &newpos);
6324 if (repunicode == NULL)
6325 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006326 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006327 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006328 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
6329 Py_DECREF(repunicode);
6330 goto onError;
6331 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006332 /* generate replacement */
6333 repsize = PyUnicode_GET_SIZE(repunicode);
6334 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
6335 Py_UNICODE ch = *uni2;
6336 if (Py_UNICODE_ISSPACE(ch))
6337 *output++ = ' ';
6338 else {
6339 decimal = Py_UNICODE_TODECIMAL(ch);
6340 if (decimal >= 0)
6341 *output++ = '0' + decimal;
6342 else if (0 < ch && ch < 256)
6343 *output++ = (char)ch;
6344 else {
6345 Py_DECREF(repunicode);
6346 raise_encode_exception(&exc, encoding,
6347 s, length, collstart-s, collend-s, reason);
6348 goto onError;
6349 }
6350 }
6351 }
6352 p = s + newpos;
6353 Py_DECREF(repunicode);
6354 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00006355 }
6356 /* 0-terminate the output string */
6357 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006358 Py_XDECREF(exc);
6359 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00006360 return 0;
6361
Benjamin Peterson29060642009-01-31 22:14:21 +00006362 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006363 Py_XDECREF(exc);
6364 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00006365 return -1;
6366}
6367
Guido van Rossumd57fd912000-03-10 22:53:23 +00006368/* --- Helpers ------------------------------------------------------------ */
6369
Eric Smith8c663262007-08-25 02:26:07 +00006370#include "stringlib/unicodedefs.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00006371#include "stringlib/fastsearch.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006372
Thomas Wouters477c8d52006-05-27 19:21:47 +00006373#include "stringlib/count.h"
6374#include "stringlib/find.h"
6375#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006376#include "stringlib/split.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00006377
Eric Smith5807c412008-05-11 21:00:57 +00006378#define _Py_InsertThousandsGrouping _PyUnicode_InsertThousandsGrouping
Eric Smitha3b1ac82009-04-03 14:45:06 +00006379#define _Py_InsertThousandsGroupingLocale _PyUnicode_InsertThousandsGroupingLocale
Eric Smith5807c412008-05-11 21:00:57 +00006380#include "stringlib/localeutil.h"
6381
Thomas Wouters477c8d52006-05-27 19:21:47 +00006382/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006383#define ADJUST_INDICES(start, end, len) \
6384 if (end > len) \
6385 end = len; \
6386 else if (end < 0) { \
6387 end += len; \
6388 if (end < 0) \
6389 end = 0; \
6390 } \
6391 if (start < 0) { \
6392 start += len; \
6393 if (start < 0) \
6394 start = 0; \
6395 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00006396
Martin v. Löwis18e16552006-02-15 17:27:45 +00006397Py_ssize_t PyUnicode_Count(PyObject *str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00006398 PyObject *substr,
6399 Py_ssize_t start,
6400 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006401{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006402 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006403 PyUnicodeObject* str_obj;
6404 PyUnicodeObject* sub_obj;
Tim Petersced69f82003-09-16 20:30:58 +00006405
Thomas Wouters477c8d52006-05-27 19:21:47 +00006406 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
6407 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00006408 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006409 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
6410 if (!sub_obj) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006411 Py_DECREF(str_obj);
6412 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006413 }
Tim Petersced69f82003-09-16 20:30:58 +00006414
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006415 ADJUST_INDICES(start, end, str_obj->length);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006416 result = stringlib_count(
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006417 str_obj->str + start, end - start, sub_obj->str, sub_obj->length,
6418 PY_SSIZE_T_MAX
Thomas Wouters477c8d52006-05-27 19:21:47 +00006419 );
6420
6421 Py_DECREF(sub_obj);
6422 Py_DECREF(str_obj);
6423
Guido van Rossumd57fd912000-03-10 22:53:23 +00006424 return result;
6425}
6426
Martin v. Löwis18e16552006-02-15 17:27:45 +00006427Py_ssize_t PyUnicode_Find(PyObject *str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00006428 PyObject *sub,
6429 Py_ssize_t start,
6430 Py_ssize_t end,
6431 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006432{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006433 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00006434
Guido van Rossumd57fd912000-03-10 22:53:23 +00006435 str = PyUnicode_FromObject(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006436 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00006437 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006438 sub = PyUnicode_FromObject(sub);
6439 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006440 Py_DECREF(str);
6441 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006442 }
Tim Petersced69f82003-09-16 20:30:58 +00006443
Thomas Wouters477c8d52006-05-27 19:21:47 +00006444 if (direction > 0)
6445 result = stringlib_find_slice(
6446 PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
6447 PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
6448 start, end
6449 );
6450 else
6451 result = stringlib_rfind_slice(
6452 PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
6453 PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
6454 start, end
6455 );
6456
Guido van Rossumd57fd912000-03-10 22:53:23 +00006457 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006458 Py_DECREF(sub);
6459
Guido van Rossumd57fd912000-03-10 22:53:23 +00006460 return result;
6461}
6462
Tim Petersced69f82003-09-16 20:30:58 +00006463static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006464int tailmatch(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006465 PyUnicodeObject *substring,
6466 Py_ssize_t start,
6467 Py_ssize_t end,
6468 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006469{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006470 if (substring->length == 0)
6471 return 1;
6472
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006473 ADJUST_INDICES(start, end, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006474 end -= substring->length;
6475 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00006476 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006477
6478 if (direction > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006479 if (Py_UNICODE_MATCH(self, end, substring))
6480 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006481 } else {
6482 if (Py_UNICODE_MATCH(self, start, substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00006483 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006484 }
6485
6486 return 0;
6487}
6488
Martin v. Löwis18e16552006-02-15 17:27:45 +00006489Py_ssize_t PyUnicode_Tailmatch(PyObject *str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006490 PyObject *substr,
6491 Py_ssize_t start,
6492 Py_ssize_t end,
6493 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006494{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006495 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00006496
Guido van Rossumd57fd912000-03-10 22:53:23 +00006497 str = PyUnicode_FromObject(str);
6498 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006499 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006500 substr = PyUnicode_FromObject(substr);
6501 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006502 Py_DECREF(str);
6503 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006504 }
Tim Petersced69f82003-09-16 20:30:58 +00006505
Guido van Rossumd57fd912000-03-10 22:53:23 +00006506 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006507 (PyUnicodeObject *)substr,
6508 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006509 Py_DECREF(str);
6510 Py_DECREF(substr);
6511 return result;
6512}
6513
Guido van Rossumd57fd912000-03-10 22:53:23 +00006514/* Apply fixfct filter to the Unicode object self and return a
6515 reference to the modified object */
6516
Tim Petersced69f82003-09-16 20:30:58 +00006517static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006518PyObject *fixup(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006519 int (*fixfct)(PyUnicodeObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00006520{
6521
6522 PyUnicodeObject *u;
6523
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006524 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006525 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006526 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006527
6528 Py_UNICODE_COPY(u->str, self->str, self->length);
6529
Tim Peters7a29bd52001-09-12 03:03:31 +00006530 if (!fixfct(u) && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006531 /* fixfct should return TRUE if it modified the buffer. If
6532 FALSE, return a reference to the original buffer instead
6533 (to save space, not time) */
6534 Py_INCREF(self);
6535 Py_DECREF(u);
6536 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006537 }
6538 return (PyObject*) u;
6539}
6540
Tim Petersced69f82003-09-16 20:30:58 +00006541static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006542int fixupper(PyUnicodeObject *self)
6543{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006544 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006545 Py_UNICODE *s = self->str;
6546 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006547
Guido van Rossumd57fd912000-03-10 22:53:23 +00006548 while (len-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006549 register Py_UNICODE ch;
Tim Petersced69f82003-09-16 20:30:58 +00006550
Benjamin Peterson29060642009-01-31 22:14:21 +00006551 ch = Py_UNICODE_TOUPPER(*s);
6552 if (ch != *s) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006553 status = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006554 *s = ch;
6555 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006556 s++;
6557 }
6558
6559 return status;
6560}
6561
Tim Petersced69f82003-09-16 20:30:58 +00006562static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006563int fixlower(PyUnicodeObject *self)
6564{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006565 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006566 Py_UNICODE *s = self->str;
6567 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006568
Guido van Rossumd57fd912000-03-10 22:53:23 +00006569 while (len-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006570 register Py_UNICODE ch;
Tim Petersced69f82003-09-16 20:30:58 +00006571
Benjamin Peterson29060642009-01-31 22:14:21 +00006572 ch = Py_UNICODE_TOLOWER(*s);
6573 if (ch != *s) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006574 status = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006575 *s = ch;
6576 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006577 s++;
6578 }
6579
6580 return status;
6581}
6582
Tim Petersced69f82003-09-16 20:30:58 +00006583static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006584int fixswapcase(PyUnicodeObject *self)
6585{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006586 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006587 Py_UNICODE *s = self->str;
6588 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006589
Guido van Rossumd57fd912000-03-10 22:53:23 +00006590 while (len-- > 0) {
6591 if (Py_UNICODE_ISUPPER(*s)) {
6592 *s = Py_UNICODE_TOLOWER(*s);
6593 status = 1;
6594 } else if (Py_UNICODE_ISLOWER(*s)) {
6595 *s = Py_UNICODE_TOUPPER(*s);
6596 status = 1;
6597 }
6598 s++;
6599 }
6600
6601 return status;
6602}
6603
Tim Petersced69f82003-09-16 20:30:58 +00006604static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006605int fixcapitalize(PyUnicodeObject *self)
6606{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006607 Py_ssize_t len = self->length;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006608 Py_UNICODE *s = self->str;
6609 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006610
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006611 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006612 return 0;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006613 if (Py_UNICODE_ISLOWER(*s)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006614 *s = Py_UNICODE_TOUPPER(*s);
6615 status = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006616 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006617 s++;
6618 while (--len > 0) {
6619 if (Py_UNICODE_ISUPPER(*s)) {
6620 *s = Py_UNICODE_TOLOWER(*s);
6621 status = 1;
6622 }
6623 s++;
6624 }
6625 return status;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006626}
6627
6628static
6629int fixtitle(PyUnicodeObject *self)
6630{
6631 register Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
6632 register Py_UNICODE *e;
6633 int previous_is_cased;
6634
6635 /* Shortcut for single character strings */
6636 if (PyUnicode_GET_SIZE(self) == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006637 Py_UNICODE ch = Py_UNICODE_TOTITLE(*p);
6638 if (*p != ch) {
6639 *p = ch;
6640 return 1;
6641 }
6642 else
6643 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006644 }
Tim Petersced69f82003-09-16 20:30:58 +00006645
Guido van Rossumd57fd912000-03-10 22:53:23 +00006646 e = p + PyUnicode_GET_SIZE(self);
6647 previous_is_cased = 0;
6648 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006649 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00006650
Benjamin Peterson29060642009-01-31 22:14:21 +00006651 if (previous_is_cased)
6652 *p = Py_UNICODE_TOLOWER(ch);
6653 else
6654 *p = Py_UNICODE_TOTITLE(ch);
Tim Petersced69f82003-09-16 20:30:58 +00006655
Benjamin Peterson29060642009-01-31 22:14:21 +00006656 if (Py_UNICODE_ISLOWER(ch) ||
6657 Py_UNICODE_ISUPPER(ch) ||
6658 Py_UNICODE_ISTITLE(ch))
6659 previous_is_cased = 1;
6660 else
6661 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006662 }
6663 return 1;
6664}
6665
Tim Peters8ce9f162004-08-27 01:49:32 +00006666PyObject *
6667PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006668{
Skip Montanaro6543b452004-09-16 03:28:13 +00006669 const Py_UNICODE blank = ' ';
6670 const Py_UNICODE *sep = &blank;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006671 Py_ssize_t seplen = 1;
Tim Peters05eba1f2004-08-27 21:32:02 +00006672 PyUnicodeObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00006673 Py_UNICODE *res_p; /* pointer to free byte in res's string area */
6674 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006675 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
6676 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00006677 PyObject *item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006678 Py_ssize_t sz, i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006679
Tim Peters05eba1f2004-08-27 21:32:02 +00006680 fseq = PySequence_Fast(seq, "");
6681 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006682 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00006683 }
6684
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006685 /* NOTE: the following code can't call back into Python code,
6686 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00006687 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006688
Tim Peters05eba1f2004-08-27 21:32:02 +00006689 seqlen = PySequence_Fast_GET_SIZE(fseq);
6690 /* If empty sequence, return u"". */
6691 if (seqlen == 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006692 res = _PyUnicode_New(0); /* empty sequence; return u"" */
6693 goto Done;
Tim Peters05eba1f2004-08-27 21:32:02 +00006694 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006695 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00006696 /* If singleton sequence with an exact Unicode, return that. */
6697 if (seqlen == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006698 item = items[0];
6699 if (PyUnicode_CheckExact(item)) {
6700 Py_INCREF(item);
6701 res = (PyUnicodeObject *)item;
6702 goto Done;
6703 }
Tim Peters8ce9f162004-08-27 01:49:32 +00006704 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006705 else {
6706 /* Set up sep and seplen */
6707 if (separator == NULL) {
6708 sep = &blank;
6709 seplen = 1;
Tim Peters05eba1f2004-08-27 21:32:02 +00006710 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006711 else {
6712 if (!PyUnicode_Check(separator)) {
6713 PyErr_Format(PyExc_TypeError,
6714 "separator: expected str instance,"
6715 " %.80s found",
6716 Py_TYPE(separator)->tp_name);
6717 goto onError;
6718 }
6719 sep = PyUnicode_AS_UNICODE(separator);
6720 seplen = PyUnicode_GET_SIZE(separator);
Tim Peters05eba1f2004-08-27 21:32:02 +00006721 }
6722 }
6723
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006724 /* There are at least two things to join, or else we have a subclass
6725 * of str in the sequence.
6726 * Do a pre-pass to figure out the total amount of space we'll
6727 * need (sz), and see whether all argument are strings.
6728 */
6729 sz = 0;
6730 for (i = 0; i < seqlen; i++) {
6731 const Py_ssize_t old_sz = sz;
6732 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00006733 if (!PyUnicode_Check(item)) {
6734 PyErr_Format(PyExc_TypeError,
6735 "sequence item %zd: expected str instance,"
6736 " %.80s found",
6737 i, Py_TYPE(item)->tp_name);
6738 goto onError;
6739 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006740 sz += PyUnicode_GET_SIZE(item);
6741 if (i != 0)
6742 sz += seplen;
6743 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
6744 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00006745 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006746 goto onError;
6747 }
6748 }
Tim Petersced69f82003-09-16 20:30:58 +00006749
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006750 res = _PyUnicode_New(sz);
6751 if (res == NULL)
6752 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00006753
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006754 /* Catenate everything. */
6755 res_p = PyUnicode_AS_UNICODE(res);
6756 for (i = 0; i < seqlen; ++i) {
6757 Py_ssize_t itemlen;
6758 item = items[i];
6759 itemlen = PyUnicode_GET_SIZE(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00006760 /* Copy item, and maybe the separator. */
6761 if (i) {
6762 Py_UNICODE_COPY(res_p, sep, seplen);
6763 res_p += seplen;
6764 }
6765 Py_UNICODE_COPY(res_p, PyUnicode_AS_UNICODE(item), itemlen);
6766 res_p += itemlen;
Tim Peters05eba1f2004-08-27 21:32:02 +00006767 }
Tim Peters8ce9f162004-08-27 01:49:32 +00006768
Benjamin Peterson29060642009-01-31 22:14:21 +00006769 Done:
Tim Peters05eba1f2004-08-27 21:32:02 +00006770 Py_DECREF(fseq);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006771 return (PyObject *)res;
6772
Benjamin Peterson29060642009-01-31 22:14:21 +00006773 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00006774 Py_DECREF(fseq);
Tim Peters8ce9f162004-08-27 01:49:32 +00006775 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006776 return NULL;
6777}
6778
Tim Petersced69f82003-09-16 20:30:58 +00006779static
6780PyUnicodeObject *pad(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006781 Py_ssize_t left,
6782 Py_ssize_t right,
6783 Py_UNICODE fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006784{
6785 PyUnicodeObject *u;
6786
6787 if (left < 0)
6788 left = 0;
6789 if (right < 0)
6790 right = 0;
6791
Tim Peters7a29bd52001-09-12 03:03:31 +00006792 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006793 Py_INCREF(self);
6794 return self;
6795 }
6796
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006797 if (left > PY_SSIZE_T_MAX - self->length ||
6798 right > PY_SSIZE_T_MAX - (left + self->length)) {
6799 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
6800 return NULL;
6801 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006802 u = _PyUnicode_New(left + self->length + right);
6803 if (u) {
6804 if (left)
6805 Py_UNICODE_FILL(u->str, fill, left);
6806 Py_UNICODE_COPY(u->str + left, self->str, self->length);
6807 if (right)
6808 Py_UNICODE_FILL(u->str + left + self->length, fill, right);
6809 }
6810
6811 return u;
6812}
6813
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006814PyObject *PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006815{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006816 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006817
6818 string = PyUnicode_FromObject(string);
6819 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006820 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006821
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006822 list = stringlib_splitlines(
6823 (PyObject*) string, PyUnicode_AS_UNICODE(string),
6824 PyUnicode_GET_SIZE(string), keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006825
6826 Py_DECREF(string);
6827 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006828}
6829
Tim Petersced69f82003-09-16 20:30:58 +00006830static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006831PyObject *split(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006832 PyUnicodeObject *substring,
6833 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006834{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006835 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006836 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006837
Guido van Rossumd57fd912000-03-10 22:53:23 +00006838 if (substring == NULL)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006839 return stringlib_split_whitespace(
6840 (PyObject*) self, self->str, self->length, maxcount
6841 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00006842
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006843 return stringlib_split(
6844 (PyObject*) self, self->str, self->length,
6845 substring->str, substring->length,
6846 maxcount
6847 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00006848}
6849
Tim Petersced69f82003-09-16 20:30:58 +00006850static
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006851PyObject *rsplit(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006852 PyUnicodeObject *substring,
6853 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006854{
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006855 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006856 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006857
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006858 if (substring == NULL)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006859 return stringlib_rsplit_whitespace(
6860 (PyObject*) self, self->str, self->length, maxcount
6861 );
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006862
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006863 return stringlib_rsplit(
6864 (PyObject*) self, self->str, self->length,
6865 substring->str, substring->length,
6866 maxcount
6867 );
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006868}
6869
6870static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006871PyObject *replace(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006872 PyUnicodeObject *str1,
6873 PyUnicodeObject *str2,
6874 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006875{
6876 PyUnicodeObject *u;
6877
6878 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006879 maxcount = PY_SSIZE_T_MAX;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006880 else if (maxcount == 0 || self->length == 0)
6881 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006882
Thomas Wouters477c8d52006-05-27 19:21:47 +00006883 if (str1->length == str2->length) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +00006884 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006885 /* same length */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006886 if (str1->length == 0)
6887 goto nothing;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006888 if (str1->length == 1) {
6889 /* replace characters */
6890 Py_UNICODE u1, u2;
6891 if (!findchar(self->str, self->length, str1->str[0]))
6892 goto nothing;
6893 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
6894 if (!u)
6895 return NULL;
6896 Py_UNICODE_COPY(u->str, self->str, self->length);
6897 u1 = str1->str[0];
6898 u2 = str2->str[0];
6899 for (i = 0; i < u->length; i++)
6900 if (u->str[i] == u1) {
6901 if (--maxcount < 0)
6902 break;
6903 u->str[i] = u2;
6904 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006905 } else {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006906 i = stringlib_find(
6907 self->str, self->length, str1->str, str1->length, 0
Guido van Rossumd57fd912000-03-10 22:53:23 +00006908 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00006909 if (i < 0)
6910 goto nothing;
6911 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
6912 if (!u)
6913 return NULL;
6914 Py_UNICODE_COPY(u->str, self->str, self->length);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006915
6916 /* change everything in-place, starting with this one */
6917 Py_UNICODE_COPY(u->str+i, str2->str, str2->length);
6918 i += str1->length;
6919
6920 while ( --maxcount > 0) {
6921 i = stringlib_find(self->str+i, self->length-i,
6922 str1->str, str1->length,
6923 i);
6924 if (i == -1)
6925 break;
6926 Py_UNICODE_COPY(u->str+i, str2->str, str2->length);
6927 i += str1->length;
6928 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006929 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006930 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006931
6932 Py_ssize_t n, i, j, e;
6933 Py_ssize_t product, new_size, delta;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006934 Py_UNICODE *p;
6935
6936 /* replace strings */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006937 n = stringlib_count(self->str, self->length, str1->str, str1->length,
6938 maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006939 if (n == 0)
6940 goto nothing;
6941 /* new_size = self->length + n * (str2->length - str1->length)); */
6942 delta = (str2->length - str1->length);
6943 if (delta == 0) {
6944 new_size = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006945 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006946 product = n * (str2->length - str1->length);
6947 if ((product / (str2->length - str1->length)) != n) {
6948 PyErr_SetString(PyExc_OverflowError,
6949 "replace string is too long");
6950 return NULL;
6951 }
6952 new_size = self->length + product;
6953 if (new_size < 0) {
6954 PyErr_SetString(PyExc_OverflowError,
6955 "replace string is too long");
6956 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006957 }
6958 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00006959 u = _PyUnicode_New(new_size);
6960 if (!u)
6961 return NULL;
6962 i = 0;
6963 p = u->str;
6964 e = self->length - str1->length;
6965 if (str1->length > 0) {
6966 while (n-- > 0) {
6967 /* look for next match */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006968 j = stringlib_find(self->str+i, self->length-i,
6969 str1->str, str1->length,
6970 i);
6971 if (j == -1)
6972 break;
6973 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006974 /* copy unchanged part [i:j] */
6975 Py_UNICODE_COPY(p, self->str+i, j-i);
6976 p += j - i;
6977 }
6978 /* copy substitution string */
6979 if (str2->length > 0) {
6980 Py_UNICODE_COPY(p, str2->str, str2->length);
6981 p += str2->length;
6982 }
6983 i = j + str1->length;
6984 }
6985 if (i < self->length)
6986 /* copy tail [i:] */
6987 Py_UNICODE_COPY(p, self->str+i, self->length-i);
6988 } else {
6989 /* interleave */
6990 while (n > 0) {
6991 Py_UNICODE_COPY(p, str2->str, str2->length);
6992 p += str2->length;
6993 if (--n <= 0)
6994 break;
6995 *p++ = self->str[i++];
6996 }
6997 Py_UNICODE_COPY(p, self->str+i, self->length-i);
6998 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006999 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007000 return (PyObject *) u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007001
Benjamin Peterson29060642009-01-31 22:14:21 +00007002 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00007003 /* nothing to replace; return original string (when possible) */
7004 if (PyUnicode_CheckExact(self)) {
7005 Py_INCREF(self);
7006 return (PyObject *) self;
7007 }
7008 return PyUnicode_FromUnicode(self->str, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007009}
7010
7011/* --- Unicode Object Methods --------------------------------------------- */
7012
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007013PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007014 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007015\n\
7016Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007017characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007018
7019static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007020unicode_title(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007021{
Guido van Rossumd57fd912000-03-10 22:53:23 +00007022 return fixup(self, fixtitle);
7023}
7024
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007025PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007026 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007027\n\
7028Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +00007029have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007030
7031static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007032unicode_capitalize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007033{
Guido van Rossumd57fd912000-03-10 22:53:23 +00007034 return fixup(self, fixcapitalize);
7035}
7036
7037#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007038PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007039 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007040\n\
7041Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007042normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007043
7044static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007045unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007046{
7047 PyObject *list;
7048 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007049 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007050
Guido van Rossumd57fd912000-03-10 22:53:23 +00007051 /* Split into words */
7052 list = split(self, NULL, -1);
7053 if (!list)
7054 return NULL;
7055
7056 /* Capitalize each word */
7057 for (i = 0; i < PyList_GET_SIZE(list); i++) {
7058 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00007059 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007060 if (item == NULL)
7061 goto onError;
7062 Py_DECREF(PyList_GET_ITEM(list, i));
7063 PyList_SET_ITEM(list, i, item);
7064 }
7065
7066 /* Join the words to form a new string */
7067 item = PyUnicode_Join(NULL, list);
7068
Benjamin Peterson29060642009-01-31 22:14:21 +00007069 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007070 Py_DECREF(list);
7071 return (PyObject *)item;
7072}
7073#endif
7074
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007075/* Argument converter. Coerces to a single unicode character */
7076
7077static int
7078convert_uc(PyObject *obj, void *addr)
7079{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007080 Py_UNICODE *fillcharloc = (Py_UNICODE *)addr;
7081 PyObject *uniobj;
7082 Py_UNICODE *unistr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007083
Benjamin Peterson14339b62009-01-31 16:36:08 +00007084 uniobj = PyUnicode_FromObject(obj);
7085 if (uniobj == NULL) {
7086 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00007087 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007088 return 0;
7089 }
7090 if (PyUnicode_GET_SIZE(uniobj) != 1) {
7091 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00007092 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007093 Py_DECREF(uniobj);
7094 return 0;
7095 }
7096 unistr = PyUnicode_AS_UNICODE(uniobj);
7097 *fillcharloc = unistr[0];
7098 Py_DECREF(uniobj);
7099 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007100}
7101
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007102PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007103 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007104\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007105Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007106done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007107
7108static PyObject *
7109unicode_center(PyUnicodeObject *self, PyObject *args)
7110{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007111 Py_ssize_t marg, left;
7112 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007113 Py_UNICODE fillchar = ' ';
Guido van Rossumd57fd912000-03-10 22:53:23 +00007114
Thomas Woutersde017742006-02-16 19:34:37 +00007115 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007116 return NULL;
7117
Tim Peters7a29bd52001-09-12 03:03:31 +00007118 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00007119 Py_INCREF(self);
7120 return (PyObject*) self;
7121 }
7122
7123 marg = width - self->length;
7124 left = marg / 2 + (marg & width & 1);
7125
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007126 return (PyObject*) pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007127}
7128
Marc-André Lemburge5034372000-08-08 08:04:29 +00007129#if 0
7130
7131/* This code should go into some future Unicode collation support
7132 module. The basic comparison should compare ordinals on a naive
Georg Brandlc6c31782009-06-08 13:41:29 +00007133 basis (this is what Java does and thus Jython too). */
Marc-André Lemburge5034372000-08-08 08:04:29 +00007134
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007135/* speedy UTF-16 code point order comparison */
7136/* gleaned from: */
7137/* http://www-4.ibm.com/software/developer/library/utf16.html?dwzone=unicode */
7138
Marc-André Lemburge12896e2000-07-07 17:51:08 +00007139static short utf16Fixup[32] =
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007140{
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007141 0, 0, 0, 0, 0, 0, 0, 0,
Tim Petersced69f82003-09-16 20:30:58 +00007142 0, 0, 0, 0, 0, 0, 0, 0,
7143 0, 0, 0, 0, 0, 0, 0, 0,
Marc-André Lemburge12896e2000-07-07 17:51:08 +00007144 0, 0, 0, 0x2000, -0x800, -0x800, -0x800, -0x800
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007145};
7146
Guido van Rossumd57fd912000-03-10 22:53:23 +00007147static int
7148unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
7149{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007150 Py_ssize_t len1, len2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007151
Guido van Rossumd57fd912000-03-10 22:53:23 +00007152 Py_UNICODE *s1 = str1->str;
7153 Py_UNICODE *s2 = str2->str;
7154
7155 len1 = str1->length;
7156 len2 = str2->length;
Tim Petersced69f82003-09-16 20:30:58 +00007157
Guido van Rossumd57fd912000-03-10 22:53:23 +00007158 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00007159 Py_UNICODE c1, c2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007160
7161 c1 = *s1++;
7162 c2 = *s2++;
Fredrik Lundh45714e92001-06-26 16:39:36 +00007163
Benjamin Peterson29060642009-01-31 22:14:21 +00007164 if (c1 > (1<<11) * 26)
7165 c1 += utf16Fixup[c1>>11];
7166 if (c2 > (1<<11) * 26)
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007167 c2 += utf16Fixup[c2>>11];
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007168 /* now c1 and c2 are in UTF-32-compatible order */
Fredrik Lundh45714e92001-06-26 16:39:36 +00007169
7170 if (c1 != c2)
7171 return (c1 < c2) ? -1 : 1;
Tim Petersced69f82003-09-16 20:30:58 +00007172
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007173 len1--; len2--;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007174 }
7175
7176 return (len1 < len2) ? -1 : (len1 != len2);
7177}
7178
Marc-André Lemburge5034372000-08-08 08:04:29 +00007179#else
7180
7181static int
7182unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
7183{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007184 register Py_ssize_t len1, len2;
Marc-André Lemburge5034372000-08-08 08:04:29 +00007185
7186 Py_UNICODE *s1 = str1->str;
7187 Py_UNICODE *s2 = str2->str;
7188
7189 len1 = str1->length;
7190 len2 = str2->length;
Tim Petersced69f82003-09-16 20:30:58 +00007191
Marc-André Lemburge5034372000-08-08 08:04:29 +00007192 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00007193 Py_UNICODE c1, c2;
Marc-André Lemburge5034372000-08-08 08:04:29 +00007194
Fredrik Lundh45714e92001-06-26 16:39:36 +00007195 c1 = *s1++;
7196 c2 = *s2++;
7197
7198 if (c1 != c2)
7199 return (c1 < c2) ? -1 : 1;
7200
Marc-André Lemburge5034372000-08-08 08:04:29 +00007201 len1--; len2--;
7202 }
7203
7204 return (len1 < len2) ? -1 : (len1 != len2);
7205}
7206
7207#endif
7208
Guido van Rossumd57fd912000-03-10 22:53:23 +00007209int PyUnicode_Compare(PyObject *left,
Benjamin Peterson29060642009-01-31 22:14:21 +00007210 PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007211{
Guido van Rossum09dc34f2007-05-04 04:17:33 +00007212 if (PyUnicode_Check(left) && PyUnicode_Check(right))
7213 return unicode_compare((PyUnicodeObject *)left,
7214 (PyUnicodeObject *)right);
Guido van Rossum09dc34f2007-05-04 04:17:33 +00007215 PyErr_Format(PyExc_TypeError,
7216 "Can't compare %.100s and %.100s",
7217 left->ob_type->tp_name,
7218 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007219 return -1;
7220}
7221
Martin v. Löwis5b222132007-06-10 09:51:05 +00007222int
7223PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
7224{
7225 int i;
7226 Py_UNICODE *id;
7227 assert(PyUnicode_Check(uni));
7228 id = PyUnicode_AS_UNICODE(uni);
7229 /* Compare Unicode string and source character set string */
7230 for (i = 0; id[i] && str[i]; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00007231 if (id[i] != str[i])
7232 return ((int)id[i] < (int)str[i]) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +00007233 /* This check keeps Python strings that end in '\0' from comparing equal
7234 to C strings identical up to that point. */
Benjamin Petersona23831f2010-04-25 21:54:00 +00007235 if (PyUnicode_GET_SIZE(uni) != i || id[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00007236 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00007237 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00007238 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00007239 return 0;
7240}
7241
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007242
Benjamin Peterson29060642009-01-31 22:14:21 +00007243#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +00007244 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007245
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007246PyObject *PyUnicode_RichCompare(PyObject *left,
7247 PyObject *right,
7248 int op)
7249{
7250 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007251
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007252 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
7253 PyObject *v;
7254 if (((PyUnicodeObject *) left)->length !=
7255 ((PyUnicodeObject *) right)->length) {
7256 if (op == Py_EQ) {
7257 Py_INCREF(Py_False);
7258 return Py_False;
7259 }
7260 if (op == Py_NE) {
7261 Py_INCREF(Py_True);
7262 return Py_True;
7263 }
7264 }
7265 if (left == right)
7266 result = 0;
7267 else
7268 result = unicode_compare((PyUnicodeObject *)left,
7269 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007270
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007271 /* Convert the return value to a Boolean */
7272 switch (op) {
7273 case Py_EQ:
7274 v = TEST_COND(result == 0);
7275 break;
7276 case Py_NE:
7277 v = TEST_COND(result != 0);
7278 break;
7279 case Py_LE:
7280 v = TEST_COND(result <= 0);
7281 break;
7282 case Py_GE:
7283 v = TEST_COND(result >= 0);
7284 break;
7285 case Py_LT:
7286 v = TEST_COND(result == -1);
7287 break;
7288 case Py_GT:
7289 v = TEST_COND(result == 1);
7290 break;
7291 default:
7292 PyErr_BadArgument();
7293 return NULL;
7294 }
7295 Py_INCREF(v);
7296 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007297 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007298
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007299 Py_INCREF(Py_NotImplemented);
7300 return Py_NotImplemented;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007301}
7302
Guido van Rossum403d68b2000-03-13 15:55:09 +00007303int PyUnicode_Contains(PyObject *container,
Benjamin Peterson29060642009-01-31 22:14:21 +00007304 PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +00007305{
Thomas Wouters477c8d52006-05-27 19:21:47 +00007306 PyObject *str, *sub;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007307 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007308
7309 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +00007310 sub = PyUnicode_FromObject(element);
7311 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007312 PyErr_Format(PyExc_TypeError,
7313 "'in <string>' requires string as left operand, not %s",
7314 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007315 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007316 }
7317
Thomas Wouters477c8d52006-05-27 19:21:47 +00007318 str = PyUnicode_FromObject(container);
7319 if (!str) {
7320 Py_DECREF(sub);
7321 return -1;
7322 }
7323
7324 result = stringlib_contains_obj(str, sub);
7325
7326 Py_DECREF(str);
7327 Py_DECREF(sub);
7328
Guido van Rossum403d68b2000-03-13 15:55:09 +00007329 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007330}
7331
Guido van Rossumd57fd912000-03-10 22:53:23 +00007332/* Concat to string or Unicode object giving a new Unicode object. */
7333
7334PyObject *PyUnicode_Concat(PyObject *left,
Benjamin Peterson29060642009-01-31 22:14:21 +00007335 PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007336{
7337 PyUnicodeObject *u = NULL, *v = NULL, *w;
7338
7339 /* Coerce the two arguments */
7340 u = (PyUnicodeObject *)PyUnicode_FromObject(left);
7341 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007342 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007343 v = (PyUnicodeObject *)PyUnicode_FromObject(right);
7344 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007345 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007346
7347 /* Shortcuts */
7348 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007349 Py_DECREF(v);
7350 return (PyObject *)u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007351 }
7352 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007353 Py_DECREF(u);
7354 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007355 }
7356
7357 /* Concat the two Unicode strings */
7358 w = _PyUnicode_New(u->length + v->length);
7359 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007360 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007361 Py_UNICODE_COPY(w->str, u->str, u->length);
7362 Py_UNICODE_COPY(w->str + u->length, v->str, v->length);
7363
7364 Py_DECREF(u);
7365 Py_DECREF(v);
7366 return (PyObject *)w;
7367
Benjamin Peterson29060642009-01-31 22:14:21 +00007368 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007369 Py_XDECREF(u);
7370 Py_XDECREF(v);
7371 return NULL;
7372}
7373
Walter Dörwald1ab83302007-05-18 17:15:44 +00007374void
7375PyUnicode_Append(PyObject **pleft, PyObject *right)
7376{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007377 PyObject *new;
7378 if (*pleft == NULL)
7379 return;
7380 if (right == NULL || !PyUnicode_Check(*pleft)) {
7381 Py_DECREF(*pleft);
7382 *pleft = NULL;
7383 return;
7384 }
7385 new = PyUnicode_Concat(*pleft, right);
7386 Py_DECREF(*pleft);
7387 *pleft = new;
Walter Dörwald1ab83302007-05-18 17:15:44 +00007388}
7389
7390void
7391PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
7392{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007393 PyUnicode_Append(pleft, right);
7394 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +00007395}
7396
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007397PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007398 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007399\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00007400Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007401string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007402interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007403
7404static PyObject *
7405unicode_count(PyUnicodeObject *self, PyObject *args)
7406{
7407 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007408 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007409 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007410 PyObject *result;
7411
Guido van Rossumb8872e62000-05-09 14:14:27 +00007412 if (!PyArg_ParseTuple(args, "O|O&O&:count", &substring,
Benjamin Peterson29060642009-01-31 22:14:21 +00007413 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007414 return NULL;
7415
7416 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Thomas Wouters477c8d52006-05-27 19:21:47 +00007417 (PyObject *)substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007418 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007419 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007420
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007421 ADJUST_INDICES(start, end, self->length);
Christian Heimes217cfd12007-12-02 14:31:20 +00007422 result = PyLong_FromSsize_t(
Thomas Wouters477c8d52006-05-27 19:21:47 +00007423 stringlib_count(self->str + start, end - start,
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007424 substring->str, substring->length,
7425 PY_SSIZE_T_MAX)
Thomas Wouters477c8d52006-05-27 19:21:47 +00007426 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007427
7428 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007429
Guido van Rossumd57fd912000-03-10 22:53:23 +00007430 return result;
7431}
7432
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007433PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +00007434 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007435\n\
Victor Stinnere14e2122010-11-07 18:41:46 +00007436Encode S using the codec registered for encoding. Default encoding\n\
7437is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +00007438handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007439a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
7440'xmlcharrefreplace' as well as any other name registered with\n\
7441codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007442
7443static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +00007444unicode_encode(PyUnicodeObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007445{
Benjamin Peterson308d6372009-09-18 21:42:35 +00007446 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +00007447 char *encoding = NULL;
7448 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +00007449
Benjamin Peterson308d6372009-09-18 21:42:35 +00007450 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
7451 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007452 return NULL;
Georg Brandl3b9406b2010-12-03 07:54:09 +00007453 return PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007454}
7455
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007456PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007457 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007458\n\
7459Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007460If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007461
7462static PyObject*
7463unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
7464{
7465 Py_UNICODE *e;
7466 Py_UNICODE *p;
7467 Py_UNICODE *q;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007468 Py_UNICODE *qe;
7469 Py_ssize_t i, j, incr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007470 PyUnicodeObject *u;
7471 int tabsize = 8;
7472
7473 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00007474 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007475
Thomas Wouters7e474022000-07-16 12:04:32 +00007476 /* First pass: determine size of output string */
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007477 i = 0; /* chars up to and including most recent \n or \r */
7478 j = 0; /* chars since most recent \n or \r (use in tab calculations) */
7479 e = self->str + self->length; /* end of input */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007480 for (p = self->str; p < e; p++)
7481 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007482 if (tabsize > 0) {
7483 incr = tabsize - (j % tabsize); /* cannot overflow */
7484 if (j > PY_SSIZE_T_MAX - incr)
7485 goto overflow1;
7486 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007487 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007488 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007489 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007490 if (j > PY_SSIZE_T_MAX - 1)
7491 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007492 j++;
7493 if (*p == '\n' || *p == '\r') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007494 if (i > PY_SSIZE_T_MAX - j)
7495 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007496 i += j;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007497 j = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007498 }
7499 }
7500
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007501 if (i > PY_SSIZE_T_MAX - j)
Benjamin Peterson29060642009-01-31 22:14:21 +00007502 goto overflow1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007503
Guido van Rossumd57fd912000-03-10 22:53:23 +00007504 /* Second pass: create output string and fill it */
7505 u = _PyUnicode_New(i + j);
7506 if (!u)
7507 return NULL;
7508
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007509 j = 0; /* same as in first pass */
7510 q = u->str; /* next output char */
7511 qe = u->str + u->length; /* end of output */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007512
7513 for (p = self->str; p < e; p++)
7514 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007515 if (tabsize > 0) {
7516 i = tabsize - (j % tabsize);
7517 j += i;
7518 while (i--) {
7519 if (q >= qe)
7520 goto overflow2;
7521 *q++ = ' ';
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007522 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007523 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007524 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007525 else {
7526 if (q >= qe)
7527 goto overflow2;
7528 *q++ = *p;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007529 j++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007530 if (*p == '\n' || *p == '\r')
7531 j = 0;
7532 }
7533
7534 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007535
7536 overflow2:
7537 Py_DECREF(u);
7538 overflow1:
7539 PyErr_SetString(PyExc_OverflowError, "new string is too long");
7540 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007541}
7542
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007543PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007544 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007545\n\
7546Return the lowest index in S where substring sub is found,\n\
Guido van Rossum806c2462007-08-06 23:33:07 +00007547such that sub is contained within s[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007548arguments start and end are interpreted as in slice notation.\n\
7549\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007550Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007551
7552static PyObject *
7553unicode_find(PyUnicodeObject *self, PyObject *args)
7554{
Thomas Wouters477c8d52006-05-27 19:21:47 +00007555 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00007556 Py_ssize_t start;
7557 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007558 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007559
Christian Heimes9cd17752007-11-18 19:35:23 +00007560 if (!_ParseTupleFinds(args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007561 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007562
Thomas Wouters477c8d52006-05-27 19:21:47 +00007563 result = stringlib_find_slice(
7564 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
7565 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
7566 start, end
7567 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007568
7569 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007570
Christian Heimes217cfd12007-12-02 14:31:20 +00007571 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007572}
7573
7574static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00007575unicode_getitem(PyUnicodeObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007576{
7577 if (index < 0 || index >= self->length) {
7578 PyErr_SetString(PyExc_IndexError, "string index out of range");
7579 return NULL;
7580 }
7581
7582 return (PyObject*) PyUnicode_FromUnicode(&self->str[index], 1);
7583}
7584
Guido van Rossumc2504932007-09-18 19:42:40 +00007585/* Believe it or not, this produces the same value for ASCII strings
7586 as string_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00007587static Py_hash_t
Neil Schemenauerf8c37d12007-09-07 20:49:04 +00007588unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007589{
Guido van Rossumc2504932007-09-18 19:42:40 +00007590 Py_ssize_t len;
7591 Py_UNICODE *p;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00007592 Py_hash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +00007593
7594 if (self->hash != -1)
7595 return self->hash;
Christian Heimes90aa7642007-12-19 02:45:37 +00007596 len = Py_SIZE(self);
Guido van Rossumc2504932007-09-18 19:42:40 +00007597 p = self->str;
7598 x = *p << 7;
7599 while (--len >= 0)
7600 x = (1000003*x) ^ *p++;
Christian Heimes90aa7642007-12-19 02:45:37 +00007601 x ^= Py_SIZE(self);
Guido van Rossumc2504932007-09-18 19:42:40 +00007602 if (x == -1)
7603 x = -2;
7604 self->hash = x;
7605 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007606}
7607
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007608PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007609 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007610\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007611Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007612
7613static PyObject *
7614unicode_index(PyUnicodeObject *self, PyObject *args)
7615{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007616 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007617 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00007618 Py_ssize_t start;
7619 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007620
Christian Heimes9cd17752007-11-18 19:35:23 +00007621 if (!_ParseTupleFinds(args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007622 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007623
Thomas Wouters477c8d52006-05-27 19:21:47 +00007624 result = stringlib_find_slice(
7625 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
7626 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
7627 start, end
7628 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007629
7630 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007631
Guido van Rossumd57fd912000-03-10 22:53:23 +00007632 if (result < 0) {
7633 PyErr_SetString(PyExc_ValueError, "substring not found");
7634 return NULL;
7635 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00007636
Christian Heimes217cfd12007-12-02 14:31:20 +00007637 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007638}
7639
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007640PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007641 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007642\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007643Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007644at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007645
7646static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007647unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007648{
7649 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7650 register const Py_UNICODE *e;
7651 int cased;
7652
Guido van Rossumd57fd912000-03-10 22:53:23 +00007653 /* Shortcut for single character strings */
7654 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007655 return PyBool_FromLong(Py_UNICODE_ISLOWER(*p));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007656
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007657 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007658 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007659 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007660
Guido van Rossumd57fd912000-03-10 22:53:23 +00007661 e = p + PyUnicode_GET_SIZE(self);
7662 cased = 0;
7663 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007664 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007665
Benjamin Peterson29060642009-01-31 22:14:21 +00007666 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
7667 return PyBool_FromLong(0);
7668 else if (!cased && Py_UNICODE_ISLOWER(ch))
7669 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007670 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007671 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007672}
7673
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007674PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007675 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007676\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007677Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007678at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007679
7680static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007681unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007682{
7683 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7684 register const Py_UNICODE *e;
7685 int cased;
7686
Guido van Rossumd57fd912000-03-10 22:53:23 +00007687 /* Shortcut for single character strings */
7688 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007689 return PyBool_FromLong(Py_UNICODE_ISUPPER(*p) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007690
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007691 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007692 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007693 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007694
Guido van Rossumd57fd912000-03-10 22:53:23 +00007695 e = p + PyUnicode_GET_SIZE(self);
7696 cased = 0;
7697 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007698 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007699
Benjamin Peterson29060642009-01-31 22:14:21 +00007700 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
7701 return PyBool_FromLong(0);
7702 else if (!cased && Py_UNICODE_ISUPPER(ch))
7703 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007704 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007705 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007706}
7707
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007708PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007709 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007710\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007711Return True if S is a titlecased string and there is at least one\n\
7712character in S, i.e. upper- and titlecase characters may only\n\
7713follow uncased characters and lowercase characters only cased ones.\n\
7714Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007715
7716static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007717unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007718{
7719 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7720 register const Py_UNICODE *e;
7721 int cased, previous_is_cased;
7722
Guido van Rossumd57fd912000-03-10 22:53:23 +00007723 /* Shortcut for single character strings */
7724 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007725 return PyBool_FromLong((Py_UNICODE_ISTITLE(*p) != 0) ||
7726 (Py_UNICODE_ISUPPER(*p) != 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007727
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007728 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007729 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007730 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007731
Guido van Rossumd57fd912000-03-10 22:53:23 +00007732 e = p + PyUnicode_GET_SIZE(self);
7733 cased = 0;
7734 previous_is_cased = 0;
7735 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007736 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007737
Benjamin Peterson29060642009-01-31 22:14:21 +00007738 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
7739 if (previous_is_cased)
7740 return PyBool_FromLong(0);
7741 previous_is_cased = 1;
7742 cased = 1;
7743 }
7744 else if (Py_UNICODE_ISLOWER(ch)) {
7745 if (!previous_is_cased)
7746 return PyBool_FromLong(0);
7747 previous_is_cased = 1;
7748 cased = 1;
7749 }
7750 else
7751 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007752 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007753 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007754}
7755
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007756PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007757 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007758\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007759Return True if all characters in S are whitespace\n\
7760and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007761
7762static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007763unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007764{
7765 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7766 register const Py_UNICODE *e;
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 Py_UNICODE_ISSPACE(*p))
7771 return PyBool_FromLong(1);
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 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007779 if (!Py_UNICODE_ISSPACE(*p))
7780 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007781 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007782 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007783}
7784
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007785PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007786 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007787\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007788Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007789and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007790
7791static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007792unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007793{
7794 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7795 register const Py_UNICODE *e;
7796
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007797 /* Shortcut for single character strings */
7798 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007799 Py_UNICODE_ISALPHA(*p))
7800 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007801
7802 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007803 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007804 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007805
7806 e = p + PyUnicode_GET_SIZE(self);
7807 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007808 if (!Py_UNICODE_ISALPHA(*p))
7809 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007810 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007811 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007812}
7813
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007814PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007815 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007816\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007817Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007818and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007819
7820static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007821unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007822{
7823 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7824 register const Py_UNICODE *e;
7825
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007826 /* Shortcut for single character strings */
7827 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007828 Py_UNICODE_ISALNUM(*p))
7829 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007830
7831 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007832 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007833 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007834
7835 e = p + PyUnicode_GET_SIZE(self);
7836 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007837 if (!Py_UNICODE_ISALNUM(*p))
7838 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007839 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007840 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007841}
7842
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007843PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007844 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007845\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007846Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007847False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007848
7849static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007850unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007851{
7852 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7853 register const Py_UNICODE *e;
7854
Guido van Rossumd57fd912000-03-10 22:53:23 +00007855 /* Shortcut for single character strings */
7856 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007857 Py_UNICODE_ISDECIMAL(*p))
7858 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007859
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007860 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007861 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007862 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007863
Guido van Rossumd57fd912000-03-10 22:53:23 +00007864 e = p + PyUnicode_GET_SIZE(self);
7865 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007866 if (!Py_UNICODE_ISDECIMAL(*p))
7867 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007868 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007869 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007870}
7871
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007872PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007873 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007874\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007875Return True if all characters in S are digits\n\
7876and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007877
7878static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007879unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007880{
7881 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7882 register const Py_UNICODE *e;
7883
Guido van Rossumd57fd912000-03-10 22:53:23 +00007884 /* Shortcut for single character strings */
7885 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007886 Py_UNICODE_ISDIGIT(*p))
7887 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007888
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007889 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007890 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007891 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007892
Guido van Rossumd57fd912000-03-10 22:53:23 +00007893 e = p + PyUnicode_GET_SIZE(self);
7894 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007895 if (!Py_UNICODE_ISDIGIT(*p))
7896 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007897 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007898 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007899}
7900
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007901PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007902 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007903\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007904Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007905False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007906
7907static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007908unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007909{
7910 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7911 register const Py_UNICODE *e;
7912
Guido van Rossumd57fd912000-03-10 22:53:23 +00007913 /* Shortcut for single character strings */
7914 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007915 Py_UNICODE_ISNUMERIC(*p))
7916 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007917
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007918 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007919 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007920 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007921
Guido van Rossumd57fd912000-03-10 22:53:23 +00007922 e = p + PyUnicode_GET_SIZE(self);
7923 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007924 if (!Py_UNICODE_ISNUMERIC(*p))
7925 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007926 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007927 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007928}
7929
Martin v. Löwis47383402007-08-15 07:32:56 +00007930int
7931PyUnicode_IsIdentifier(PyObject *self)
7932{
7933 register const Py_UNICODE *p = PyUnicode_AS_UNICODE((PyUnicodeObject*)self);
7934 register const Py_UNICODE *e;
7935
7936 /* Special case for empty strings */
7937 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007938 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +00007939
7940 /* PEP 3131 says that the first character must be in
7941 XID_Start and subsequent characters in XID_Continue,
7942 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +00007943 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +00007944 letters, digits, underscore). However, given the current
7945 definition of XID_Start and XID_Continue, it is sufficient
7946 to check just for these, except that _ must be allowed
7947 as starting an identifier. */
7948 if (!_PyUnicode_IsXidStart(*p) && *p != 0x5F /* LOW LINE */)
7949 return 0;
7950
7951 e = p + PyUnicode_GET_SIZE(self);
7952 for (p++; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007953 if (!_PyUnicode_IsXidContinue(*p))
7954 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +00007955 }
7956 return 1;
7957}
7958
7959PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007960 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +00007961\n\
7962Return True if S is a valid identifier according\n\
7963to the language definition.");
7964
7965static PyObject*
7966unicode_isidentifier(PyObject *self)
7967{
7968 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
7969}
7970
Georg Brandl559e5d72008-06-11 18:37:52 +00007971PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007972 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +00007973\n\
7974Return True if all characters in S are considered\n\
7975printable in repr() or S is empty, False otherwise.");
7976
7977static PyObject*
7978unicode_isprintable(PyObject *self)
7979{
7980 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7981 register const Py_UNICODE *e;
7982
7983 /* Shortcut for single character strings */
7984 if (PyUnicode_GET_SIZE(self) == 1 && Py_UNICODE_ISPRINTABLE(*p)) {
7985 Py_RETURN_TRUE;
7986 }
7987
7988 e = p + PyUnicode_GET_SIZE(self);
7989 for (; p < e; p++) {
7990 if (!Py_UNICODE_ISPRINTABLE(*p)) {
7991 Py_RETURN_FALSE;
7992 }
7993 }
7994 Py_RETURN_TRUE;
7995}
7996
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007997PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +00007998 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007999\n\
8000Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +00008001iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008002
8003static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008004unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008005{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008006 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008007}
8008
Martin v. Löwis18e16552006-02-15 17:27:45 +00008009static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +00008010unicode_length(PyUnicodeObject *self)
8011{
8012 return self->length;
8013}
8014
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008015PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008016 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008017\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008018Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008019done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008020
8021static PyObject *
8022unicode_ljust(PyUnicodeObject *self, PyObject *args)
8023{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008024 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008025 Py_UNICODE fillchar = ' ';
8026
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008027 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008028 return NULL;
8029
Tim Peters7a29bd52001-09-12 03:03:31 +00008030 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008031 Py_INCREF(self);
8032 return (PyObject*) self;
8033 }
8034
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008035 return (PyObject*) pad(self, 0, width - self->length, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008036}
8037
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008038PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008039 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008040\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008041Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008042
8043static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008044unicode_lower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008045{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008046 return fixup(self, fixlower);
8047}
8048
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008049#define LEFTSTRIP 0
8050#define RIGHTSTRIP 1
8051#define BOTHSTRIP 2
8052
8053/* Arrays indexed by above */
8054static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
8055
8056#define STRIPNAME(i) (stripformat[i]+3)
8057
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008058/* externally visible for str.strip(unicode) */
8059PyObject *
8060_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
8061{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008062 Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
8063 Py_ssize_t len = PyUnicode_GET_SIZE(self);
8064 Py_UNICODE *sep = PyUnicode_AS_UNICODE(sepobj);
8065 Py_ssize_t seplen = PyUnicode_GET_SIZE(sepobj);
8066 Py_ssize_t i, j;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008067
Benjamin Peterson29060642009-01-31 22:14:21 +00008068 BLOOM_MASK sepmask = make_bloom_mask(sep, seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008069
Benjamin Peterson14339b62009-01-31 16:36:08 +00008070 i = 0;
8071 if (striptype != RIGHTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008072 while (i < len && BLOOM_MEMBER(sepmask, s[i], sep, seplen)) {
8073 i++;
8074 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008075 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008076
Benjamin Peterson14339b62009-01-31 16:36:08 +00008077 j = len;
8078 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008079 do {
8080 j--;
8081 } while (j >= i && BLOOM_MEMBER(sepmask, s[j], sep, seplen));
8082 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008083 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008084
Benjamin Peterson14339b62009-01-31 16:36:08 +00008085 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008086 Py_INCREF(self);
8087 return (PyObject*)self;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008088 }
8089 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008090 return PyUnicode_FromUnicode(s+i, j-i);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008091}
8092
Guido van Rossumd57fd912000-03-10 22:53:23 +00008093
8094static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008095do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008096{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008097 Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
8098 Py_ssize_t len = PyUnicode_GET_SIZE(self), i, j;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008099
Benjamin Peterson14339b62009-01-31 16:36:08 +00008100 i = 0;
8101 if (striptype != RIGHTSTRIP) {
8102 while (i < len && Py_UNICODE_ISSPACE(s[i])) {
8103 i++;
8104 }
8105 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008106
Benjamin Peterson14339b62009-01-31 16:36:08 +00008107 j = len;
8108 if (striptype != LEFTSTRIP) {
8109 do {
8110 j--;
8111 } while (j >= i && Py_UNICODE_ISSPACE(s[j]));
8112 j++;
8113 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008114
Benjamin Peterson14339b62009-01-31 16:36:08 +00008115 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
8116 Py_INCREF(self);
8117 return (PyObject*)self;
8118 }
8119 else
8120 return PyUnicode_FromUnicode(s+i, j-i);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008121}
8122
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008123
8124static PyObject *
8125do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
8126{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008127 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008128
Benjamin Peterson14339b62009-01-31 16:36:08 +00008129 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
8130 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008131
Benjamin Peterson14339b62009-01-31 16:36:08 +00008132 if (sep != NULL && sep != Py_None) {
8133 if (PyUnicode_Check(sep))
8134 return _PyUnicode_XStrip(self, striptype, sep);
8135 else {
8136 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00008137 "%s arg must be None or str",
8138 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +00008139 return NULL;
8140 }
8141 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008142
Benjamin Peterson14339b62009-01-31 16:36:08 +00008143 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008144}
8145
8146
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008147PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008148 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008149\n\
8150Return a copy of the string S with leading and trailing\n\
8151whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008152If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008153
8154static PyObject *
8155unicode_strip(PyUnicodeObject *self, PyObject *args)
8156{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008157 if (PyTuple_GET_SIZE(args) == 0)
8158 return do_strip(self, BOTHSTRIP); /* Common case */
8159 else
8160 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008161}
8162
8163
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008164PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008165 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008166\n\
8167Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008168If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008169
8170static PyObject *
8171unicode_lstrip(PyUnicodeObject *self, PyObject *args)
8172{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008173 if (PyTuple_GET_SIZE(args) == 0)
8174 return do_strip(self, LEFTSTRIP); /* Common case */
8175 else
8176 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008177}
8178
8179
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008180PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008181 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008182\n\
8183Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008184If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008185
8186static PyObject *
8187unicode_rstrip(PyUnicodeObject *self, PyObject *args)
8188{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008189 if (PyTuple_GET_SIZE(args) == 0)
8190 return do_strip(self, RIGHTSTRIP); /* Common case */
8191 else
8192 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008193}
8194
8195
Guido van Rossumd57fd912000-03-10 22:53:23 +00008196static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +00008197unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008198{
8199 PyUnicodeObject *u;
8200 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008201 Py_ssize_t nchars;
Tim Peters8f422462000-09-09 06:13:41 +00008202 size_t nbytes;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008203
Georg Brandl222de0f2009-04-12 12:01:50 +00008204 if (len < 1) {
8205 Py_INCREF(unicode_empty);
8206 return (PyObject *)unicode_empty;
8207 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008208
Tim Peters7a29bd52001-09-12 03:03:31 +00008209 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008210 /* no repeat, return original string */
8211 Py_INCREF(str);
8212 return (PyObject*) str;
8213 }
Tim Peters8f422462000-09-09 06:13:41 +00008214
8215 /* ensure # of chars needed doesn't overflow int and # of bytes
8216 * needed doesn't overflow size_t
8217 */
8218 nchars = len * str->length;
Georg Brandl222de0f2009-04-12 12:01:50 +00008219 if (nchars / len != str->length) {
Tim Peters8f422462000-09-09 06:13:41 +00008220 PyErr_SetString(PyExc_OverflowError,
8221 "repeated string is too long");
8222 return NULL;
8223 }
8224 nbytes = (nchars + 1) * sizeof(Py_UNICODE);
8225 if (nbytes / sizeof(Py_UNICODE) != (size_t)(nchars + 1)) {
8226 PyErr_SetString(PyExc_OverflowError,
8227 "repeated string is too long");
8228 return NULL;
8229 }
8230 u = _PyUnicode_New(nchars);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008231 if (!u)
8232 return NULL;
8233
8234 p = u->str;
8235
Georg Brandl222de0f2009-04-12 12:01:50 +00008236 if (str->length == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00008237 Py_UNICODE_FILL(p, str->str[0], len);
8238 } else {
Georg Brandl222de0f2009-04-12 12:01:50 +00008239 Py_ssize_t done = str->length; /* number of characters copied this far */
8240 Py_UNICODE_COPY(p, str->str, str->length);
Benjamin Peterson29060642009-01-31 22:14:21 +00008241 while (done < nchars) {
Christian Heimescc47b052008-03-25 14:56:36 +00008242 Py_ssize_t n = (done <= nchars-done) ? done : nchars-done;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008243 Py_UNICODE_COPY(p+done, p, n);
8244 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00008245 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008246 }
8247
8248 return (PyObject*) u;
8249}
8250
8251PyObject *PyUnicode_Replace(PyObject *obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00008252 PyObject *subobj,
8253 PyObject *replobj,
8254 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008255{
8256 PyObject *self;
8257 PyObject *str1;
8258 PyObject *str2;
8259 PyObject *result;
8260
8261 self = PyUnicode_FromObject(obj);
8262 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008263 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008264 str1 = PyUnicode_FromObject(subobj);
8265 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008266 Py_DECREF(self);
8267 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008268 }
8269 str2 = PyUnicode_FromObject(replobj);
8270 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008271 Py_DECREF(self);
8272 Py_DECREF(str1);
8273 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008274 }
Tim Petersced69f82003-09-16 20:30:58 +00008275 result = replace((PyUnicodeObject *)self,
Benjamin Peterson29060642009-01-31 22:14:21 +00008276 (PyUnicodeObject *)str1,
8277 (PyUnicodeObject *)str2,
8278 maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008279 Py_DECREF(self);
8280 Py_DECREF(str1);
8281 Py_DECREF(str2);
8282 return result;
8283}
8284
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008285PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +00008286 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008287\n\
8288Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +00008289old replaced by new. If the optional argument count is\n\
8290given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008291
8292static PyObject*
8293unicode_replace(PyUnicodeObject *self, PyObject *args)
8294{
8295 PyUnicodeObject *str1;
8296 PyUnicodeObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008297 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008298 PyObject *result;
8299
Martin v. Löwis18e16552006-02-15 17:27:45 +00008300 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008301 return NULL;
8302 str1 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str1);
8303 if (str1 == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008304 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008305 str2 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str2);
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +00008306 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008307 Py_DECREF(str1);
8308 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +00008309 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008310
8311 result = replace(self, str1, str2, maxcount);
8312
8313 Py_DECREF(str1);
8314 Py_DECREF(str2);
8315 return result;
8316}
8317
8318static
8319PyObject *unicode_repr(PyObject *unicode)
8320{
Walter Dörwald79e913e2007-05-12 11:08:06 +00008321 PyObject *repr;
Walter Dörwald1ab83302007-05-18 17:15:44 +00008322 Py_UNICODE *p;
Walter Dörwald79e913e2007-05-12 11:08:06 +00008323 Py_UNICODE *s = PyUnicode_AS_UNICODE(unicode);
8324 Py_ssize_t size = PyUnicode_GET_SIZE(unicode);
8325
8326 /* XXX(nnorwitz): rather than over-allocating, it would be
8327 better to choose a different scheme. Perhaps scan the
8328 first N-chars of the string and allocate based on that size.
8329 */
8330 /* Initial allocation is based on the longest-possible unichr
8331 escape.
8332
8333 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
8334 unichr, so in this case it's the longest unichr escape. In
8335 narrow (UTF-16) builds this is five chars per source unichr
8336 since there are two unichrs in the surrogate pair, so in narrow
8337 (UTF-16) builds it's not the longest unichr escape.
8338
8339 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
8340 so in the narrow (UTF-16) build case it's the longest unichr
8341 escape.
8342 */
8343
Walter Dörwald1ab83302007-05-18 17:15:44 +00008344 repr = PyUnicode_FromUnicode(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00008345 2 /* quotes */
Walter Dörwald79e913e2007-05-12 11:08:06 +00008346#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00008347 + 10*size
Walter Dörwald79e913e2007-05-12 11:08:06 +00008348#else
Benjamin Peterson29060642009-01-31 22:14:21 +00008349 + 6*size
Walter Dörwald79e913e2007-05-12 11:08:06 +00008350#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00008351 + 1);
Walter Dörwald79e913e2007-05-12 11:08:06 +00008352 if (repr == NULL)
8353 return NULL;
8354
Walter Dörwald1ab83302007-05-18 17:15:44 +00008355 p = PyUnicode_AS_UNICODE(repr);
Walter Dörwald79e913e2007-05-12 11:08:06 +00008356
8357 /* Add quote */
8358 *p++ = (findchar(s, size, '\'') &&
8359 !findchar(s, size, '"')) ? '"' : '\'';
8360 while (size-- > 0) {
8361 Py_UNICODE ch = *s++;
8362
8363 /* Escape quotes and backslashes */
Walter Dörwald1ab83302007-05-18 17:15:44 +00008364 if ((ch == PyUnicode_AS_UNICODE(repr)[0]) || (ch == '\\')) {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008365 *p++ = '\\';
Walter Dörwald1ab83302007-05-18 17:15:44 +00008366 *p++ = ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00008367 continue;
8368 }
8369
Benjamin Peterson29060642009-01-31 22:14:21 +00008370 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +00008371 if (ch == '\t') {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008372 *p++ = '\\';
8373 *p++ = 't';
8374 }
8375 else if (ch == '\n') {
8376 *p++ = '\\';
8377 *p++ = 'n';
8378 }
8379 else if (ch == '\r') {
8380 *p++ = '\\';
8381 *p++ = 'r';
8382 }
8383
8384 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +00008385 else if (ch < ' ' || ch == 0x7F) {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008386 *p++ = '\\';
8387 *p++ = 'x';
8388 *p++ = hexdigits[(ch >> 4) & 0x000F];
8389 *p++ = hexdigits[ch & 0x000F];
8390 }
8391
Georg Brandl559e5d72008-06-11 18:37:52 +00008392 /* Copy ASCII characters as-is */
8393 else if (ch < 0x7F) {
8394 *p++ = ch;
8395 }
8396
Benjamin Peterson29060642009-01-31 22:14:21 +00008397 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +00008398 else {
8399 Py_UCS4 ucs = ch;
8400
8401#ifndef Py_UNICODE_WIDE
8402 Py_UNICODE ch2 = 0;
8403 /* Get code point from surrogate pair */
8404 if (size > 0) {
8405 ch2 = *s;
8406 if (ch >= 0xD800 && ch < 0xDC00 && ch2 >= 0xDC00
Benjamin Peterson29060642009-01-31 22:14:21 +00008407 && ch2 <= 0xDFFF) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008408 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF))
Benjamin Peterson29060642009-01-31 22:14:21 +00008409 + 0x00010000;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008410 s++;
Georg Brandl559e5d72008-06-11 18:37:52 +00008411 size--;
8412 }
8413 }
8414#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00008415 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +00008416 (categories Z* and C* except ASCII space)
8417 */
8418 if (!Py_UNICODE_ISPRINTABLE(ucs)) {
8419 /* Map 8-bit characters to '\xhh' */
8420 if (ucs <= 0xff) {
8421 *p++ = '\\';
8422 *p++ = 'x';
8423 *p++ = hexdigits[(ch >> 4) & 0x000F];
8424 *p++ = hexdigits[ch & 0x000F];
8425 }
8426 /* Map 21-bit characters to '\U00xxxxxx' */
8427 else if (ucs >= 0x10000) {
8428 *p++ = '\\';
8429 *p++ = 'U';
8430 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
8431 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
8432 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
8433 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
8434 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
8435 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
8436 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
8437 *p++ = hexdigits[ucs & 0x0000000F];
8438 }
8439 /* Map 16-bit characters to '\uxxxx' */
8440 else {
8441 *p++ = '\\';
8442 *p++ = 'u';
8443 *p++ = hexdigits[(ucs >> 12) & 0x000F];
8444 *p++ = hexdigits[(ucs >> 8) & 0x000F];
8445 *p++ = hexdigits[(ucs >> 4) & 0x000F];
8446 *p++ = hexdigits[ucs & 0x000F];
8447 }
8448 }
8449 /* Copy characters as-is */
8450 else {
8451 *p++ = ch;
8452#ifndef Py_UNICODE_WIDE
8453 if (ucs >= 0x10000)
8454 *p++ = ch2;
8455#endif
8456 }
8457 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00008458 }
8459 /* Add quote */
Walter Dörwald1ab83302007-05-18 17:15:44 +00008460 *p++ = PyUnicode_AS_UNICODE(repr)[0];
Walter Dörwald79e913e2007-05-12 11:08:06 +00008461
8462 *p = '\0';
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00008463 PyUnicode_Resize(&repr, p - PyUnicode_AS_UNICODE(repr));
Walter Dörwald79e913e2007-05-12 11:08:06 +00008464 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008465}
8466
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008467PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008468 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008469\n\
8470Return the highest index in S where substring sub is found,\n\
Guido van Rossum806c2462007-08-06 23:33:07 +00008471such that sub is contained within s[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008472arguments start and end are interpreted as in slice notation.\n\
8473\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008474Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008475
8476static PyObject *
8477unicode_rfind(PyUnicodeObject *self, PyObject *args)
8478{
Thomas Wouters477c8d52006-05-27 19:21:47 +00008479 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00008480 Py_ssize_t start;
8481 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008482 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008483
Christian Heimes9cd17752007-11-18 19:35:23 +00008484 if (!_ParseTupleFinds(args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008485 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008486
Thomas Wouters477c8d52006-05-27 19:21:47 +00008487 result = stringlib_rfind_slice(
8488 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
8489 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
8490 start, end
8491 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008492
8493 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008494
Christian Heimes217cfd12007-12-02 14:31:20 +00008495 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008496}
8497
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008498PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008499 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008500\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008501Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008502
8503static PyObject *
8504unicode_rindex(PyUnicodeObject *self, PyObject *args)
8505{
Thomas Wouters477c8d52006-05-27 19:21:47 +00008506 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00008507 Py_ssize_t start;
8508 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008509 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008510
Christian Heimes9cd17752007-11-18 19:35:23 +00008511 if (!_ParseTupleFinds(args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008512 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008513
Thomas Wouters477c8d52006-05-27 19:21:47 +00008514 result = stringlib_rfind_slice(
8515 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
8516 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
8517 start, end
8518 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008519
8520 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008521
Guido van Rossumd57fd912000-03-10 22:53:23 +00008522 if (result < 0) {
8523 PyErr_SetString(PyExc_ValueError, "substring not found");
8524 return NULL;
8525 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008526 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008527}
8528
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008529PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008530 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008531\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008532Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008533done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008534
8535static PyObject *
8536unicode_rjust(PyUnicodeObject *self, PyObject *args)
8537{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008538 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008539 Py_UNICODE fillchar = ' ';
8540
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008541 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008542 return NULL;
8543
Tim Peters7a29bd52001-09-12 03:03:31 +00008544 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008545 Py_INCREF(self);
8546 return (PyObject*) self;
8547 }
8548
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008549 return (PyObject*) pad(self, width - self->length, 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008550}
8551
Guido van Rossumd57fd912000-03-10 22:53:23 +00008552PyObject *PyUnicode_Split(PyObject *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00008553 PyObject *sep,
8554 Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008555{
8556 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008557
Guido van Rossumd57fd912000-03-10 22:53:23 +00008558 s = PyUnicode_FromObject(s);
8559 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008560 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00008561 if (sep != NULL) {
8562 sep = PyUnicode_FromObject(sep);
8563 if (sep == NULL) {
8564 Py_DECREF(s);
8565 return NULL;
8566 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008567 }
8568
8569 result = split((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
8570
8571 Py_DECREF(s);
8572 Py_XDECREF(sep);
8573 return result;
8574}
8575
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008576PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008577 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008578\n\
8579Return a list of the words in S, using sep as the\n\
8580delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00008581splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00008582whitespace string is a separator and empty strings are\n\
8583removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008584
8585static PyObject*
8586unicode_split(PyUnicodeObject *self, PyObject *args)
8587{
8588 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008589 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008590
Martin v. Löwis18e16552006-02-15 17:27:45 +00008591 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008592 return NULL;
8593
8594 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008595 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008596 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00008597 return split(self, (PyUnicodeObject *)substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008598 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008599 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008600}
8601
Thomas Wouters477c8d52006-05-27 19:21:47 +00008602PyObject *
8603PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
8604{
8605 PyObject* str_obj;
8606 PyObject* sep_obj;
8607 PyObject* out;
8608
8609 str_obj = PyUnicode_FromObject(str_in);
8610 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008611 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008612 sep_obj = PyUnicode_FromObject(sep_in);
8613 if (!sep_obj) {
8614 Py_DECREF(str_obj);
8615 return NULL;
8616 }
8617
8618 out = stringlib_partition(
8619 str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
8620 sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
8621 );
8622
8623 Py_DECREF(sep_obj);
8624 Py_DECREF(str_obj);
8625
8626 return out;
8627}
8628
8629
8630PyObject *
8631PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
8632{
8633 PyObject* str_obj;
8634 PyObject* sep_obj;
8635 PyObject* out;
8636
8637 str_obj = PyUnicode_FromObject(str_in);
8638 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008639 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008640 sep_obj = PyUnicode_FromObject(sep_in);
8641 if (!sep_obj) {
8642 Py_DECREF(str_obj);
8643 return NULL;
8644 }
8645
8646 out = stringlib_rpartition(
8647 str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
8648 sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
8649 );
8650
8651 Py_DECREF(sep_obj);
8652 Py_DECREF(str_obj);
8653
8654 return out;
8655}
8656
8657PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008658 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008659\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00008660Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008661the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008662found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00008663
8664static PyObject*
8665unicode_partition(PyUnicodeObject *self, PyObject *separator)
8666{
8667 return PyUnicode_Partition((PyObject *)self, separator);
8668}
8669
8670PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +00008671 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008672\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00008673Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008674the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008675separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00008676
8677static PyObject*
8678unicode_rpartition(PyUnicodeObject *self, PyObject *separator)
8679{
8680 return PyUnicode_RPartition((PyObject *)self, separator);
8681}
8682
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008683PyObject *PyUnicode_RSplit(PyObject *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00008684 PyObject *sep,
8685 Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008686{
8687 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008688
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008689 s = PyUnicode_FromObject(s);
8690 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008691 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00008692 if (sep != NULL) {
8693 sep = PyUnicode_FromObject(sep);
8694 if (sep == NULL) {
8695 Py_DECREF(s);
8696 return NULL;
8697 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008698 }
8699
8700 result = rsplit((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
8701
8702 Py_DECREF(s);
8703 Py_XDECREF(sep);
8704 return result;
8705}
8706
8707PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008708 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008709\n\
8710Return a list of the words in S, using sep as the\n\
8711delimiter string, starting at the end of the string and\n\
8712working to the front. If maxsplit is given, at most maxsplit\n\
8713splits are done. If sep is not specified, any whitespace string\n\
8714is a separator.");
8715
8716static PyObject*
8717unicode_rsplit(PyUnicodeObject *self, PyObject *args)
8718{
8719 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008720 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008721
Martin v. Löwis18e16552006-02-15 17:27:45 +00008722 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008723 return NULL;
8724
8725 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008726 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008727 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00008728 return rsplit(self, (PyUnicodeObject *)substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008729 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008730 return PyUnicode_RSplit((PyObject *)self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008731}
8732
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008733PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008734 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008735\n\
8736Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +00008737Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008738is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008739
8740static PyObject*
8741unicode_splitlines(PyUnicodeObject *self, PyObject *args)
8742{
Guido van Rossum86662912000-04-11 15:38:46 +00008743 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008744
Guido van Rossum86662912000-04-11 15:38:46 +00008745 if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008746 return NULL;
8747
Guido van Rossum86662912000-04-11 15:38:46 +00008748 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008749}
8750
8751static
Guido van Rossumf15a29f2007-05-04 00:41:39 +00008752PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008753{
Walter Dörwald346737f2007-05-31 10:44:43 +00008754 if (PyUnicode_CheckExact(self)) {
8755 Py_INCREF(self);
8756 return self;
8757 } else
8758 /* Subtype -- return genuine unicode string with the same value. */
8759 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(self),
8760 PyUnicode_GET_SIZE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +00008761}
8762
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008763PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008764 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008765\n\
8766Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008767and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008768
8769static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008770unicode_swapcase(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008771{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008772 return fixup(self, fixswapcase);
8773}
8774
Georg Brandlceee0772007-11-27 23:48:05 +00008775PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008776 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +00008777\n\
8778Return a translation table usable for str.translate().\n\
8779If there is only one argument, it must be a dictionary mapping Unicode\n\
8780ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008781Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +00008782If there are two arguments, they must be strings of equal length, and\n\
8783in the resulting dictionary, each character in x will be mapped to the\n\
8784character at the same position in y. If there is a third argument, it\n\
8785must be a string, whose characters will be mapped to None in the result.");
8786
8787static PyObject*
8788unicode_maketrans(PyUnicodeObject *null, PyObject *args)
8789{
8790 PyObject *x, *y = NULL, *z = NULL;
8791 PyObject *new = NULL, *key, *value;
8792 Py_ssize_t i = 0;
8793 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008794
Georg Brandlceee0772007-11-27 23:48:05 +00008795 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
8796 return NULL;
8797 new = PyDict_New();
8798 if (!new)
8799 return NULL;
8800 if (y != NULL) {
8801 /* x must be a string too, of equal length */
8802 Py_ssize_t ylen = PyUnicode_GET_SIZE(y);
8803 if (!PyUnicode_Check(x)) {
8804 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
8805 "be a string if there is a second argument");
8806 goto err;
8807 }
8808 if (PyUnicode_GET_SIZE(x) != ylen) {
8809 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
8810 "arguments must have equal length");
8811 goto err;
8812 }
8813 /* create entries for translating chars in x to those in y */
8814 for (i = 0; i < PyUnicode_GET_SIZE(x); i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +00008815 key = PyLong_FromLong(PyUnicode_AS_UNICODE(x)[i]);
8816 value = PyLong_FromLong(PyUnicode_AS_UNICODE(y)[i]);
Georg Brandlceee0772007-11-27 23:48:05 +00008817 if (!key || !value)
8818 goto err;
8819 res = PyDict_SetItem(new, key, value);
8820 Py_DECREF(key);
8821 Py_DECREF(value);
8822 if (res < 0)
8823 goto err;
8824 }
8825 /* create entries for deleting chars in z */
8826 if (z != NULL) {
8827 for (i = 0; i < PyUnicode_GET_SIZE(z); i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +00008828 key = PyLong_FromLong(PyUnicode_AS_UNICODE(z)[i]);
Georg Brandlceee0772007-11-27 23:48:05 +00008829 if (!key)
8830 goto err;
8831 res = PyDict_SetItem(new, key, Py_None);
8832 Py_DECREF(key);
8833 if (res < 0)
8834 goto err;
8835 }
8836 }
8837 } else {
8838 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +00008839 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +00008840 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
8841 "to maketrans it must be a dict");
8842 goto err;
8843 }
8844 /* copy entries into the new dict, converting string keys to int keys */
8845 while (PyDict_Next(x, &i, &key, &value)) {
8846 if (PyUnicode_Check(key)) {
8847 /* convert string keys to integer keys */
8848 PyObject *newkey;
8849 if (PyUnicode_GET_SIZE(key) != 1) {
8850 PyErr_SetString(PyExc_ValueError, "string keys in translate "
8851 "table must be of length 1");
8852 goto err;
8853 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008854 newkey = PyLong_FromLong(PyUnicode_AS_UNICODE(key)[0]);
Georg Brandlceee0772007-11-27 23:48:05 +00008855 if (!newkey)
8856 goto err;
8857 res = PyDict_SetItem(new, newkey, value);
8858 Py_DECREF(newkey);
8859 if (res < 0)
8860 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +00008861 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +00008862 /* just keep integer keys */
8863 if (PyDict_SetItem(new, key, value) < 0)
8864 goto err;
8865 } else {
8866 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
8867 "be strings or integers");
8868 goto err;
8869 }
8870 }
8871 }
8872 return new;
8873 err:
8874 Py_DECREF(new);
8875 return NULL;
8876}
8877
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008878PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008879 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008880\n\
8881Return a copy of the string S, where all characters have been mapped\n\
8882through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008883Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +00008884Unmapped characters are left untouched. Characters mapped to None\n\
8885are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008886
8887static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008888unicode_translate(PyUnicodeObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008889{
Georg Brandlceee0772007-11-27 23:48:05 +00008890 return PyUnicode_TranslateCharmap(self->str, self->length, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008891}
8892
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008893PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008894 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008895\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008896Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008897
8898static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008899unicode_upper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008900{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008901 return fixup(self, fixupper);
8902}
8903
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008904PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008905 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008906\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +00008907Pad a numeric string S with zeros on the left, to fill a field\n\
8908of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008909
8910static PyObject *
8911unicode_zfill(PyUnicodeObject *self, PyObject *args)
8912{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008913 Py_ssize_t fill;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008914 PyUnicodeObject *u;
8915
Martin v. Löwis18e16552006-02-15 17:27:45 +00008916 Py_ssize_t width;
8917 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008918 return NULL;
8919
8920 if (self->length >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +00008921 if (PyUnicode_CheckExact(self)) {
8922 Py_INCREF(self);
8923 return (PyObject*) self;
8924 }
8925 else
8926 return PyUnicode_FromUnicode(
8927 PyUnicode_AS_UNICODE(self),
8928 PyUnicode_GET_SIZE(self)
Benjamin Peterson29060642009-01-31 22:14:21 +00008929 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008930 }
8931
8932 fill = width - self->length;
8933
8934 u = pad(self, fill, 0, '0');
8935
Walter Dörwald068325e2002-04-15 13:36:47 +00008936 if (u == NULL)
8937 return NULL;
8938
Guido van Rossumd57fd912000-03-10 22:53:23 +00008939 if (u->str[fill] == '+' || u->str[fill] == '-') {
8940 /* move sign to beginning of string */
8941 u->str[0] = u->str[fill];
8942 u->str[fill] = '0';
8943 }
8944
8945 return (PyObject*) u;
8946}
Guido van Rossumd57fd912000-03-10 22:53:23 +00008947
8948#if 0
8949static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008950unicode_freelistsize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008951{
Christian Heimes2202f872008-02-06 14:31:34 +00008952 return PyLong_FromLong(numfree);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008953}
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008954
8955static PyObject *
8956unicode__decimal2ascii(PyObject *self)
8957{
8958 return PyUnicode_TransformDecimalToASCII(PyUnicode_AS_UNICODE(self),
8959 PyUnicode_GET_SIZE(self));
8960}
Guido van Rossumd57fd912000-03-10 22:53:23 +00008961#endif
8962
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008963PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008964 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008965\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00008966Return True if S starts with the specified prefix, False otherwise.\n\
8967With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008968With optional end, stop comparing S at that position.\n\
8969prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008970
8971static PyObject *
8972unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00008973 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008974{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008975 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008976 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008977 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008978 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008979 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008980
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008981 if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
Benjamin Peterson29060642009-01-31 22:14:21 +00008982 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
8983 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008984 if (PyTuple_Check(subobj)) {
8985 Py_ssize_t i;
8986 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
8987 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +00008988 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008989 if (substring == NULL)
8990 return NULL;
8991 result = tailmatch(self, substring, start, end, -1);
8992 Py_DECREF(substring);
8993 if (result) {
8994 Py_RETURN_TRUE;
8995 }
8996 }
8997 /* nothing matched */
8998 Py_RETURN_FALSE;
8999 }
9000 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009001 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009002 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009003 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009004 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009005 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009006}
9007
9008
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009009PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009010 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009011\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00009012Return True if S ends with the specified suffix, False otherwise.\n\
9013With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009014With optional end, stop comparing S at that position.\n\
9015suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009016
9017static PyObject *
9018unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00009019 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009020{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009021 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009022 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009023 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009024 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009025 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009026
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009027 if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
Benjamin Peterson29060642009-01-31 22:14:21 +00009028 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
9029 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)
Benjamin Peterson29060642009-01-31 22:14:21 +00009036 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009037 result = tailmatch(self, substring, start, end, +1);
9038 Py_DECREF(substring);
9039 if (result) {
9040 Py_RETURN_TRUE;
9041 }
9042 }
9043 Py_RETURN_FALSE;
9044 }
9045 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009046 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009047 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009048
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009049 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009050 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009051 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009052}
9053
Eric Smith8c663262007-08-25 02:26:07 +00009054#include "stringlib/string_format.h"
9055
9056PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009057 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +00009058\n\
Eric Smith51d2fd92010-11-06 19:27:37 +00009059Return a formatted version of S, using substitutions from args and kwargs.\n\
9060The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +00009061
Eric Smith27bbca62010-11-04 17:06:58 +00009062PyDoc_STRVAR(format_map__doc__,
9063 "S.format_map(mapping) -> str\n\
9064\n\
Eric Smith51d2fd92010-11-06 19:27:37 +00009065Return a formatted version of S, using substitutions from mapping.\n\
9066The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +00009067
Eric Smith4a7d76d2008-05-30 18:10:19 +00009068static PyObject *
9069unicode__format__(PyObject* self, PyObject* args)
9070{
9071 PyObject *format_spec;
9072
9073 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
9074 return NULL;
9075
9076 return _PyUnicode_FormatAdvanced(self,
9077 PyUnicode_AS_UNICODE(format_spec),
9078 PyUnicode_GET_SIZE(format_spec));
9079}
9080
Eric Smith8c663262007-08-25 02:26:07 +00009081PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009082 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +00009083\n\
Eric Smith51d2fd92010-11-06 19:27:37 +00009084Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +00009085
9086static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009087unicode__sizeof__(PyUnicodeObject *v)
9088{
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00009089 return PyLong_FromSsize_t(sizeof(PyUnicodeObject) +
9090 sizeof(Py_UNICODE) * (v->length + 1));
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009091}
9092
9093PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009094 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009095
9096static PyObject *
Guido van Rossum5d9113d2003-01-29 17:58:45 +00009097unicode_getnewargs(PyUnicodeObject *v)
9098{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009099 return Py_BuildValue("(u#)", v->str, v->length);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00009100}
9101
Guido van Rossumd57fd912000-03-10 22:53:23 +00009102static PyMethodDef unicode_methods[] = {
9103
9104 /* Order is according to common usage: often used methods should
9105 appear first, since lookup is done sequentially. */
9106
Benjamin Peterson28a4dce2010-12-12 01:33:04 +00009107 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009108 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
9109 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009110 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009111 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
9112 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
9113 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
9114 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
9115 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
9116 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
9117 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00009118 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009119 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
9120 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
9121 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00009122 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009123 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
9124 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
9125 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00009126 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00009127 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009128 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00009129 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009130 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
9131 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
9132 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
9133 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
9134 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
9135 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
9136 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
9137 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
9138 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
9139 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
9140 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
9141 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
9142 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
9143 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +00009144 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +00009145 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009146 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +00009147 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +00009148 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +00009149 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +00009150 {"maketrans", (PyCFunction) unicode_maketrans,
9151 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009152 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +00009153#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009154 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +00009155#endif
9156
9157#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009158 /* These methods are just used for debugging the implementation. */
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009159 {"freelistsize", (PyCFunction) unicode_freelistsize, METH_NOARGS},
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009160 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +00009161#endif
9162
Benjamin Peterson14339b62009-01-31 16:36:08 +00009163 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +00009164 {NULL, NULL}
9165};
9166
Neil Schemenauerce30bc92002-11-18 16:10:18 +00009167static PyObject *
9168unicode_mod(PyObject *v, PyObject *w)
9169{
Benjamin Peterson29060642009-01-31 22:14:21 +00009170 if (!PyUnicode_Check(v)) {
9171 Py_INCREF(Py_NotImplemented);
9172 return Py_NotImplemented;
9173 }
9174 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +00009175}
9176
9177static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009178 0, /*nb_add*/
9179 0, /*nb_subtract*/
9180 0, /*nb_multiply*/
9181 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +00009182};
9183
Guido van Rossumd57fd912000-03-10 22:53:23 +00009184static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009185 (lenfunc) unicode_length, /* sq_length */
9186 PyUnicode_Concat, /* sq_concat */
9187 (ssizeargfunc) unicode_repeat, /* sq_repeat */
9188 (ssizeargfunc) unicode_getitem, /* sq_item */
9189 0, /* sq_slice */
9190 0, /* sq_ass_item */
9191 0, /* sq_ass_slice */
9192 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009193};
9194
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009195static PyObject*
9196unicode_subscript(PyUnicodeObject* self, PyObject* item)
9197{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009198 if (PyIndex_Check(item)) {
9199 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009200 if (i == -1 && PyErr_Occurred())
9201 return NULL;
9202 if (i < 0)
Martin v. Löwisdea59e52006-01-05 10:00:36 +00009203 i += PyUnicode_GET_SIZE(self);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009204 return unicode_getitem(self, i);
9205 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00009206 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009207 Py_UNICODE* source_buf;
9208 Py_UNICODE* result_buf;
9209 PyObject* result;
9210
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00009211 if (PySlice_GetIndicesEx(item, PyUnicode_GET_SIZE(self),
Benjamin Peterson29060642009-01-31 22:14:21 +00009212 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009213 return NULL;
9214 }
9215
9216 if (slicelength <= 0) {
9217 return PyUnicode_FromUnicode(NULL, 0);
Thomas Woutersed03b412007-08-28 21:37:11 +00009218 } else if (start == 0 && step == 1 && slicelength == self->length &&
9219 PyUnicode_CheckExact(self)) {
9220 Py_INCREF(self);
9221 return (PyObject *)self;
9222 } else if (step == 1) {
9223 return PyUnicode_FromUnicode(self->str + start, slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009224 } else {
9225 source_buf = PyUnicode_AS_UNICODE((PyObject*)self);
Christian Heimesb186d002008-03-18 15:15:01 +00009226 result_buf = (Py_UNICODE *)PyObject_MALLOC(slicelength*
9227 sizeof(Py_UNICODE));
Benjamin Peterson14339b62009-01-31 16:36:08 +00009228
Benjamin Peterson29060642009-01-31 22:14:21 +00009229 if (result_buf == NULL)
9230 return PyErr_NoMemory();
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009231
9232 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
9233 result_buf[i] = source_buf[cur];
9234 }
Tim Petersced69f82003-09-16 20:30:58 +00009235
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009236 result = PyUnicode_FromUnicode(result_buf, slicelength);
Christian Heimesb186d002008-03-18 15:15:01 +00009237 PyObject_FREE(result_buf);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009238 return result;
9239 }
9240 } else {
9241 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
9242 return NULL;
9243 }
9244}
9245
9246static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009247 (lenfunc)unicode_length, /* mp_length */
9248 (binaryfunc)unicode_subscript, /* mp_subscript */
9249 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009250};
9251
Guido van Rossumd57fd912000-03-10 22:53:23 +00009252
Guido van Rossumd57fd912000-03-10 22:53:23 +00009253/* Helpers for PyUnicode_Format() */
9254
9255static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00009256getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009257{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009258 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009259 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009260 (*p_argidx)++;
9261 if (arglen < 0)
9262 return args;
9263 else
9264 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009265 }
9266 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009267 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009268 return NULL;
9269}
9270
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009271/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009272
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009273static PyObject *
9274formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009275{
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009276 char *p;
9277 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009278 double x;
Tim Petersced69f82003-09-16 20:30:58 +00009279
Guido van Rossumd57fd912000-03-10 22:53:23 +00009280 x = PyFloat_AsDouble(v);
9281 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009282 return NULL;
9283
Guido van Rossumd57fd912000-03-10 22:53:23 +00009284 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009285 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +00009286
Eric Smith0923d1d2009-04-16 20:16:10 +00009287 p = PyOS_double_to_string(x, type, prec,
9288 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009289 if (p == NULL)
9290 return NULL;
9291 result = PyUnicode_FromStringAndSize(p, strlen(p));
Eric Smith0923d1d2009-04-16 20:16:10 +00009292 PyMem_Free(p);
9293 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009294}
9295
Tim Peters38fd5b62000-09-21 05:43:11 +00009296static PyObject*
9297formatlong(PyObject *val, int flags, int prec, int type)
9298{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009299 char *buf;
9300 int len;
9301 PyObject *str; /* temporary string object. */
9302 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +00009303
Benjamin Peterson14339b62009-01-31 16:36:08 +00009304 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
9305 if (!str)
9306 return NULL;
9307 result = PyUnicode_FromStringAndSize(buf, len);
9308 Py_DECREF(str);
9309 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +00009310}
9311
Guido van Rossumd57fd912000-03-10 22:53:23 +00009312static int
9313formatchar(Py_UNICODE *buf,
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009314 size_t buflen,
9315 PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009316{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00009317 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009318 if (PyUnicode_Check(v)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009319 if (PyUnicode_GET_SIZE(v) == 1) {
9320 buf[0] = PyUnicode_AS_UNICODE(v)[0];
9321 buf[1] = '\0';
9322 return 1;
9323 }
9324#ifndef Py_UNICODE_WIDE
9325 if (PyUnicode_GET_SIZE(v) == 2) {
9326 /* Decode a valid surrogate pair */
9327 int c0 = PyUnicode_AS_UNICODE(v)[0];
9328 int c1 = PyUnicode_AS_UNICODE(v)[1];
9329 if (0xD800 <= c0 && c0 <= 0xDBFF &&
9330 0xDC00 <= c1 && c1 <= 0xDFFF) {
9331 buf[0] = c0;
9332 buf[1] = c1;
9333 buf[2] = '\0';
9334 return 2;
9335 }
9336 }
9337#endif
9338 goto onError;
9339 }
9340 else {
9341 /* Integer input truncated to a character */
9342 long x;
9343 x = PyLong_AsLong(v);
9344 if (x == -1 && PyErr_Occurred())
9345 goto onError;
9346
9347 if (x < 0 || x > 0x10ffff) {
9348 PyErr_SetString(PyExc_OverflowError,
9349 "%c arg not in range(0x110000)");
9350 return -1;
9351 }
9352
9353#ifndef Py_UNICODE_WIDE
9354 if (x > 0xffff) {
9355 x -= 0x10000;
9356 buf[0] = (Py_UNICODE)(0xD800 | (x >> 10));
9357 buf[1] = (Py_UNICODE)(0xDC00 | (x & 0x3FF));
9358 return 2;
9359 }
9360#endif
9361 buf[0] = (Py_UNICODE) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009362 buf[1] = '\0';
9363 return 1;
9364 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00009365
Benjamin Peterson29060642009-01-31 22:14:21 +00009366 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009367 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009368 "%c requires int or char");
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009369 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009370}
9371
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009372/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009373 FORMATBUFLEN is the length of the buffer in which chars are formatted.
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009374*/
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009375#define FORMATBUFLEN (size_t)10
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009376
Guido van Rossumd57fd912000-03-10 22:53:23 +00009377PyObject *PyUnicode_Format(PyObject *format,
Benjamin Peterson29060642009-01-31 22:14:21 +00009378 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009379{
9380 Py_UNICODE *fmt, *res;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009381 Py_ssize_t fmtcnt, rescnt, reslen, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009382 int args_owned = 0;
9383 PyUnicodeObject *result = NULL;
9384 PyObject *dict = NULL;
9385 PyObject *uformat;
Tim Petersced69f82003-09-16 20:30:58 +00009386
Guido van Rossumd57fd912000-03-10 22:53:23 +00009387 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009388 PyErr_BadInternalCall();
9389 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009390 }
9391 uformat = PyUnicode_FromObject(format);
Fred Drakee4315f52000-05-09 19:53:39 +00009392 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009393 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009394 fmt = PyUnicode_AS_UNICODE(uformat);
9395 fmtcnt = PyUnicode_GET_SIZE(uformat);
9396
9397 reslen = rescnt = fmtcnt + 100;
9398 result = _PyUnicode_New(reslen);
9399 if (result == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009400 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009401 res = PyUnicode_AS_UNICODE(result);
9402
9403 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009404 arglen = PyTuple_Size(args);
9405 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009406 }
9407 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009408 arglen = -1;
9409 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009410 }
Christian Heimes90aa7642007-12-19 02:45:37 +00009411 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +00009412 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +00009413 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009414
9415 while (--fmtcnt >= 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009416 if (*fmt != '%') {
9417 if (--rescnt < 0) {
9418 rescnt = fmtcnt + 100;
9419 reslen += rescnt;
9420 if (_PyUnicode_Resize(&result, reslen) < 0)
9421 goto onError;
9422 res = PyUnicode_AS_UNICODE(result) + reslen - rescnt;
9423 --rescnt;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009424 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009425 *res++ = *fmt++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009426 }
9427 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009428 /* Got a format specifier */
9429 int flags = 0;
9430 Py_ssize_t width = -1;
9431 int prec = -1;
9432 Py_UNICODE c = '\0';
9433 Py_UNICODE fill;
9434 int isnumok;
9435 PyObject *v = NULL;
9436 PyObject *temp = NULL;
9437 Py_UNICODE *pbuf;
9438 Py_UNICODE sign;
9439 Py_ssize_t len;
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009440 Py_UNICODE formatbuf[FORMATBUFLEN]; /* For formatchar() */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009441
Benjamin Peterson29060642009-01-31 22:14:21 +00009442 fmt++;
9443 if (*fmt == '(') {
9444 Py_UNICODE *keystart;
9445 Py_ssize_t keylen;
9446 PyObject *key;
9447 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +00009448
Benjamin Peterson29060642009-01-31 22:14:21 +00009449 if (dict == NULL) {
9450 PyErr_SetString(PyExc_TypeError,
9451 "format requires a mapping");
9452 goto onError;
9453 }
9454 ++fmt;
9455 --fmtcnt;
9456 keystart = fmt;
9457 /* Skip over balanced parentheses */
9458 while (pcount > 0 && --fmtcnt >= 0) {
9459 if (*fmt == ')')
9460 --pcount;
9461 else if (*fmt == '(')
9462 ++pcount;
9463 fmt++;
9464 }
9465 keylen = fmt - keystart - 1;
9466 if (fmtcnt < 0 || pcount > 0) {
9467 PyErr_SetString(PyExc_ValueError,
9468 "incomplete format key");
9469 goto onError;
9470 }
9471#if 0
9472 /* keys are converted to strings using UTF-8 and
9473 then looked up since Python uses strings to hold
9474 variables names etc. in its namespaces and we
9475 wouldn't want to break common idioms. */
9476 key = PyUnicode_EncodeUTF8(keystart,
9477 keylen,
9478 NULL);
9479#else
9480 key = PyUnicode_FromUnicode(keystart, keylen);
9481#endif
9482 if (key == NULL)
9483 goto onError;
9484 if (args_owned) {
9485 Py_DECREF(args);
9486 args_owned = 0;
9487 }
9488 args = PyObject_GetItem(dict, key);
9489 Py_DECREF(key);
9490 if (args == NULL) {
9491 goto onError;
9492 }
9493 args_owned = 1;
9494 arglen = -1;
9495 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009496 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009497 while (--fmtcnt >= 0) {
9498 switch (c = *fmt++) {
9499 case '-': flags |= F_LJUST; continue;
9500 case '+': flags |= F_SIGN; continue;
9501 case ' ': flags |= F_BLANK; continue;
9502 case '#': flags |= F_ALT; continue;
9503 case '0': flags |= F_ZERO; continue;
9504 }
9505 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009506 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009507 if (c == '*') {
9508 v = getnextarg(args, arglen, &argidx);
9509 if (v == NULL)
9510 goto onError;
9511 if (!PyLong_Check(v)) {
9512 PyErr_SetString(PyExc_TypeError,
9513 "* wants int");
9514 goto onError;
9515 }
9516 width = PyLong_AsLong(v);
9517 if (width == -1 && PyErr_Occurred())
9518 goto onError;
9519 if (width < 0) {
9520 flags |= F_LJUST;
9521 width = -width;
9522 }
9523 if (--fmtcnt >= 0)
9524 c = *fmt++;
9525 }
9526 else if (c >= '0' && c <= '9') {
9527 width = c - '0';
9528 while (--fmtcnt >= 0) {
9529 c = *fmt++;
9530 if (c < '0' || c > '9')
9531 break;
9532 if ((width*10) / 10 != width) {
9533 PyErr_SetString(PyExc_ValueError,
9534 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009535 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00009536 }
9537 width = width*10 + (c - '0');
9538 }
9539 }
9540 if (c == '.') {
9541 prec = 0;
9542 if (--fmtcnt >= 0)
9543 c = *fmt++;
9544 if (c == '*') {
9545 v = getnextarg(args, arglen, &argidx);
9546 if (v == NULL)
9547 goto onError;
9548 if (!PyLong_Check(v)) {
9549 PyErr_SetString(PyExc_TypeError,
9550 "* wants int");
9551 goto onError;
9552 }
9553 prec = PyLong_AsLong(v);
9554 if (prec == -1 && PyErr_Occurred())
9555 goto onError;
9556 if (prec < 0)
9557 prec = 0;
9558 if (--fmtcnt >= 0)
9559 c = *fmt++;
9560 }
9561 else if (c >= '0' && c <= '9') {
9562 prec = c - '0';
9563 while (--fmtcnt >= 0) {
Stefan Krah99212f62010-07-19 17:58:26 +00009564 c = *fmt++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009565 if (c < '0' || c > '9')
9566 break;
9567 if ((prec*10) / 10 != prec) {
9568 PyErr_SetString(PyExc_ValueError,
9569 "prec too big");
9570 goto onError;
9571 }
9572 prec = prec*10 + (c - '0');
9573 }
9574 }
9575 } /* prec */
9576 if (fmtcnt >= 0) {
9577 if (c == 'h' || c == 'l' || c == 'L') {
9578 if (--fmtcnt >= 0)
9579 c = *fmt++;
9580 }
9581 }
9582 if (fmtcnt < 0) {
9583 PyErr_SetString(PyExc_ValueError,
9584 "incomplete format");
9585 goto onError;
9586 }
9587 if (c != '%') {
9588 v = getnextarg(args, arglen, &argidx);
9589 if (v == NULL)
9590 goto onError;
9591 }
9592 sign = 0;
9593 fill = ' ';
9594 switch (c) {
9595
9596 case '%':
9597 pbuf = formatbuf;
9598 /* presume that buffer length is at least 1 */
9599 pbuf[0] = '%';
9600 len = 1;
9601 break;
9602
9603 case 's':
9604 case 'r':
9605 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +00009606 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +00009607 temp = v;
9608 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009609 }
9610 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009611 if (c == 's')
9612 temp = PyObject_Str(v);
9613 else if (c == 'r')
9614 temp = PyObject_Repr(v);
9615 else
9616 temp = PyObject_ASCII(v);
9617 if (temp == NULL)
9618 goto onError;
9619 if (PyUnicode_Check(temp))
9620 /* nothing to do */;
9621 else {
9622 Py_DECREF(temp);
9623 PyErr_SetString(PyExc_TypeError,
9624 "%s argument has non-string str()");
9625 goto onError;
9626 }
9627 }
9628 pbuf = PyUnicode_AS_UNICODE(temp);
9629 len = PyUnicode_GET_SIZE(temp);
9630 if (prec >= 0 && len > prec)
9631 len = prec;
9632 break;
9633
9634 case 'i':
9635 case 'd':
9636 case 'u':
9637 case 'o':
9638 case 'x':
9639 case 'X':
9640 if (c == 'i')
9641 c = 'd';
9642 isnumok = 0;
9643 if (PyNumber_Check(v)) {
9644 PyObject *iobj=NULL;
9645
9646 if (PyLong_Check(v)) {
9647 iobj = v;
9648 Py_INCREF(iobj);
9649 }
9650 else {
9651 iobj = PyNumber_Long(v);
9652 }
9653 if (iobj!=NULL) {
9654 if (PyLong_Check(iobj)) {
9655 isnumok = 1;
9656 temp = formatlong(iobj, flags, prec, c);
9657 Py_DECREF(iobj);
9658 if (!temp)
9659 goto onError;
9660 pbuf = PyUnicode_AS_UNICODE(temp);
9661 len = PyUnicode_GET_SIZE(temp);
9662 sign = 1;
9663 }
9664 else {
9665 Py_DECREF(iobj);
9666 }
9667 }
9668 }
9669 if (!isnumok) {
9670 PyErr_Format(PyExc_TypeError,
9671 "%%%c format: a number is required, "
9672 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
9673 goto onError;
9674 }
9675 if (flags & F_ZERO)
9676 fill = '0';
9677 break;
9678
9679 case 'e':
9680 case 'E':
9681 case 'f':
9682 case 'F':
9683 case 'g':
9684 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009685 temp = formatfloat(v, flags, prec, c);
9686 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +00009687 goto onError;
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009688 pbuf = PyUnicode_AS_UNICODE(temp);
9689 len = PyUnicode_GET_SIZE(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +00009690 sign = 1;
9691 if (flags & F_ZERO)
9692 fill = '0';
9693 break;
9694
9695 case 'c':
9696 pbuf = formatbuf;
9697 len = formatchar(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), v);
9698 if (len < 0)
9699 goto onError;
9700 break;
9701
9702 default:
9703 PyErr_Format(PyExc_ValueError,
9704 "unsupported format character '%c' (0x%x) "
9705 "at index %zd",
9706 (31<=c && c<=126) ? (char)c : '?',
9707 (int)c,
9708 (Py_ssize_t)(fmt - 1 -
9709 PyUnicode_AS_UNICODE(uformat)));
9710 goto onError;
9711 }
9712 if (sign) {
9713 if (*pbuf == '-' || *pbuf == '+') {
9714 sign = *pbuf++;
9715 len--;
9716 }
9717 else if (flags & F_SIGN)
9718 sign = '+';
9719 else if (flags & F_BLANK)
9720 sign = ' ';
9721 else
9722 sign = 0;
9723 }
9724 if (width < len)
9725 width = len;
9726 if (rescnt - (sign != 0) < width) {
9727 reslen -= rescnt;
9728 rescnt = width + fmtcnt + 100;
9729 reslen += rescnt;
9730 if (reslen < 0) {
9731 Py_XDECREF(temp);
9732 PyErr_NoMemory();
9733 goto onError;
9734 }
9735 if (_PyUnicode_Resize(&result, reslen) < 0) {
9736 Py_XDECREF(temp);
9737 goto onError;
9738 }
9739 res = PyUnicode_AS_UNICODE(result)
9740 + reslen - rescnt;
9741 }
9742 if (sign) {
9743 if (fill != ' ')
9744 *res++ = sign;
9745 rescnt--;
9746 if (width > len)
9747 width--;
9748 }
9749 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
9750 assert(pbuf[0] == '0');
9751 assert(pbuf[1] == c);
9752 if (fill != ' ') {
9753 *res++ = *pbuf++;
9754 *res++ = *pbuf++;
9755 }
9756 rescnt -= 2;
9757 width -= 2;
9758 if (width < 0)
9759 width = 0;
9760 len -= 2;
9761 }
9762 if (width > len && !(flags & F_LJUST)) {
9763 do {
9764 --rescnt;
9765 *res++ = fill;
9766 } while (--width > len);
9767 }
9768 if (fill == ' ') {
9769 if (sign)
9770 *res++ = sign;
9771 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
9772 assert(pbuf[0] == '0');
9773 assert(pbuf[1] == c);
9774 *res++ = *pbuf++;
9775 *res++ = *pbuf++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009776 }
9777 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009778 Py_UNICODE_COPY(res, pbuf, len);
9779 res += len;
9780 rescnt -= len;
9781 while (--width >= len) {
9782 --rescnt;
9783 *res++ = ' ';
9784 }
9785 if (dict && (argidx < arglen) && c != '%') {
9786 PyErr_SetString(PyExc_TypeError,
9787 "not all arguments converted during string formatting");
Thomas Woutersa96affe2006-03-12 00:29:36 +00009788 Py_XDECREF(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +00009789 goto onError;
9790 }
9791 Py_XDECREF(temp);
9792 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009793 } /* until end */
9794 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009795 PyErr_SetString(PyExc_TypeError,
9796 "not all arguments converted during string formatting");
9797 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009798 }
9799
Thomas Woutersa96affe2006-03-12 00:29:36 +00009800 if (_PyUnicode_Resize(&result, reslen - rescnt) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009801 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009802 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009803 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009804 }
9805 Py_DECREF(uformat);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009806 return (PyObject *)result;
9807
Benjamin Peterson29060642009-01-31 22:14:21 +00009808 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009809 Py_XDECREF(result);
9810 Py_DECREF(uformat);
9811 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009812 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009813 }
9814 return NULL;
9815}
9816
Jeremy Hylton938ace62002-07-17 16:30:39 +00009817static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +00009818unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
9819
Tim Peters6d6c1a32001-08-02 04:15:00 +00009820static PyObject *
9821unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9822{
Benjamin Peterson29060642009-01-31 22:14:21 +00009823 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009824 static char *kwlist[] = {"object", "encoding", "errors", 0};
9825 char *encoding = NULL;
9826 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00009827
Benjamin Peterson14339b62009-01-31 16:36:08 +00009828 if (type != &PyUnicode_Type)
9829 return unicode_subtype_new(type, args, kwds);
9830 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +00009831 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009832 return NULL;
9833 if (x == NULL)
9834 return (PyObject *)_PyUnicode_New(0);
9835 if (encoding == NULL && errors == NULL)
9836 return PyObject_Str(x);
9837 else
Benjamin Peterson29060642009-01-31 22:14:21 +00009838 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +00009839}
9840
Guido van Rossume023fe02001-08-30 03:12:59 +00009841static PyObject *
9842unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9843{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009844 PyUnicodeObject *tmp, *pnew;
9845 Py_ssize_t n;
Guido van Rossume023fe02001-08-30 03:12:59 +00009846
Benjamin Peterson14339b62009-01-31 16:36:08 +00009847 assert(PyType_IsSubtype(type, &PyUnicode_Type));
9848 tmp = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
9849 if (tmp == NULL)
9850 return NULL;
9851 assert(PyUnicode_Check(tmp));
9852 pnew = (PyUnicodeObject *) type->tp_alloc(type, n = tmp->length);
9853 if (pnew == NULL) {
9854 Py_DECREF(tmp);
9855 return NULL;
9856 }
9857 pnew->str = (Py_UNICODE*) PyObject_MALLOC(sizeof(Py_UNICODE) * (n+1));
9858 if (pnew->str == NULL) {
9859 _Py_ForgetReference((PyObject *)pnew);
9860 PyObject_Del(pnew);
9861 Py_DECREF(tmp);
9862 return PyErr_NoMemory();
9863 }
9864 Py_UNICODE_COPY(pnew->str, tmp->str, n+1);
9865 pnew->length = n;
9866 pnew->hash = tmp->hash;
9867 Py_DECREF(tmp);
9868 return (PyObject *)pnew;
Guido van Rossume023fe02001-08-30 03:12:59 +00009869}
9870
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009871PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +00009872 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00009873\n\
Collin Winterd474ce82007-08-07 19:42:11 +00009874Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +00009875encoding defaults to the current default string encoding.\n\
9876errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00009877
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009878static PyObject *unicode_iter(PyObject *seq);
9879
Guido van Rossumd57fd912000-03-10 22:53:23 +00009880PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00009881 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +00009882 "str", /* tp_name */
9883 sizeof(PyUnicodeObject), /* tp_size */
9884 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009885 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009886 (destructor)unicode_dealloc, /* tp_dealloc */
9887 0, /* tp_print */
9888 0, /* tp_getattr */
9889 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00009890 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009891 unicode_repr, /* tp_repr */
9892 &unicode_as_number, /* tp_as_number */
9893 &unicode_as_sequence, /* tp_as_sequence */
9894 &unicode_as_mapping, /* tp_as_mapping */
9895 (hashfunc) unicode_hash, /* tp_hash*/
9896 0, /* tp_call*/
9897 (reprfunc) unicode_str, /* tp_str */
9898 PyObject_GenericGetAttr, /* tp_getattro */
9899 0, /* tp_setattro */
9900 0, /* tp_as_buffer */
9901 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +00009902 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009903 unicode_doc, /* tp_doc */
9904 0, /* tp_traverse */
9905 0, /* tp_clear */
9906 PyUnicode_RichCompare, /* tp_richcompare */
9907 0, /* tp_weaklistoffset */
9908 unicode_iter, /* tp_iter */
9909 0, /* tp_iternext */
9910 unicode_methods, /* tp_methods */
9911 0, /* tp_members */
9912 0, /* tp_getset */
9913 &PyBaseObject_Type, /* tp_base */
9914 0, /* tp_dict */
9915 0, /* tp_descr_get */
9916 0, /* tp_descr_set */
9917 0, /* tp_dictoffset */
9918 0, /* tp_init */
9919 0, /* tp_alloc */
9920 unicode_new, /* tp_new */
9921 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009922};
9923
9924/* Initialize the Unicode implementation */
9925
Thomas Wouters78890102000-07-22 19:25:51 +00009926void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009927{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009928 int i;
9929
Thomas Wouters477c8d52006-05-27 19:21:47 +00009930 /* XXX - move this array to unicodectype.c ? */
9931 Py_UNICODE linebreak[] = {
9932 0x000A, /* LINE FEED */
9933 0x000D, /* CARRIAGE RETURN */
9934 0x001C, /* FILE SEPARATOR */
9935 0x001D, /* GROUP SEPARATOR */
9936 0x001E, /* RECORD SEPARATOR */
9937 0x0085, /* NEXT LINE */
9938 0x2028, /* LINE SEPARATOR */
9939 0x2029, /* PARAGRAPH SEPARATOR */
9940 };
9941
Fred Drakee4315f52000-05-09 19:53:39 +00009942 /* Init the implementation */
Christian Heimes2202f872008-02-06 14:31:34 +00009943 free_list = NULL;
9944 numfree = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009945 unicode_empty = _PyUnicode_New(0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009946 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00009947 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009948
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009949 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00009950 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +00009951 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009952 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +00009953
9954 /* initialize the linebreak bloom filter */
9955 bloom_linebreak = make_bloom_mask(
9956 linebreak, sizeof(linebreak) / sizeof(linebreak[0])
9957 );
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009958
9959 PyType_Ready(&EncodingMapType);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009960}
9961
9962/* Finalize the Unicode implementation */
9963
Christian Heimesa156e092008-02-16 07:38:31 +00009964int
9965PyUnicode_ClearFreeList(void)
9966{
9967 int freelist_size = numfree;
9968 PyUnicodeObject *u;
9969
9970 for (u = free_list; u != NULL;) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009971 PyUnicodeObject *v = u;
9972 u = *(PyUnicodeObject **)u;
9973 if (v->str)
9974 PyObject_DEL(v->str);
9975 Py_XDECREF(v->defenc);
9976 PyObject_Del(v);
9977 numfree--;
Christian Heimesa156e092008-02-16 07:38:31 +00009978 }
9979 free_list = NULL;
9980 assert(numfree == 0);
9981 return freelist_size;
9982}
9983
Guido van Rossumd57fd912000-03-10 22:53:23 +00009984void
Thomas Wouters78890102000-07-22 19:25:51 +00009985_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009986{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009987 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009988
Guido van Rossum4ae8ef82000-10-03 18:09:04 +00009989 Py_XDECREF(unicode_empty);
9990 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +00009991
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009992 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009993 if (unicode_latin1[i]) {
9994 Py_DECREF(unicode_latin1[i]);
9995 unicode_latin1[i] = NULL;
9996 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009997 }
Christian Heimesa156e092008-02-16 07:38:31 +00009998 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +00009999}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000010000
Walter Dörwald16807132007-05-25 13:52:07 +000010001void
10002PyUnicode_InternInPlace(PyObject **p)
10003{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010004 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
10005 PyObject *t;
10006 if (s == NULL || !PyUnicode_Check(s))
10007 Py_FatalError(
10008 "PyUnicode_InternInPlace: unicode strings only please!");
10009 /* If it's a subclass, we don't really know what putting
10010 it in the interned dict might do. */
10011 if (!PyUnicode_CheckExact(s))
10012 return;
10013 if (PyUnicode_CHECK_INTERNED(s))
10014 return;
10015 if (interned == NULL) {
10016 interned = PyDict_New();
10017 if (interned == NULL) {
10018 PyErr_Clear(); /* Don't leave an exception */
10019 return;
10020 }
10021 }
10022 /* It might be that the GetItem call fails even
10023 though the key is present in the dictionary,
10024 namely when this happens during a stack overflow. */
10025 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000010026 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010027 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000010028
Benjamin Peterson29060642009-01-31 22:14:21 +000010029 if (t) {
10030 Py_INCREF(t);
10031 Py_DECREF(*p);
10032 *p = t;
10033 return;
10034 }
Walter Dörwald16807132007-05-25 13:52:07 +000010035
Benjamin Peterson14339b62009-01-31 16:36:08 +000010036 PyThreadState_GET()->recursion_critical = 1;
10037 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
10038 PyErr_Clear();
10039 PyThreadState_GET()->recursion_critical = 0;
10040 return;
10041 }
10042 PyThreadState_GET()->recursion_critical = 0;
10043 /* The two references in interned are not counted by refcnt.
10044 The deallocator will take care of this */
10045 Py_REFCNT(s) -= 2;
10046 PyUnicode_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000010047}
10048
10049void
10050PyUnicode_InternImmortal(PyObject **p)
10051{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010052 PyUnicode_InternInPlace(p);
10053 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
10054 PyUnicode_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
10055 Py_INCREF(*p);
10056 }
Walter Dörwald16807132007-05-25 13:52:07 +000010057}
10058
10059PyObject *
10060PyUnicode_InternFromString(const char *cp)
10061{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010062 PyObject *s = PyUnicode_FromString(cp);
10063 if (s == NULL)
10064 return NULL;
10065 PyUnicode_InternInPlace(&s);
10066 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000010067}
10068
10069void _Py_ReleaseInternedUnicodeStrings(void)
10070{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010071 PyObject *keys;
10072 PyUnicodeObject *s;
10073 Py_ssize_t i, n;
10074 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000010075
Benjamin Peterson14339b62009-01-31 16:36:08 +000010076 if (interned == NULL || !PyDict_Check(interned))
10077 return;
10078 keys = PyDict_Keys(interned);
10079 if (keys == NULL || !PyList_Check(keys)) {
10080 PyErr_Clear();
10081 return;
10082 }
Walter Dörwald16807132007-05-25 13:52:07 +000010083
Benjamin Peterson14339b62009-01-31 16:36:08 +000010084 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
10085 detector, interned unicode strings are not forcibly deallocated;
10086 rather, we give them their stolen references back, and then clear
10087 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000010088
Benjamin Peterson14339b62009-01-31 16:36:08 +000010089 n = PyList_GET_SIZE(keys);
10090 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000010091 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010092 for (i = 0; i < n; i++) {
10093 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
10094 switch (s->state) {
10095 case SSTATE_NOT_INTERNED:
10096 /* XXX Shouldn't happen */
10097 break;
10098 case SSTATE_INTERNED_IMMORTAL:
10099 Py_REFCNT(s) += 1;
10100 immortal_size += s->length;
10101 break;
10102 case SSTATE_INTERNED_MORTAL:
10103 Py_REFCNT(s) += 2;
10104 mortal_size += s->length;
10105 break;
10106 default:
10107 Py_FatalError("Inconsistent interned string state.");
10108 }
10109 s->state = SSTATE_NOT_INTERNED;
10110 }
10111 fprintf(stderr, "total size of all interned strings: "
10112 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
10113 "mortal/immortal\n", mortal_size, immortal_size);
10114 Py_DECREF(keys);
10115 PyDict_Clear(interned);
10116 Py_DECREF(interned);
10117 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000010118}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010119
10120
10121/********************* Unicode Iterator **************************/
10122
10123typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010124 PyObject_HEAD
10125 Py_ssize_t it_index;
10126 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010127} unicodeiterobject;
10128
10129static void
10130unicodeiter_dealloc(unicodeiterobject *it)
10131{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010132 _PyObject_GC_UNTRACK(it);
10133 Py_XDECREF(it->it_seq);
10134 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010135}
10136
10137static int
10138unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
10139{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010140 Py_VISIT(it->it_seq);
10141 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010142}
10143
10144static PyObject *
10145unicodeiter_next(unicodeiterobject *it)
10146{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010147 PyUnicodeObject *seq;
10148 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010149
Benjamin Peterson14339b62009-01-31 16:36:08 +000010150 assert(it != NULL);
10151 seq = it->it_seq;
10152 if (seq == NULL)
10153 return NULL;
10154 assert(PyUnicode_Check(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010155
Benjamin Peterson14339b62009-01-31 16:36:08 +000010156 if (it->it_index < PyUnicode_GET_SIZE(seq)) {
10157 item = PyUnicode_FromUnicode(
Benjamin Peterson29060642009-01-31 22:14:21 +000010158 PyUnicode_AS_UNICODE(seq)+it->it_index, 1);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010159 if (item != NULL)
10160 ++it->it_index;
10161 return item;
10162 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010163
Benjamin Peterson14339b62009-01-31 16:36:08 +000010164 Py_DECREF(seq);
10165 it->it_seq = NULL;
10166 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010167}
10168
10169static PyObject *
10170unicodeiter_len(unicodeiterobject *it)
10171{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010172 Py_ssize_t len = 0;
10173 if (it->it_seq)
10174 len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index;
10175 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010176}
10177
10178PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
10179
10180static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010181 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000010182 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000010183 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010184};
10185
10186PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010187 PyVarObject_HEAD_INIT(&PyType_Type, 0)
10188 "str_iterator", /* tp_name */
10189 sizeof(unicodeiterobject), /* tp_basicsize */
10190 0, /* tp_itemsize */
10191 /* methods */
10192 (destructor)unicodeiter_dealloc, /* tp_dealloc */
10193 0, /* tp_print */
10194 0, /* tp_getattr */
10195 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000010196 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000010197 0, /* tp_repr */
10198 0, /* tp_as_number */
10199 0, /* tp_as_sequence */
10200 0, /* tp_as_mapping */
10201 0, /* tp_hash */
10202 0, /* tp_call */
10203 0, /* tp_str */
10204 PyObject_GenericGetAttr, /* tp_getattro */
10205 0, /* tp_setattro */
10206 0, /* tp_as_buffer */
10207 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
10208 0, /* tp_doc */
10209 (traverseproc)unicodeiter_traverse, /* tp_traverse */
10210 0, /* tp_clear */
10211 0, /* tp_richcompare */
10212 0, /* tp_weaklistoffset */
10213 PyObject_SelfIter, /* tp_iter */
10214 (iternextfunc)unicodeiter_next, /* tp_iternext */
10215 unicodeiter_methods, /* tp_methods */
10216 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010217};
10218
10219static PyObject *
10220unicode_iter(PyObject *seq)
10221{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010222 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010223
Benjamin Peterson14339b62009-01-31 16:36:08 +000010224 if (!PyUnicode_Check(seq)) {
10225 PyErr_BadInternalCall();
10226 return NULL;
10227 }
10228 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
10229 if (it == NULL)
10230 return NULL;
10231 it->it_index = 0;
10232 Py_INCREF(seq);
10233 it->it_seq = (PyUnicodeObject *)seq;
10234 _PyObject_GC_TRACK(it);
10235 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010236}
10237
Martin v. Löwis5b222132007-06-10 09:51:05 +000010238size_t
10239Py_UNICODE_strlen(const Py_UNICODE *u)
10240{
10241 int res = 0;
10242 while(*u++)
10243 res++;
10244 return res;
10245}
10246
10247Py_UNICODE*
10248Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
10249{
10250 Py_UNICODE *u = s1;
10251 while ((*u++ = *s2++));
10252 return s1;
10253}
10254
10255Py_UNICODE*
10256Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
10257{
10258 Py_UNICODE *u = s1;
10259 while ((*u++ = *s2++))
10260 if (n-- == 0)
10261 break;
10262 return s1;
10263}
10264
Victor Stinnerc4eb7652010-09-01 23:43:50 +000010265Py_UNICODE*
10266Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
10267{
10268 Py_UNICODE *u1 = s1;
10269 u1 += Py_UNICODE_strlen(u1);
10270 Py_UNICODE_strcpy(u1, s2);
10271 return s1;
10272}
10273
Martin v. Löwis5b222132007-06-10 09:51:05 +000010274int
10275Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
10276{
10277 while (*s1 && *s2 && *s1 == *s2)
10278 s1++, s2++;
10279 if (*s1 && *s2)
10280 return (*s1 < *s2) ? -1 : +1;
10281 if (*s1)
10282 return 1;
10283 if (*s2)
10284 return -1;
10285 return 0;
10286}
10287
Victor Stinneref8d95c2010-08-16 22:03:11 +000010288int
10289Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
10290{
10291 register Py_UNICODE u1, u2;
10292 for (; n != 0; n--) {
10293 u1 = *s1;
10294 u2 = *s2;
10295 if (u1 != u2)
10296 return (u1 < u2) ? -1 : +1;
10297 if (u1 == '\0')
10298 return 0;
10299 s1++;
10300 s2++;
10301 }
10302 return 0;
10303}
10304
Martin v. Löwis5b222132007-06-10 09:51:05 +000010305Py_UNICODE*
10306Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
10307{
10308 const Py_UNICODE *p;
10309 for (p = s; *p; p++)
10310 if (*p == c)
10311 return (Py_UNICODE*)p;
10312 return NULL;
10313}
10314
Victor Stinner331ea922010-08-10 16:37:20 +000010315Py_UNICODE*
10316Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
10317{
10318 const Py_UNICODE *p;
10319 p = s + Py_UNICODE_strlen(s);
10320 while (p != s) {
10321 p--;
10322 if (*p == c)
10323 return (Py_UNICODE*)p;
10324 }
10325 return NULL;
10326}
10327
Victor Stinner71133ff2010-09-01 23:43:53 +000010328Py_UNICODE*
Victor Stinner46408602010-09-03 16:18:00 +000010329PyUnicode_AsUnicodeCopy(PyObject *object)
Victor Stinner71133ff2010-09-01 23:43:53 +000010330{
10331 PyUnicodeObject *unicode = (PyUnicodeObject *)object;
10332 Py_UNICODE *copy;
10333 Py_ssize_t size;
10334
10335 /* Ensure we won't overflow the size. */
10336 if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
10337 PyErr_NoMemory();
10338 return NULL;
10339 }
10340 size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
10341 size *= sizeof(Py_UNICODE);
10342 copy = PyMem_Malloc(size);
10343 if (copy == NULL) {
10344 PyErr_NoMemory();
10345 return NULL;
10346 }
10347 memcpy(copy, PyUnicode_AS_UNICODE(unicode), size);
10348 return copy;
10349}
Martin v. Löwis5b222132007-06-10 09:51:05 +000010350
Georg Brandl66c221e2010-10-14 07:04:07 +000010351/* A _string module, to export formatter_parser and formatter_field_name_split
10352 to the string.Formatter class implemented in Python. */
10353
10354static PyMethodDef _string_methods[] = {
10355 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
10356 METH_O, PyDoc_STR("split the argument as a field name")},
10357 {"formatter_parser", (PyCFunction) formatter_parser,
10358 METH_O, PyDoc_STR("parse the argument as a format string")},
10359 {NULL, NULL}
10360};
10361
10362static struct PyModuleDef _string_module = {
10363 PyModuleDef_HEAD_INIT,
10364 "_string",
10365 PyDoc_STR("string helper module"),
10366 0,
10367 _string_methods,
10368 NULL,
10369 NULL,
10370 NULL,
10371 NULL
10372};
10373
10374PyMODINIT_FUNC
10375PyInit__string(void)
10376{
10377 return PyModule_Create(&_string_module);
10378}
10379
10380
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010381#ifdef __cplusplus
10382}
10383#endif