blob: b70666106d274fc475aa2eacd013942d7220f293 [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Fred Drake785d14f2000-05-09 19:54:43 +00004modified by Marc-Andre Lemburg <mal@lemburg.com> according to the
Guido van Rossumd57fd912000-03-10 22:53:23 +00005Unicode Integration Proposal (see file Misc/unicode.txt).
6
Thomas Wouters477c8d52006-05-27 19:21:47 +00007Major speed upgrades to the method implementations at the Reykjavik
8NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
9
Guido van Rossum16b1ad92000-08-03 16:24:25 +000010Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000011
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000012--------------------------------------------------------------------
13The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000014
Benjamin Peterson29060642009-01-31 22:14:21 +000015 Copyright (c) 1999 by Secret Labs AB
16 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000017
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000018By obtaining, using, and/or copying this software and/or its
19associated documentation, you agree that you have read, understood,
20and will comply with the following terms and conditions:
21
22Permission to use, copy, modify, and distribute this software and its
23associated documentation for any purpose and without fee is hereby
24granted, provided that the above copyright notice appears in all
25copies, and that both that copyright notice and this permission notice
26appear in supporting documentation, and that the name of Secret Labs
27AB or the author not be used in advertising or publicity pertaining to
28distribution of the software without specific, written prior
29permission.
30
31SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
32THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
33FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
34ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
35WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
36ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
37OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
38--------------------------------------------------------------------
39
40*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000041
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000042#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000043#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000044#include "ucnhash.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000045
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000046#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000047#include <windows.h>
48#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000049
Guido van Rossumd57fd912000-03-10 22:53:23 +000050/* Limit for the Unicode object free list */
51
Christian Heimes2202f872008-02-06 14:31:34 +000052#define PyUnicode_MAXFREELIST 1024
Guido van Rossumd57fd912000-03-10 22:53:23 +000053
54/* Limit for the Unicode object free list stay alive optimization.
55
56 The implementation will keep allocated Unicode memory intact for
57 all objects on the free list having a size less than this
Tim Petersced69f82003-09-16 20:30:58 +000058 limit. This reduces malloc() overhead for small Unicode objects.
Guido van Rossumd57fd912000-03-10 22:53:23 +000059
Christian Heimes2202f872008-02-06 14:31:34 +000060 At worst this will result in PyUnicode_MAXFREELIST *
Guido van Rossumfd4b9572000-04-10 13:51:10 +000061 (sizeof(PyUnicodeObject) + KEEPALIVE_SIZE_LIMIT +
Guido van Rossumd57fd912000-03-10 22:53:23 +000062 malloc()-overhead) bytes of unused garbage.
63
64 Setting the limit to 0 effectively turns the feature off.
65
Guido van Rossumfd4b9572000-04-10 13:51:10 +000066 Note: This is an experimental feature ! If you get core dumps when
67 using Unicode objects, turn this feature off.
Guido van Rossumd57fd912000-03-10 22:53:23 +000068
69*/
70
Guido van Rossumfd4b9572000-04-10 13:51:10 +000071#define KEEPALIVE_SIZE_LIMIT 9
Guido van Rossumd57fd912000-03-10 22:53:23 +000072
73/* Endianness switches; defaults to little endian */
74
75#ifdef WORDS_BIGENDIAN
76# define BYTEORDER_IS_BIG_ENDIAN
77#else
78# define BYTEORDER_IS_LITTLE_ENDIAN
79#endif
80
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000081/* --- Globals ------------------------------------------------------------
82
83 The globals are initialized by the _PyUnicode_Init() API and should
84 not be used before calling that API.
85
86*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000087
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000088
89#ifdef __cplusplus
90extern "C" {
91#endif
92
Walter Dörwald16807132007-05-25 13:52:07 +000093/* This dictionary holds all interned unicode strings. Note that references
94 to strings in this dictionary are *not* counted in the string's ob_refcnt.
95 When the interned string reaches a refcnt of 0 the string deallocation
96 function will delete the reference from this dictionary.
97
98 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +000099 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000100*/
101static PyObject *interned;
102
Guido van Rossumd57fd912000-03-10 22:53:23 +0000103/* Free list for Unicode objects */
Christian Heimes2202f872008-02-06 14:31:34 +0000104static PyUnicodeObject *free_list;
105static int numfree;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000106
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000107/* The empty Unicode object is shared to improve performance. */
108static PyUnicodeObject *unicode_empty;
109
110/* Single character Unicode strings in the Latin-1 range are being
111 shared as well. */
112static PyUnicodeObject *unicode_latin1[256];
113
Christian Heimes190d79e2008-01-30 11:58:22 +0000114/* Fast detection of the most frequent whitespace characters */
115const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000116 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000117/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000118/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000119/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000120/* case 0x000C: * FORM FEED */
121/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000122 0, 1, 1, 1, 1, 1, 0, 0,
123 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000124/* case 0x001C: * FILE SEPARATOR */
125/* case 0x001D: * GROUP SEPARATOR */
126/* case 0x001E: * RECORD SEPARATOR */
127/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000128 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000129/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000130 1, 0, 0, 0, 0, 0, 0, 0,
131 0, 0, 0, 0, 0, 0, 0, 0,
132 0, 0, 0, 0, 0, 0, 0, 0,
133 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000134
Benjamin Peterson14339b62009-01-31 16:36:08 +0000135 0, 0, 0, 0, 0, 0, 0, 0,
136 0, 0, 0, 0, 0, 0, 0, 0,
137 0, 0, 0, 0, 0, 0, 0, 0,
138 0, 0, 0, 0, 0, 0, 0, 0,
139 0, 0, 0, 0, 0, 0, 0, 0,
140 0, 0, 0, 0, 0, 0, 0, 0,
141 0, 0, 0, 0, 0, 0, 0, 0,
142 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000143};
144
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000145static PyObject *unicode_encode_call_errorhandler(const char *errors,
146 PyObject **errorHandler,const char *encoding, const char *reason,
147 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
148 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
149
Victor Stinner31be90b2010-04-22 19:38:16 +0000150static void raise_encode_exception(PyObject **exceptionObject,
151 const char *encoding,
152 const Py_UNICODE *unicode, Py_ssize_t size,
153 Py_ssize_t startpos, Py_ssize_t endpos,
154 const char *reason);
155
Christian Heimes190d79e2008-01-30 11:58:22 +0000156/* Same for linebreaks */
157static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000158 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000159/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000160/* 0x000B, * LINE TABULATION */
161/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000162/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000163 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000164 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000165/* 0x001C, * FILE SEPARATOR */
166/* 0x001D, * GROUP SEPARATOR */
167/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000168 0, 0, 0, 0, 1, 1, 1, 0,
169 0, 0, 0, 0, 0, 0, 0, 0,
170 0, 0, 0, 0, 0, 0, 0, 0,
171 0, 0, 0, 0, 0, 0, 0, 0,
172 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000173
Benjamin Peterson14339b62009-01-31 16:36:08 +0000174 0, 0, 0, 0, 0, 0, 0, 0,
175 0, 0, 0, 0, 0, 0, 0, 0,
176 0, 0, 0, 0, 0, 0, 0, 0,
177 0, 0, 0, 0, 0, 0, 0, 0,
178 0, 0, 0, 0, 0, 0, 0, 0,
179 0, 0, 0, 0, 0, 0, 0, 0,
180 0, 0, 0, 0, 0, 0, 0, 0,
181 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000182};
183
184
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000185Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000186PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000187{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000188#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000189 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000190#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000191 /* This is actually an illegal character, so it should
192 not be passed to unichr. */
193 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000194#endif
195}
196
Thomas Wouters477c8d52006-05-27 19:21:47 +0000197/* --- Bloom Filters ----------------------------------------------------- */
198
199/* stuff to implement simple "bloom filters" for Unicode characters.
200 to keep things simple, we use a single bitmask, using the least 5
201 bits from each unicode characters as the bit index. */
202
203/* the linebreak mask is set up by Unicode_Init below */
204
Antoine Pitrouf068f942010-01-13 14:19:12 +0000205#if LONG_BIT >= 128
206#define BLOOM_WIDTH 128
207#elif LONG_BIT >= 64
208#define BLOOM_WIDTH 64
209#elif LONG_BIT >= 32
210#define BLOOM_WIDTH 32
211#else
212#error "LONG_BIT is smaller than 32"
213#endif
214
Thomas Wouters477c8d52006-05-27 19:21:47 +0000215#define BLOOM_MASK unsigned long
216
217static BLOOM_MASK bloom_linebreak;
218
Antoine Pitrouf068f942010-01-13 14:19:12 +0000219#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
220#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000221
Benjamin Peterson29060642009-01-31 22:14:21 +0000222#define BLOOM_LINEBREAK(ch) \
223 ((ch) < 128U ? ascii_linebreak[(ch)] : \
224 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000225
226Py_LOCAL_INLINE(BLOOM_MASK) make_bloom_mask(Py_UNICODE* ptr, Py_ssize_t len)
227{
228 /* calculate simple bloom-style bitmask for a given unicode string */
229
Antoine Pitrouf068f942010-01-13 14:19:12 +0000230 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000231 Py_ssize_t i;
232
233 mask = 0;
234 for (i = 0; i < len; i++)
Antoine Pitrouf2c54842010-01-13 08:07:53 +0000235 BLOOM_ADD(mask, ptr[i]);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000236
237 return mask;
238}
239
240Py_LOCAL_INLINE(int) unicode_member(Py_UNICODE chr, Py_UNICODE* set, Py_ssize_t setlen)
241{
242 Py_ssize_t i;
243
244 for (i = 0; i < setlen; i++)
245 if (set[i] == chr)
246 return 1;
247
248 return 0;
249}
250
Benjamin Peterson29060642009-01-31 22:14:21 +0000251#define BLOOM_MEMBER(mask, chr, set, setlen) \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000252 BLOOM(mask, chr) && unicode_member(chr, set, setlen)
253
Guido van Rossumd57fd912000-03-10 22:53:23 +0000254/* --- Unicode Object ----------------------------------------------------- */
255
256static
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000257int unicode_resize(register PyUnicodeObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +0000258 Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000259{
260 void *oldstr;
Tim Petersced69f82003-09-16 20:30:58 +0000261
Guido van Rossumfd4b9572000-04-10 13:51:10 +0000262 /* Shortcut if there's nothing much to do. */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000263 if (unicode->length == length)
Benjamin Peterson29060642009-01-31 22:14:21 +0000264 goto reset;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000265
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000266 /* Resizing shared object (unicode_empty or single character
267 objects) in-place is not allowed. Use PyUnicode_Resize()
268 instead ! */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000269
Benjamin Peterson14339b62009-01-31 16:36:08 +0000270 if (unicode == unicode_empty ||
Benjamin Peterson29060642009-01-31 22:14:21 +0000271 (unicode->length == 1 &&
272 unicode->str[0] < 256U &&
273 unicode_latin1[unicode->str[0]] == unicode)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +0000274 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson142957c2008-07-04 19:55:29 +0000275 "can't resize shared str objects");
Guido van Rossumd57fd912000-03-10 22:53:23 +0000276 return -1;
277 }
278
Thomas Wouters477c8d52006-05-27 19:21:47 +0000279 /* We allocate one more byte to make sure the string is Ux0000 terminated.
280 The overallocation is also used by fastsearch, which assumes that it's
281 safe to look at str[length] (without making any assumptions about what
282 it contains). */
283
Guido van Rossumd57fd912000-03-10 22:53:23 +0000284 oldstr = unicode->str;
Christian Heimesb186d002008-03-18 15:15:01 +0000285 unicode->str = PyObject_REALLOC(unicode->str,
Benjamin Peterson29060642009-01-31 22:14:21 +0000286 sizeof(Py_UNICODE) * (length + 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000287 if (!unicode->str) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000288 unicode->str = (Py_UNICODE *)oldstr;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000289 PyErr_NoMemory();
290 return -1;
291 }
292 unicode->str[length] = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000293 unicode->length = length;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000294
Benjamin Peterson29060642009-01-31 22:14:21 +0000295 reset:
Guido van Rossumd57fd912000-03-10 22:53:23 +0000296 /* Reset the object caches */
Marc-André Lemburgbff879c2000-08-03 18:46:08 +0000297 if (unicode->defenc) {
Georg Brandl8ee604b2010-07-29 14:23:06 +0000298 Py_CLEAR(unicode->defenc);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000299 }
300 unicode->hash = -1;
Tim Petersced69f82003-09-16 20:30:58 +0000301
Guido van Rossumd57fd912000-03-10 22:53:23 +0000302 return 0;
303}
304
305/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000306 Ux0000 terminated; some code (e.g. new_identifier)
307 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000308
309 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000310 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000311
312*/
313
314static
Martin v. Löwis18e16552006-02-15 17:27:45 +0000315PyUnicodeObject *_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000316{
317 register PyUnicodeObject *unicode;
318
Thomas Wouters477c8d52006-05-27 19:21:47 +0000319 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000320 if (length == 0 && unicode_empty != NULL) {
321 Py_INCREF(unicode_empty);
322 return unicode_empty;
323 }
324
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000325 /* Ensure we won't overflow the size. */
326 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
327 return (PyUnicodeObject *)PyErr_NoMemory();
328 }
329
Guido van Rossumd57fd912000-03-10 22:53:23 +0000330 /* Unicode freelist & memory allocation */
Christian Heimes2202f872008-02-06 14:31:34 +0000331 if (free_list) {
332 unicode = free_list;
333 free_list = *(PyUnicodeObject **)unicode;
334 numfree--;
Benjamin Peterson29060642009-01-31 22:14:21 +0000335 if (unicode->str) {
336 /* Keep-Alive optimization: we only upsize the buffer,
337 never downsize it. */
338 if ((unicode->length < length) &&
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +0000339 unicode_resize(unicode, length) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000340 PyObject_DEL(unicode->str);
341 unicode->str = NULL;
342 }
Benjamin Peterson14339b62009-01-31 16:36:08 +0000343 }
Guido van Rossumad98db12001-06-14 17:52:02 +0000344 else {
Benjamin Peterson29060642009-01-31 22:14:21 +0000345 size_t new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
346 unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
Guido van Rossumad98db12001-06-14 17:52:02 +0000347 }
348 PyObject_INIT(unicode, &PyUnicode_Type);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000349 }
350 else {
Benjamin Peterson29060642009-01-31 22:14:21 +0000351 size_t new_size;
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000352 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000353 if (unicode == NULL)
354 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +0000355 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
356 unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000357 }
358
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000359 if (!unicode->str) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000360 PyErr_NoMemory();
361 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000362 }
Jeremy Hyltond8082792003-09-16 19:41:39 +0000363 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000364 * the caller fails before initializing str -- unicode_resize()
365 * reads str[0], and the Keep-Alive optimization can keep memory
366 * allocated for str alive across a call to unicode_dealloc(unicode).
367 * We don't want unicode_resize to read uninitialized memory in
368 * that case.
369 */
Jeremy Hyltond8082792003-09-16 19:41:39 +0000370 unicode->str[0] = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000371 unicode->str[length] = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000372 unicode->length = length;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000373 unicode->hash = -1;
Walter Dörwald16807132007-05-25 13:52:07 +0000374 unicode->state = 0;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +0000375 unicode->defenc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000376 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000377
Benjamin Peterson29060642009-01-31 22:14:21 +0000378 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000379 /* XXX UNREF/NEWREF interface should be more symmetrical */
380 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000381 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000382 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000383 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000384}
385
386static
Guido van Rossum9475a232001-10-05 20:51:39 +0000387void unicode_dealloc(register PyUnicodeObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000388{
Walter Dörwald16807132007-05-25 13:52:07 +0000389 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000390 case SSTATE_NOT_INTERNED:
391 break;
Walter Dörwald16807132007-05-25 13:52:07 +0000392
Benjamin Peterson29060642009-01-31 22:14:21 +0000393 case SSTATE_INTERNED_MORTAL:
394 /* revive dead object temporarily for DelItem */
395 Py_REFCNT(unicode) = 3;
396 if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
397 Py_FatalError(
398 "deletion of interned string failed");
399 break;
Walter Dörwald16807132007-05-25 13:52:07 +0000400
Benjamin Peterson29060642009-01-31 22:14:21 +0000401 case SSTATE_INTERNED_IMMORTAL:
402 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +0000403
Benjamin Peterson29060642009-01-31 22:14:21 +0000404 default:
405 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +0000406 }
407
Guido van Rossum604ddf82001-12-06 20:03:56 +0000408 if (PyUnicode_CheckExact(unicode) &&
Benjamin Peterson29060642009-01-31 22:14:21 +0000409 numfree < PyUnicode_MAXFREELIST) {
Guido van Rossumfd4b9572000-04-10 13:51:10 +0000410 /* Keep-Alive optimization */
Benjamin Peterson29060642009-01-31 22:14:21 +0000411 if (unicode->length >= KEEPALIVE_SIZE_LIMIT) {
412 PyObject_DEL(unicode->str);
413 unicode->str = NULL;
414 unicode->length = 0;
415 }
416 if (unicode->defenc) {
Georg Brandl8ee604b2010-07-29 14:23:06 +0000417 Py_CLEAR(unicode->defenc);
Benjamin Peterson29060642009-01-31 22:14:21 +0000418 }
419 /* Add to free list */
Christian Heimes2202f872008-02-06 14:31:34 +0000420 *(PyUnicodeObject **)unicode = free_list;
421 free_list = unicode;
422 numfree++;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000423 }
424 else {
Benjamin Peterson29060642009-01-31 22:14:21 +0000425 PyObject_DEL(unicode->str);
426 Py_XDECREF(unicode->defenc);
427 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000428 }
429}
430
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000431static
432int _PyUnicode_Resize(PyUnicodeObject **unicode, Py_ssize_t length)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000433{
434 register PyUnicodeObject *v;
435
436 /* Argument checks */
437 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000438 PyErr_BadInternalCall();
439 return -1;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000440 }
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000441 v = *unicode;
Christian Heimes90aa7642007-12-19 02:45:37 +0000442 if (v == NULL || !PyUnicode_Check(v) || Py_REFCNT(v) != 1 || length < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000443 PyErr_BadInternalCall();
444 return -1;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000445 }
446
447 /* Resizing unicode_empty and single character objects is not
448 possible since these are being shared. We simply return a fresh
449 copy with the same Unicode content. */
Tim Petersced69f82003-09-16 20:30:58 +0000450 if (v->length != length &&
Benjamin Peterson29060642009-01-31 22:14:21 +0000451 (v == unicode_empty || v->length == 1)) {
452 PyUnicodeObject *w = _PyUnicode_New(length);
453 if (w == NULL)
454 return -1;
455 Py_UNICODE_COPY(w->str, v->str,
456 length < v->length ? length : v->length);
457 Py_DECREF(*unicode);
458 *unicode = w;
459 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000460 }
461
462 /* Note that we don't have to modify *unicode for unshared Unicode
463 objects, since we can modify them in-place. */
464 return unicode_resize(v, length);
465}
466
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000467int PyUnicode_Resize(PyObject **unicode, Py_ssize_t length)
468{
469 return _PyUnicode_Resize((PyUnicodeObject **)unicode, length);
470}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000471
Guido van Rossumd57fd912000-03-10 22:53:23 +0000472PyObject *PyUnicode_FromUnicode(const Py_UNICODE *u,
Benjamin Peterson29060642009-01-31 22:14:21 +0000473 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000474{
475 PyUnicodeObject *unicode;
476
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000477 /* If the Unicode data is known at construction time, we can apply
478 some optimizations which share commonly used objects. */
479 if (u != NULL) {
480
Benjamin Peterson29060642009-01-31 22:14:21 +0000481 /* Optimization for empty strings */
482 if (size == 0 && unicode_empty != NULL) {
483 Py_INCREF(unicode_empty);
484 return (PyObject *)unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000485 }
Benjamin Peterson29060642009-01-31 22:14:21 +0000486
487 /* Single character Unicode objects in the Latin-1 range are
488 shared when using this constructor */
489 if (size == 1 && *u < 256) {
490 unicode = unicode_latin1[*u];
491 if (!unicode) {
492 unicode = _PyUnicode_New(1);
493 if (!unicode)
494 return NULL;
495 unicode->str[0] = *u;
496 unicode_latin1[*u] = unicode;
497 }
498 Py_INCREF(unicode);
499 return (PyObject *)unicode;
500 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000501 }
Tim Petersced69f82003-09-16 20:30:58 +0000502
Guido van Rossumd57fd912000-03-10 22:53:23 +0000503 unicode = _PyUnicode_New(size);
504 if (!unicode)
505 return NULL;
506
507 /* Copy the Unicode data into the new object */
508 if (u != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +0000509 Py_UNICODE_COPY(unicode->str, u, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000510
511 return (PyObject *)unicode;
512}
513
Walter Dörwaldd2034312007-05-18 16:29:38 +0000514PyObject *PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000515{
516 PyUnicodeObject *unicode;
Christian Heimes33fe8092008-04-13 13:53:33 +0000517
Benjamin Peterson14339b62009-01-31 16:36:08 +0000518 if (size < 0) {
519 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +0000520 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +0000521 return NULL;
522 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000523
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000524 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +0000525 some optimizations which share commonly used objects.
526 Also, this means the input must be UTF-8, so fall back to the
527 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000528 if (u != NULL) {
529
Benjamin Peterson29060642009-01-31 22:14:21 +0000530 /* Optimization for empty strings */
531 if (size == 0 && unicode_empty != NULL) {
532 Py_INCREF(unicode_empty);
533 return (PyObject *)unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000534 }
Benjamin Peterson29060642009-01-31 22:14:21 +0000535
536 /* Single characters are shared when using this constructor.
537 Restrict to ASCII, since the input must be UTF-8. */
538 if (size == 1 && Py_CHARMASK(*u) < 128) {
539 unicode = unicode_latin1[Py_CHARMASK(*u)];
540 if (!unicode) {
541 unicode = _PyUnicode_New(1);
542 if (!unicode)
543 return NULL;
544 unicode->str[0] = Py_CHARMASK(*u);
545 unicode_latin1[Py_CHARMASK(*u)] = unicode;
546 }
547 Py_INCREF(unicode);
548 return (PyObject *)unicode;
549 }
Martin v. Löwis9c121062007-08-05 20:26:11 +0000550
551 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000552 }
553
Walter Dörwald55507312007-05-18 13:12:10 +0000554 unicode = _PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000555 if (!unicode)
556 return NULL;
557
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000558 return (PyObject *)unicode;
559}
560
Walter Dörwaldd2034312007-05-18 16:29:38 +0000561PyObject *PyUnicode_FromString(const char *u)
562{
563 size_t size = strlen(u);
564 if (size > PY_SSIZE_T_MAX) {
565 PyErr_SetString(PyExc_OverflowError, "input too long");
566 return NULL;
567 }
568
569 return PyUnicode_FromStringAndSize(u, size);
570}
571
Guido van Rossumd57fd912000-03-10 22:53:23 +0000572#ifdef HAVE_WCHAR_H
573
Mark Dickinson081dfee2009-03-18 14:47:41 +0000574#if (Py_UNICODE_SIZE == 2) && defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4)
575# define CONVERT_WCHAR_TO_SURROGATES
576#endif
577
578#ifdef CONVERT_WCHAR_TO_SURROGATES
579
580/* Here sizeof(wchar_t) is 4 but Py_UNICODE_SIZE == 2, so we need
581 to convert from UTF32 to UTF16. */
582
583PyObject *PyUnicode_FromWideChar(register const wchar_t *w,
584 Py_ssize_t size)
585{
586 PyUnicodeObject *unicode;
587 register Py_ssize_t i;
588 Py_ssize_t alloc;
589 const wchar_t *orig_w;
590
591 if (w == NULL) {
592 if (size == 0)
593 return PyUnicode_FromStringAndSize(NULL, 0);
594 PyErr_BadInternalCall();
595 return NULL;
596 }
597
598 if (size == -1) {
599 size = wcslen(w);
600 }
601
602 alloc = size;
603 orig_w = w;
604 for (i = size; i > 0; i--) {
605 if (*w > 0xFFFF)
606 alloc++;
607 w++;
608 }
609 w = orig_w;
610 unicode = _PyUnicode_New(alloc);
611 if (!unicode)
612 return NULL;
613
614 /* Copy the wchar_t data into the new object */
615 {
616 register Py_UNICODE *u;
617 u = PyUnicode_AS_UNICODE(unicode);
618 for (i = size; i > 0; i--) {
619 if (*w > 0xFFFF) {
620 wchar_t ordinal = *w++;
621 ordinal -= 0x10000;
622 *u++ = 0xD800 | (ordinal >> 10);
623 *u++ = 0xDC00 | (ordinal & 0x3FF);
624 }
625 else
626 *u++ = *w++;
627 }
628 }
629 return (PyObject *)unicode;
630}
631
632#else
633
Guido van Rossumd57fd912000-03-10 22:53:23 +0000634PyObject *PyUnicode_FromWideChar(register const wchar_t *w,
Benjamin Peterson29060642009-01-31 22:14:21 +0000635 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000636{
637 PyUnicodeObject *unicode;
638
639 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +0000640 if (size == 0)
641 return PyUnicode_FromStringAndSize(NULL, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +0000642 PyErr_BadInternalCall();
643 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000644 }
645
Martin v. Löwis790465f2008-04-05 20:41:37 +0000646 if (size == -1) {
647 size = wcslen(w);
648 }
649
Guido van Rossumd57fd912000-03-10 22:53:23 +0000650 unicode = _PyUnicode_New(size);
651 if (!unicode)
652 return NULL;
653
654 /* Copy the wchar_t data into the new object */
Daniel Stutzbach8515eae2010-08-24 21:57:33 +0000655#if Py_UNICODE_SIZE == SIZEOF_WCHAR_T
Guido van Rossumd57fd912000-03-10 22:53:23 +0000656 memcpy(unicode->str, w, size * sizeof(wchar_t));
Tim Petersced69f82003-09-16 20:30:58 +0000657#else
Guido van Rossumd57fd912000-03-10 22:53:23 +0000658 {
Benjamin Peterson29060642009-01-31 22:14:21 +0000659 register Py_UNICODE *u;
660 register Py_ssize_t i;
661 u = PyUnicode_AS_UNICODE(unicode);
662 for (i = size; i > 0; i--)
663 *u++ = *w++;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000664 }
665#endif
666
667 return (PyObject *)unicode;
668}
669
Mark Dickinson081dfee2009-03-18 14:47:41 +0000670#endif /* CONVERT_WCHAR_TO_SURROGATES */
671
672#undef CONVERT_WCHAR_TO_SURROGATES
673
Walter Dörwald346737f2007-05-31 10:44:43 +0000674static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000675makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
676 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +0000677{
Benjamin Peterson14339b62009-01-31 16:36:08 +0000678 *fmt++ = '%';
679 if (width) {
680 if (zeropad)
681 *fmt++ = '0';
682 fmt += sprintf(fmt, "%d", width);
683 }
684 if (precision)
685 fmt += sprintf(fmt, ".%d", precision);
686 if (longflag)
687 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000688 else if (longlongflag) {
689 /* longlongflag should only ever be nonzero on machines with
690 HAVE_LONG_LONG defined */
691#ifdef HAVE_LONG_LONG
692 char *f = PY_FORMAT_LONG_LONG;
693 while (*f)
694 *fmt++ = *f++;
695#else
696 /* we shouldn't ever get here */
697 assert(0);
698 *fmt++ = 'l';
699#endif
700 }
Benjamin Peterson14339b62009-01-31 16:36:08 +0000701 else if (size_tflag) {
702 char *f = PY_FORMAT_SIZE_T;
703 while (*f)
704 *fmt++ = *f++;
705 }
706 *fmt++ = c;
707 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +0000708}
709
Walter Dörwaldd2034312007-05-18 16:29:38 +0000710#define appendstring(string) {for (copy = string;*copy;) *s++ = *copy++;}
711
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000712/* size of fixed-size buffer for formatting single arguments */
713#define ITEM_BUFFER_LEN 21
714/* maximum number of characters required for output of %ld. 21 characters
715 allows for 64-bit integers (in decimal) and an optional sign. */
716#define MAX_LONG_CHARS 21
717/* maximum number of characters required for output of %lld.
718 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
719 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
720#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
721
Walter Dörwaldd2034312007-05-18 16:29:38 +0000722PyObject *
723PyUnicode_FromFormatV(const char *format, va_list vargs)
724{
Benjamin Peterson14339b62009-01-31 16:36:08 +0000725 va_list count;
726 Py_ssize_t callcount = 0;
727 PyObject **callresults = NULL;
728 PyObject **callresult = NULL;
729 Py_ssize_t n = 0;
730 int width = 0;
731 int precision = 0;
732 int zeropad;
733 const char* f;
734 Py_UNICODE *s;
735 PyObject *string;
736 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000737 char buffer[ITEM_BUFFER_LEN+1];
Benjamin Peterson14339b62009-01-31 16:36:08 +0000738 /* use abuffer instead of buffer, if we need more space
739 * (which can happen if there's a format specifier with width). */
740 char *abuffer = NULL;
741 char *realbuffer;
742 Py_ssize_t abuffersize = 0;
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000743 char fmt[61]; /* should be enough for %0width.precisionlld */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000744 const char *copy;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000745
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000746 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000747 /* step 1: count the number of %S/%R/%A/%s format specifications
748 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
749 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
750 * result in an array) */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000751 for (f = format; *f; f++) {
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000752 if (*f == '%') {
753 if (*(f+1)=='%')
754 continue;
Victor Stinner2b574a22011-03-01 22:48:49 +0000755 if (*(f+1)=='S' || *(f+1)=='R' || *(f+1)=='A' || *(f+1) == 'V')
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000756 ++callcount;
David Malcolm96960882010-11-05 17:23:41 +0000757 while (Py_ISDIGIT((unsigned)*f))
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000758 width = (width*10) + *f++ - '0';
David Malcolm96960882010-11-05 17:23:41 +0000759 while (*++f && *f != '%' && !Py_ISALPHA((unsigned)*f))
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000760 ;
761 if (*f == 's')
762 ++callcount;
763 }
Benjamin Peterson9be0b2e2010-09-12 03:40:54 +0000764 else if (128 <= (unsigned char)*f) {
765 PyErr_Format(PyExc_ValueError,
766 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
Victor Stinner4c7db312010-09-12 07:51:18 +0000767 "string, got a non-ASCII byte: 0x%02x",
Benjamin Peterson9be0b2e2010-09-12 03:40:54 +0000768 (unsigned char)*f);
Benjamin Petersond4ac96a2010-09-12 16:40:53 +0000769 return NULL;
Benjamin Peterson9be0b2e2010-09-12 03:40:54 +0000770 }
Benjamin Peterson14339b62009-01-31 16:36:08 +0000771 }
772 /* step 2: allocate memory for the results of
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000773 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000774 if (callcount) {
775 callresults = PyObject_Malloc(sizeof(PyObject *)*callcount);
776 if (!callresults) {
777 PyErr_NoMemory();
778 return NULL;
779 }
780 callresult = callresults;
781 }
782 /* step 3: figure out how large a buffer we need */
783 for (f = format; *f; f++) {
784 if (*f == '%') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000785#ifdef HAVE_LONG_LONG
786 int longlongflag = 0;
787#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +0000788 const char* p = f;
789 width = 0;
David Malcolm96960882010-11-05 17:23:41 +0000790 while (Py_ISDIGIT((unsigned)*f))
Benjamin Peterson14339b62009-01-31 16:36:08 +0000791 width = (width*10) + *f++ - '0';
David Malcolm96960882010-11-05 17:23:41 +0000792 while (*++f && *f != '%' && !Py_ISALPHA((unsigned)*f))
Benjamin Peterson14339b62009-01-31 16:36:08 +0000793 ;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000794
Benjamin Peterson14339b62009-01-31 16:36:08 +0000795 /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
796 * they don't affect the amount of space we reserve.
797 */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000798 if (*f == 'l') {
799 if (f[1] == 'd' || f[1] == 'u') {
800 ++f;
801 }
802#ifdef HAVE_LONG_LONG
803 else if (f[1] == 'l' &&
804 (f[2] == 'd' || f[2] == 'u')) {
805 longlongflag = 1;
806 f += 2;
807 }
808#endif
809 }
810 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000811 ++f;
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000812 }
Walter Dörwaldd2034312007-05-18 16:29:38 +0000813
Benjamin Peterson14339b62009-01-31 16:36:08 +0000814 switch (*f) {
815 case 'c':
Victor Stinner659eb842011-02-23 12:14:22 +0000816 {
817#ifndef Py_UNICODE_WIDE
818 int ordinal = va_arg(count, int);
819 if (ordinal > 0xffff)
820 n += 2;
821 else
822 n++;
823#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000824 (void)va_arg(count, int);
Victor Stinner659eb842011-02-23 12:14:22 +0000825 n++;
826#endif
827 break;
828 }
Benjamin Peterson14339b62009-01-31 16:36:08 +0000829 case '%':
830 n++;
831 break;
832 case 'd': case 'u': case 'i': case 'x':
833 (void) va_arg(count, int);
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000834#ifdef HAVE_LONG_LONG
835 if (longlongflag) {
836 if (width < MAX_LONG_LONG_CHARS)
837 width = MAX_LONG_LONG_CHARS;
838 }
839 else
840#endif
841 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
842 including sign. Decimal takes the most space. This
843 isn't enough for octal. If a width is specified we
844 need more (which we allocate later). */
845 if (width < MAX_LONG_CHARS)
846 width = MAX_LONG_CHARS;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000847 n += width;
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000848 /* XXX should allow for large precision here too. */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000849 if (abuffersize < width)
850 abuffersize = width;
851 break;
852 case 's':
853 {
854 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +0000855 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000856 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
857 if (!str)
858 goto fail;
859 n += PyUnicode_GET_SIZE(str);
860 /* Remember the str and switch to the next slot */
861 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000862 break;
863 }
864 case 'U':
865 {
866 PyObject *obj = va_arg(count, PyObject *);
867 assert(obj && PyUnicode_Check(obj));
868 n += PyUnicode_GET_SIZE(obj);
869 break;
870 }
871 case 'V':
872 {
873 PyObject *obj = va_arg(count, PyObject *);
874 const char *str = va_arg(count, const char *);
Victor Stinner2b574a22011-03-01 22:48:49 +0000875 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000876 assert(obj || str);
877 assert(!obj || PyUnicode_Check(obj));
Victor Stinner2b574a22011-03-01 22:48:49 +0000878 if (obj) {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000879 n += PyUnicode_GET_SIZE(obj);
Victor Stinner2b574a22011-03-01 22:48:49 +0000880 *callresult++ = NULL;
881 }
882 else {
883 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
884 if (!str_obj)
885 goto fail;
886 n += PyUnicode_GET_SIZE(str_obj);
887 *callresult++ = str_obj;
888 }
Benjamin Peterson14339b62009-01-31 16:36:08 +0000889 break;
890 }
891 case 'S':
892 {
893 PyObject *obj = va_arg(count, PyObject *);
894 PyObject *str;
895 assert(obj);
896 str = PyObject_Str(obj);
897 if (!str)
898 goto fail;
899 n += PyUnicode_GET_SIZE(str);
900 /* Remember the str and switch to the next slot */
901 *callresult++ = str;
902 break;
903 }
904 case 'R':
905 {
906 PyObject *obj = va_arg(count, PyObject *);
907 PyObject *repr;
908 assert(obj);
909 repr = PyObject_Repr(obj);
910 if (!repr)
911 goto fail;
912 n += PyUnicode_GET_SIZE(repr);
913 /* Remember the repr and switch to the next slot */
914 *callresult++ = repr;
915 break;
916 }
917 case 'A':
918 {
919 PyObject *obj = va_arg(count, PyObject *);
920 PyObject *ascii;
921 assert(obj);
922 ascii = PyObject_ASCII(obj);
923 if (!ascii)
924 goto fail;
925 n += PyUnicode_GET_SIZE(ascii);
926 /* Remember the repr and switch to the next slot */
927 *callresult++ = ascii;
928 break;
929 }
930 case 'p':
931 (void) va_arg(count, int);
932 /* maximum 64-bit pointer representation:
933 * 0xffffffffffffffff
934 * so 19 characters is enough.
935 * XXX I count 18 -- what's the extra for?
936 */
937 n += 19;
938 break;
939 default:
940 /* if we stumble upon an unknown
941 formatting code, copy the rest of
942 the format string to the output
943 string. (we cannot just skip the
944 code, since there's no way to know
945 what's in the argument list) */
946 n += strlen(p);
947 goto expand;
948 }
949 } else
950 n++;
951 }
Benjamin Peterson29060642009-01-31 22:14:21 +0000952 expand:
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000953 if (abuffersize > ITEM_BUFFER_LEN) {
954 /* add 1 for sprintf's trailing null byte */
955 abuffer = PyObject_Malloc(abuffersize + 1);
Benjamin Peterson14339b62009-01-31 16:36:08 +0000956 if (!abuffer) {
957 PyErr_NoMemory();
958 goto fail;
959 }
960 realbuffer = abuffer;
961 }
962 else
963 realbuffer = buffer;
964 /* step 4: fill the buffer */
965 /* Since we've analyzed how much space we need for the worst case,
966 we don't have to resize the string.
967 There can be no errors beyond this point. */
968 string = PyUnicode_FromUnicode(NULL, n);
969 if (!string)
970 goto fail;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000971
Benjamin Peterson14339b62009-01-31 16:36:08 +0000972 s = PyUnicode_AS_UNICODE(string);
973 callresult = callresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000974
Benjamin Peterson14339b62009-01-31 16:36:08 +0000975 for (f = format; *f; f++) {
976 if (*f == '%') {
977 const char* p = f++;
978 int longflag = 0;
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000979 int longlongflag = 0;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000980 int size_tflag = 0;
981 zeropad = (*f == '0');
982 /* parse the width.precision part */
983 width = 0;
David Malcolm96960882010-11-05 17:23:41 +0000984 while (Py_ISDIGIT((unsigned)*f))
Benjamin Peterson14339b62009-01-31 16:36:08 +0000985 width = (width*10) + *f++ - '0';
986 precision = 0;
987 if (*f == '.') {
988 f++;
David Malcolm96960882010-11-05 17:23:41 +0000989 while (Py_ISDIGIT((unsigned)*f))
Benjamin Peterson14339b62009-01-31 16:36:08 +0000990 precision = (precision*10) + *f++ - '0';
991 }
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000992 /* Handle %ld, %lu, %lld and %llu. */
993 if (*f == 'l') {
994 if (f[1] == 'd' || f[1] == 'u') {
995 longflag = 1;
996 ++f;
997 }
998#ifdef HAVE_LONG_LONG
999 else if (f[1] == 'l' &&
1000 (f[2] == 'd' || f[2] == 'u')) {
1001 longlongflag = 1;
1002 f += 2;
1003 }
1004#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001005 }
1006 /* handle the size_t flag. */
1007 if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
1008 size_tflag = 1;
1009 ++f;
1010 }
Walter Dörwaldd2034312007-05-18 16:29:38 +00001011
Benjamin Peterson14339b62009-01-31 16:36:08 +00001012 switch (*f) {
1013 case 'c':
Victor Stinner659eb842011-02-23 12:14:22 +00001014 {
1015 int ordinal = va_arg(vargs, int);
1016#ifndef Py_UNICODE_WIDE
1017 if (ordinal > 0xffff) {
1018 ordinal -= 0x10000;
1019 *s++ = 0xD800 | (ordinal >> 10);
1020 *s++ = 0xDC00 | (ordinal & 0x3FF);
1021 } else
1022#endif
1023 *s++ = ordinal;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001024 break;
Victor Stinner659eb842011-02-23 12:14:22 +00001025 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00001026 case 'd':
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001027 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
1028 width, precision, 'd');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001029 if (longflag)
1030 sprintf(realbuffer, fmt, va_arg(vargs, long));
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001031#ifdef HAVE_LONG_LONG
1032 else if (longlongflag)
1033 sprintf(realbuffer, fmt, va_arg(vargs, PY_LONG_LONG));
1034#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001035 else if (size_tflag)
1036 sprintf(realbuffer, fmt, va_arg(vargs, Py_ssize_t));
1037 else
1038 sprintf(realbuffer, fmt, va_arg(vargs, int));
1039 appendstring(realbuffer);
1040 break;
1041 case 'u':
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001042 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
1043 width, precision, 'u');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001044 if (longflag)
1045 sprintf(realbuffer, fmt, va_arg(vargs, unsigned long));
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001046#ifdef HAVE_LONG_LONG
1047 else if (longlongflag)
1048 sprintf(realbuffer, fmt, va_arg(vargs,
1049 unsigned PY_LONG_LONG));
1050#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001051 else if (size_tflag)
1052 sprintf(realbuffer, fmt, va_arg(vargs, size_t));
1053 else
1054 sprintf(realbuffer, fmt, va_arg(vargs, unsigned int));
1055 appendstring(realbuffer);
1056 break;
1057 case 'i':
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001058 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'i');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001059 sprintf(realbuffer, fmt, va_arg(vargs, int));
1060 appendstring(realbuffer);
1061 break;
1062 case 'x':
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001063 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001064 sprintf(realbuffer, fmt, va_arg(vargs, int));
1065 appendstring(realbuffer);
1066 break;
1067 case 's':
1068 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001069 /* unused, since we already have the result */
1070 (void) va_arg(vargs, char *);
1071 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(*callresult),
1072 PyUnicode_GET_SIZE(*callresult));
1073 s += PyUnicode_GET_SIZE(*callresult);
1074 /* We're done with the unicode()/repr() => forget it */
1075 Py_DECREF(*callresult);
1076 /* switch to next unicode()/repr() result */
1077 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001078 break;
1079 }
1080 case 'U':
1081 {
1082 PyObject *obj = va_arg(vargs, PyObject *);
1083 Py_ssize_t size = PyUnicode_GET_SIZE(obj);
1084 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size);
1085 s += size;
1086 break;
1087 }
1088 case 'V':
1089 {
1090 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2b574a22011-03-01 22:48:49 +00001091 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001092 if (obj) {
1093 Py_ssize_t size = PyUnicode_GET_SIZE(obj);
1094 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size);
1095 s += size;
1096 } else {
Victor Stinner2b574a22011-03-01 22:48:49 +00001097 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(*callresult),
1098 PyUnicode_GET_SIZE(*callresult));
1099 s += PyUnicode_GET_SIZE(*callresult);
1100 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001101 }
Victor Stinner2b574a22011-03-01 22:48:49 +00001102 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001103 break;
1104 }
1105 case 'S':
1106 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00001107 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00001108 {
1109 Py_UNICODE *ucopy;
1110 Py_ssize_t usize;
1111 Py_ssize_t upos;
1112 /* unused, since we already have the result */
1113 (void) va_arg(vargs, PyObject *);
1114 ucopy = PyUnicode_AS_UNICODE(*callresult);
1115 usize = PyUnicode_GET_SIZE(*callresult);
1116 for (upos = 0; upos<usize;)
1117 *s++ = ucopy[upos++];
1118 /* We're done with the unicode()/repr() => forget it */
1119 Py_DECREF(*callresult);
1120 /* switch to next unicode()/repr() result */
1121 ++callresult;
1122 break;
1123 }
1124 case 'p':
1125 sprintf(buffer, "%p", va_arg(vargs, void*));
1126 /* %p is ill-defined: ensure leading 0x. */
1127 if (buffer[1] == 'X')
1128 buffer[1] = 'x';
1129 else if (buffer[1] != 'x') {
1130 memmove(buffer+2, buffer, strlen(buffer)+1);
1131 buffer[0] = '0';
1132 buffer[1] = 'x';
1133 }
1134 appendstring(buffer);
1135 break;
1136 case '%':
1137 *s++ = '%';
1138 break;
1139 default:
1140 appendstring(p);
1141 goto end;
1142 }
Victor Stinner1205f272010-09-11 00:54:47 +00001143 }
Victor Stinner1205f272010-09-11 00:54:47 +00001144 else
Benjamin Peterson14339b62009-01-31 16:36:08 +00001145 *s++ = *f;
1146 }
Walter Dörwaldd2034312007-05-18 16:29:38 +00001147
Benjamin Peterson29060642009-01-31 22:14:21 +00001148 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001149 if (callresults)
1150 PyObject_Free(callresults);
1151 if (abuffer)
1152 PyObject_Free(abuffer);
1153 PyUnicode_Resize(&string, s - PyUnicode_AS_UNICODE(string));
1154 return string;
Benjamin Peterson29060642009-01-31 22:14:21 +00001155 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001156 if (callresults) {
1157 PyObject **callresult2 = callresults;
1158 while (callresult2 < callresult) {
Victor Stinner2b574a22011-03-01 22:48:49 +00001159 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001160 ++callresult2;
1161 }
1162 PyObject_Free(callresults);
1163 }
1164 if (abuffer)
1165 PyObject_Free(abuffer);
1166 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001167}
1168
1169#undef appendstring
1170
1171PyObject *
1172PyUnicode_FromFormat(const char *format, ...)
1173{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001174 PyObject* ret;
1175 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001176
1177#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00001178 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001179#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00001180 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001181#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001182 ret = PyUnicode_FromFormatV(format, vargs);
1183 va_end(vargs);
1184 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001185}
1186
Victor Stinner5593d8a2010-10-02 11:11:27 +00001187/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
1188 convert a Unicode object to a wide character string.
1189
Victor Stinnerd88d9832011-09-06 02:00:05 +02001190 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00001191 character) required to convert the unicode object. Ignore size argument.
1192
Victor Stinnerd88d9832011-09-06 02:00:05 +02001193 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00001194 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02001195 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00001196static Py_ssize_t
Victor Stinner137c34c2010-09-29 10:25:54 +00001197unicode_aswidechar(PyUnicodeObject *unicode,
1198 wchar_t *w,
1199 Py_ssize_t size)
1200{
1201#if Py_UNICODE_SIZE == SIZEOF_WCHAR_T
Victor Stinner5593d8a2010-10-02 11:11:27 +00001202 Py_ssize_t res;
1203 if (w != NULL) {
1204 res = PyUnicode_GET_SIZE(unicode);
1205 if (size > res)
1206 size = res + 1;
1207 else
1208 res = size;
1209 memcpy(w, unicode->str, size * sizeof(wchar_t));
1210 return res;
1211 }
1212 else
1213 return PyUnicode_GET_SIZE(unicode) + 1;
1214#elif Py_UNICODE_SIZE == 2 && SIZEOF_WCHAR_T == 4
1215 register const Py_UNICODE *u;
1216 const Py_UNICODE *uend;
1217 const wchar_t *worig, *wend;
1218 Py_ssize_t nchar;
1219
Victor Stinner137c34c2010-09-29 10:25:54 +00001220 u = PyUnicode_AS_UNICODE(unicode);
Victor Stinner5593d8a2010-10-02 11:11:27 +00001221 uend = u + PyUnicode_GET_SIZE(unicode);
1222 if (w != NULL) {
1223 worig = w;
1224 wend = w + size;
1225 while (u != uend && w != wend) {
1226 if (0xD800 <= u[0] && u[0] <= 0xDBFF
1227 && 0xDC00 <= u[1] && u[1] <= 0xDFFF)
1228 {
1229 *w = (((u[0] & 0x3FF) << 10) | (u[1] & 0x3FF)) + 0x10000;
1230 u += 2;
1231 }
1232 else {
1233 *w = *u;
1234 u++;
1235 }
1236 w++;
1237 }
1238 if (w != wend)
1239 *w = L'\0';
1240 return w - worig;
1241 }
1242 else {
Victor Stinnerd88d9832011-09-06 02:00:05 +02001243 nchar = 1; /* null character at the end */
Victor Stinner5593d8a2010-10-02 11:11:27 +00001244 while (u != uend) {
1245 if (0xD800 <= u[0] && u[0] <= 0xDBFF
1246 && 0xDC00 <= u[1] && u[1] <= 0xDFFF)
1247 u += 2;
1248 else
1249 u++;
1250 nchar++;
1251 }
1252 }
1253 return nchar;
1254#elif Py_UNICODE_SIZE == 4 && SIZEOF_WCHAR_T == 2
1255 register Py_UNICODE *u, *uend, ordinal;
1256 register Py_ssize_t i;
1257 wchar_t *worig, *wend;
1258 Py_ssize_t nchar;
1259
1260 u = PyUnicode_AS_UNICODE(unicode);
1261 uend = u + PyUnicode_GET_SIZE(u);
1262 if (w != NULL) {
1263 worig = w;
1264 wend = w + size;
1265 while (u != uend && w != wend) {
1266 ordinal = *u;
1267 if (ordinal > 0xffff) {
1268 ordinal -= 0x10000;
1269 *w++ = 0xD800 | (ordinal >> 10);
1270 *w++ = 0xDC00 | (ordinal & 0x3FF);
1271 }
1272 else
1273 *w++ = ordinal;
1274 u++;
1275 }
1276 if (w != wend)
1277 *w = 0;
1278 return w - worig;
1279 }
1280 else {
Victor Stinnerd88d9832011-09-06 02:00:05 +02001281 nchar = 1; /* null character */
Victor Stinner5593d8a2010-10-02 11:11:27 +00001282 while (u != uend) {
1283 if (*u > 0xffff)
1284 nchar += 2;
1285 else
1286 nchar++;
1287 u++;
1288 }
1289 return nchar;
1290 }
1291#else
1292# error "unsupported wchar_t and Py_UNICODE sizes, see issue #8670"
Victor Stinner137c34c2010-09-29 10:25:54 +00001293#endif
1294}
1295
1296Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001297PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00001298 wchar_t *w,
1299 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001300{
1301 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001302 PyErr_BadInternalCall();
1303 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001304 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001305 return unicode_aswidechar((PyUnicodeObject*)unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001306}
1307
Victor Stinner137c34c2010-09-29 10:25:54 +00001308wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00001309PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00001310 Py_ssize_t *size)
1311{
1312 wchar_t* buffer;
1313 Py_ssize_t buflen;
1314
1315 if (unicode == NULL) {
1316 PyErr_BadInternalCall();
1317 return NULL;
1318 }
1319
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00001320 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, NULL, 0);
Victor Stinner5593d8a2010-10-02 11:11:27 +00001321 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00001322 PyErr_NoMemory();
1323 return NULL;
1324 }
1325
Victor Stinner137c34c2010-09-29 10:25:54 +00001326 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
1327 if (buffer == NULL) {
1328 PyErr_NoMemory();
1329 return NULL;
1330 }
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00001331 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, buffer, buflen);
Victor Stinner5593d8a2010-10-02 11:11:27 +00001332 if (size != NULL)
1333 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00001334 return buffer;
1335}
1336
Guido van Rossumd57fd912000-03-10 22:53:23 +00001337#endif
1338
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001339PyObject *PyUnicode_FromOrdinal(int ordinal)
1340{
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001341 Py_UNICODE s[2];
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001342
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001343 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001344 PyErr_SetString(PyExc_ValueError,
1345 "chr() arg not in range(0x110000)");
1346 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001347 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001348
1349#ifndef Py_UNICODE_WIDE
1350 if (ordinal > 0xffff) {
1351 ordinal -= 0x10000;
1352 s[0] = 0xD800 | (ordinal >> 10);
1353 s[1] = 0xDC00 | (ordinal & 0x3FF);
1354 return PyUnicode_FromUnicode(s, 2);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001355 }
1356#endif
1357
Hye-Shik Chang40574832004-04-06 07:24:51 +00001358 s[0] = (Py_UNICODE)ordinal;
1359 return PyUnicode_FromUnicode(s, 1);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001360}
1361
Guido van Rossumd57fd912000-03-10 22:53:23 +00001362PyObject *PyUnicode_FromObject(register PyObject *obj)
1363{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001364 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00001365 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001366 if (PyUnicode_CheckExact(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001367 Py_INCREF(obj);
1368 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001369 }
1370 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001371 /* For a Unicode subtype that's not a Unicode object,
1372 return a true Unicode object with the same data. */
1373 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(obj),
1374 PyUnicode_GET_SIZE(obj));
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001375 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001376 PyErr_Format(PyExc_TypeError,
1377 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00001378 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001379 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001380}
1381
1382PyObject *PyUnicode_FromEncodedObject(register PyObject *obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00001383 const char *encoding,
1384 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001385{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001386 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001387 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00001388
Guido van Rossumd57fd912000-03-10 22:53:23 +00001389 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001390 PyErr_BadInternalCall();
1391 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001392 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001393
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001394 /* Decoding bytes objects is the most common case and should be fast */
1395 if (PyBytes_Check(obj)) {
1396 if (PyBytes_GET_SIZE(obj) == 0) {
1397 Py_INCREF(unicode_empty);
1398 v = (PyObject *) unicode_empty;
1399 }
1400 else {
1401 v = PyUnicode_Decode(
1402 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
1403 encoding, errors);
1404 }
1405 return v;
1406 }
1407
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001408 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001409 PyErr_SetString(PyExc_TypeError,
1410 "decoding str is not supported");
1411 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001412 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001413
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001414 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
1415 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
1416 PyErr_Format(PyExc_TypeError,
1417 "coercing to str: need bytes, bytearray "
1418 "or buffer-like object, %.80s found",
1419 Py_TYPE(obj)->tp_name);
1420 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00001421 }
Tim Petersced69f82003-09-16 20:30:58 +00001422
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001423 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001424 Py_INCREF(unicode_empty);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001425 v = (PyObject *) unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001426 }
Tim Petersced69f82003-09-16 20:30:58 +00001427 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001428 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00001429
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001430 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001431 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001432}
1433
Victor Stinner600d3be2010-06-10 12:00:55 +00001434/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00001435 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
1436 1 on success. */
1437static int
1438normalize_encoding(const char *encoding,
1439 char *lower,
1440 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001441{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001442 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00001443 char *l;
1444 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001445
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001446 e = encoding;
1447 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00001448 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00001449 while (*e) {
1450 if (l == l_end)
1451 return 0;
David Malcolm96960882010-11-05 17:23:41 +00001452 if (Py_ISUPPER(*e)) {
1453 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001454 }
1455 else if (*e == '_') {
1456 *l++ = '-';
1457 e++;
1458 }
1459 else {
1460 *l++ = *e++;
1461 }
1462 }
1463 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00001464 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00001465}
1466
1467PyObject *PyUnicode_Decode(const char *s,
1468 Py_ssize_t size,
1469 const char *encoding,
1470 const char *errors)
1471{
1472 PyObject *buffer = NULL, *unicode;
1473 Py_buffer info;
1474 char lower[11]; /* Enough for any encoding shortcut */
1475
1476 if (encoding == NULL)
1477 encoding = PyUnicode_GetDefaultEncoding();
Fred Drakee4315f52000-05-09 19:53:39 +00001478
1479 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00001480 if (normalize_encoding(encoding, lower, sizeof(lower))) {
1481 if (strcmp(lower, "utf-8") == 0)
1482 return PyUnicode_DecodeUTF8(s, size, errors);
1483 else if ((strcmp(lower, "latin-1") == 0) ||
1484 (strcmp(lower, "iso-8859-1") == 0))
1485 return PyUnicode_DecodeLatin1(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001486#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Victor Stinner37296e82010-06-10 13:36:23 +00001487 else if (strcmp(lower, "mbcs") == 0)
1488 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001489#endif
Victor Stinner37296e82010-06-10 13:36:23 +00001490 else if (strcmp(lower, "ascii") == 0)
1491 return PyUnicode_DecodeASCII(s, size, errors);
1492 else if (strcmp(lower, "utf-16") == 0)
1493 return PyUnicode_DecodeUTF16(s, size, errors, 0);
1494 else if (strcmp(lower, "utf-32") == 0)
1495 return PyUnicode_DecodeUTF32(s, size, errors, 0);
1496 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001497
1498 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00001499 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00001500 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00001501 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00001502 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001503 if (buffer == NULL)
1504 goto onError;
1505 unicode = PyCodec_Decode(buffer, encoding, errors);
1506 if (unicode == NULL)
1507 goto onError;
1508 if (!PyUnicode_Check(unicode)) {
1509 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001510 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00001511 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001512 Py_DECREF(unicode);
1513 goto onError;
1514 }
1515 Py_DECREF(buffer);
1516 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00001517
Benjamin Peterson29060642009-01-31 22:14:21 +00001518 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001519 Py_XDECREF(buffer);
1520 return NULL;
1521}
1522
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001523PyObject *PyUnicode_AsDecodedObject(PyObject *unicode,
1524 const char *encoding,
1525 const char *errors)
1526{
1527 PyObject *v;
1528
1529 if (!PyUnicode_Check(unicode)) {
1530 PyErr_BadArgument();
1531 goto onError;
1532 }
1533
1534 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001535 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001536
1537 /* Decode via the codec registry */
1538 v = PyCodec_Decode(unicode, encoding, errors);
1539 if (v == NULL)
1540 goto onError;
1541 return v;
1542
Benjamin Peterson29060642009-01-31 22:14:21 +00001543 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001544 return NULL;
1545}
1546
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001547PyObject *PyUnicode_AsDecodedUnicode(PyObject *unicode,
1548 const char *encoding,
1549 const char *errors)
1550{
1551 PyObject *v;
1552
1553 if (!PyUnicode_Check(unicode)) {
1554 PyErr_BadArgument();
1555 goto onError;
1556 }
1557
1558 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001559 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001560
1561 /* Decode via the codec registry */
1562 v = PyCodec_Decode(unicode, encoding, errors);
1563 if (v == NULL)
1564 goto onError;
1565 if (!PyUnicode_Check(v)) {
1566 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001567 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001568 Py_TYPE(v)->tp_name);
1569 Py_DECREF(v);
1570 goto onError;
1571 }
1572 return v;
1573
Benjamin Peterson29060642009-01-31 22:14:21 +00001574 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001575 return NULL;
1576}
1577
Guido van Rossumd57fd912000-03-10 22:53:23 +00001578PyObject *PyUnicode_Encode(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00001579 Py_ssize_t size,
1580 const char *encoding,
1581 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001582{
1583 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00001584
Guido van Rossumd57fd912000-03-10 22:53:23 +00001585 unicode = PyUnicode_FromUnicode(s, size);
1586 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001587 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001588 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
1589 Py_DECREF(unicode);
1590 return v;
1591}
1592
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001593PyObject *PyUnicode_AsEncodedObject(PyObject *unicode,
1594 const char *encoding,
1595 const char *errors)
1596{
1597 PyObject *v;
1598
1599 if (!PyUnicode_Check(unicode)) {
1600 PyErr_BadArgument();
1601 goto onError;
1602 }
1603
1604 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001605 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001606
1607 /* Encode via the codec registry */
1608 v = PyCodec_Encode(unicode, encoding, errors);
1609 if (v == NULL)
1610 goto onError;
1611 return v;
1612
Benjamin Peterson29060642009-01-31 22:14:21 +00001613 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001614 return NULL;
1615}
1616
Victor Stinnerad158722010-10-27 00:25:46 +00001617PyObject *
1618PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00001619{
Victor Stinner313a1202010-06-11 23:56:51 +00001620#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Victor Stinnerad158722010-10-27 00:25:46 +00001621 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
1622 PyUnicode_GET_SIZE(unicode),
1623 NULL);
1624#elif defined(__APPLE__)
1625 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
1626 PyUnicode_GET_SIZE(unicode),
1627 "surrogateescape");
1628#else
Victor Stinner3cbf14b2011-04-27 00:24:21 +02001629 PyInterpreterState *interp = PyThreadState_GET()->interp;
1630 /* Bootstrap check: if the filesystem codec is implemented in Python, we
1631 cannot use it to encode and decode filenames before it is loaded. Load
1632 the Python codec requires to encode at least its own filename. Use the C
1633 version of the locale codec until the codec registry is initialized and
1634 the Python codec is loaded.
1635
1636 Py_FileSystemDefaultEncoding is shared between all interpreters, we
1637 cannot only rely on it: check also interp->fscodec_initialized for
1638 subinterpreters. */
1639 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00001640 return PyUnicode_AsEncodedString(unicode,
1641 Py_FileSystemDefaultEncoding,
1642 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00001643 }
1644 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001645 /* locale encoding with surrogateescape */
1646 wchar_t *wchar;
1647 char *bytes;
1648 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00001649 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001650
1651 wchar = PyUnicode_AsWideCharString(unicode, NULL);
1652 if (wchar == NULL)
1653 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00001654 bytes = _Py_wchar2char(wchar, &error_pos);
1655 if (bytes == NULL) {
1656 if (error_pos != (size_t)-1) {
1657 char *errmsg = strerror(errno);
1658 PyObject *exc = NULL;
1659 if (errmsg == NULL)
1660 errmsg = "Py_wchar2char() failed";
1661 raise_encode_exception(&exc,
1662 "filesystemencoding",
1663 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
1664 error_pos, error_pos+1,
1665 errmsg);
1666 Py_XDECREF(exc);
1667 }
1668 else
1669 PyErr_NoMemory();
1670 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001671 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00001672 }
1673 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001674
1675 bytes_obj = PyBytes_FromString(bytes);
1676 PyMem_Free(bytes);
1677 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00001678 }
Victor Stinnerad158722010-10-27 00:25:46 +00001679#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00001680}
1681
Guido van Rossumd57fd912000-03-10 22:53:23 +00001682PyObject *PyUnicode_AsEncodedString(PyObject *unicode,
1683 const char *encoding,
1684 const char *errors)
1685{
1686 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00001687 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00001688
Guido van Rossumd57fd912000-03-10 22:53:23 +00001689 if (!PyUnicode_Check(unicode)) {
1690 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001691 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001692 }
Fred Drakee4315f52000-05-09 19:53:39 +00001693
Tim Petersced69f82003-09-16 20:30:58 +00001694 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001695 encoding = PyUnicode_GetDefaultEncoding();
Fred Drakee4315f52000-05-09 19:53:39 +00001696
1697 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00001698 if (normalize_encoding(encoding, lower, sizeof(lower))) {
1699 if (strcmp(lower, "utf-8") == 0)
1700 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
1701 PyUnicode_GET_SIZE(unicode),
1702 errors);
1703 else if ((strcmp(lower, "latin-1") == 0) ||
1704 (strcmp(lower, "iso-8859-1") == 0))
1705 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
1706 PyUnicode_GET_SIZE(unicode),
1707 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001708#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Victor Stinner37296e82010-06-10 13:36:23 +00001709 else if (strcmp(lower, "mbcs") == 0)
1710 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
1711 PyUnicode_GET_SIZE(unicode),
1712 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001713#endif
Victor Stinner37296e82010-06-10 13:36:23 +00001714 else if (strcmp(lower, "ascii") == 0)
1715 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
1716 PyUnicode_GET_SIZE(unicode),
1717 errors);
1718 }
Victor Stinner59e62db2010-05-15 13:14:32 +00001719 /* During bootstrap, we may need to find the encodings
1720 package, to load the file system encoding, and require the
1721 file system encoding in order to load the encodings
1722 package.
Christian Heimes6a27efa2008-10-30 21:48:26 +00001723
Victor Stinner59e62db2010-05-15 13:14:32 +00001724 Break out of this dependency by assuming that the path to
1725 the encodings module is ASCII-only. XXX could try wcstombs
1726 instead, if the file system encoding is the locale's
1727 encoding. */
Victor Stinner37296e82010-06-10 13:36:23 +00001728 if (Py_FileSystemDefaultEncoding &&
Victor Stinner59e62db2010-05-15 13:14:32 +00001729 strcmp(encoding, Py_FileSystemDefaultEncoding) == 0 &&
1730 !PyThreadState_GET()->interp->codecs_initialized)
1731 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
1732 PyUnicode_GET_SIZE(unicode),
1733 errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001734
1735 /* Encode via the codec registry */
1736 v = PyCodec_Encode(unicode, encoding, errors);
1737 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001738 return NULL;
1739
1740 /* The normal path */
1741 if (PyBytes_Check(v))
1742 return v;
1743
1744 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001745 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001746 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001747 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001748
1749 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1750 "encoder %s returned bytearray instead of bytes",
1751 encoding);
1752 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001753 Py_DECREF(v);
1754 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001755 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001756
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001757 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
1758 Py_DECREF(v);
1759 return b;
1760 }
1761
1762 PyErr_Format(PyExc_TypeError,
1763 "encoder did not return a bytes object (type=%.400s)",
1764 Py_TYPE(v)->tp_name);
1765 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001766 return NULL;
1767}
1768
1769PyObject *PyUnicode_AsEncodedUnicode(PyObject *unicode,
1770 const char *encoding,
1771 const char *errors)
1772{
1773 PyObject *v;
1774
1775 if (!PyUnicode_Check(unicode)) {
1776 PyErr_BadArgument();
1777 goto onError;
1778 }
1779
1780 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001781 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001782
1783 /* Encode via the codec registry */
1784 v = PyCodec_Encode(unicode, encoding, errors);
1785 if (v == NULL)
1786 goto onError;
1787 if (!PyUnicode_Check(v)) {
1788 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001789 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001790 Py_TYPE(v)->tp_name);
1791 Py_DECREF(v);
1792 goto onError;
1793 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001794 return v;
Tim Petersced69f82003-09-16 20:30:58 +00001795
Benjamin Peterson29060642009-01-31 22:14:21 +00001796 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001797 return NULL;
1798}
1799
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001800PyObject *_PyUnicode_AsDefaultEncodedString(PyObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00001801 const char *errors)
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001802{
1803 PyObject *v = ((PyUnicodeObject *)unicode)->defenc;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001804 if (v)
1805 return v;
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001806 if (errors != NULL)
1807 Py_FatalError("non-NULL encoding in _PyUnicode_AsDefaultEncodedString");
Guido van Rossum98297ee2007-11-06 21:34:58 +00001808 v = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
Guido van Rossum06610092007-08-16 21:02:22 +00001809 PyUnicode_GET_SIZE(unicode),
1810 NULL);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001811 if (!v)
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001812 return NULL;
Guido van Rossume7a0d392007-07-12 07:53:00 +00001813 ((PyUnicodeObject *)unicode)->defenc = v;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001814 return v;
1815}
1816
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001817PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00001818PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001819 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00001820 return PyUnicode_DecodeFSDefaultAndSize(s, size);
1821}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001822
Christian Heimes5894ba72007-11-04 11:43:14 +00001823PyObject*
1824PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
1825{
Victor Stinnerad158722010-10-27 00:25:46 +00001826#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
1827 return PyUnicode_DecodeMBCS(s, size, NULL);
1828#elif defined(__APPLE__)
1829 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
1830#else
Victor Stinner3cbf14b2011-04-27 00:24:21 +02001831 PyInterpreterState *interp = PyThreadState_GET()->interp;
1832 /* Bootstrap check: if the filesystem codec is implemented in Python, we
1833 cannot use it to encode and decode filenames before it is loaded. Load
1834 the Python codec requires to encode at least its own filename. Use the C
1835 version of the locale codec until the codec registry is initialized and
1836 the Python codec is loaded.
1837
1838 Py_FileSystemDefaultEncoding is shared between all interpreters, we
1839 cannot only rely on it: check also interp->fscodec_initialized for
1840 subinterpreters. */
1841 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001842 return PyUnicode_Decode(s, size,
1843 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00001844 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001845 }
1846 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001847 /* locale encoding with surrogateescape */
1848 wchar_t *wchar;
1849 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00001850 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001851
1852 if (s[size] != '\0' || size != strlen(s)) {
1853 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
1854 return NULL;
1855 }
1856
Victor Stinner168e1172010-10-16 23:16:16 +00001857 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001858 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00001859 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001860
Victor Stinner168e1172010-10-16 23:16:16 +00001861 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001862 PyMem_Free(wchar);
1863 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001864 }
Victor Stinnerad158722010-10-27 00:25:46 +00001865#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001866}
1867
Martin v. Löwis011e8422009-05-05 04:43:17 +00001868
1869int
Antoine Pitrou13348842012-01-29 18:36:34 +01001870_PyUnicode_HasNULChars(PyObject* s)
1871{
1872 static PyObject *nul = NULL;
1873
1874 if (nul == NULL)
1875 nul = PyUnicode_FromStringAndSize("\0", 1);
1876 if (nul == NULL)
1877 return -1;
1878 return PyUnicode_Contains(s, nul);
1879}
1880
1881
1882int
Martin v. Löwis011e8422009-05-05 04:43:17 +00001883PyUnicode_FSConverter(PyObject* arg, void* addr)
1884{
1885 PyObject *output = NULL;
1886 Py_ssize_t size;
1887 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00001888 if (arg == NULL) {
1889 Py_DECREF(*(PyObject**)addr);
1890 return 1;
1891 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00001892 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00001893 output = arg;
1894 Py_INCREF(output);
1895 }
1896 else {
1897 arg = PyUnicode_FromObject(arg);
1898 if (!arg)
1899 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00001900 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00001901 Py_DECREF(arg);
1902 if (!output)
1903 return 0;
1904 if (!PyBytes_Check(output)) {
1905 Py_DECREF(output);
1906 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
1907 return 0;
1908 }
1909 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00001910 size = PyBytes_GET_SIZE(output);
1911 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00001912 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05001913 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00001914 Py_DECREF(output);
1915 return 0;
1916 }
1917 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00001918 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00001919}
1920
1921
Victor Stinner47fcb5b2010-08-13 23:59:58 +00001922int
1923PyUnicode_FSDecoder(PyObject* arg, void* addr)
1924{
1925 PyObject *output = NULL;
1926 Py_ssize_t size;
1927 void *data;
1928 if (arg == NULL) {
1929 Py_DECREF(*(PyObject**)addr);
1930 return 1;
1931 }
1932 if (PyUnicode_Check(arg)) {
1933 output = arg;
1934 Py_INCREF(output);
1935 }
1936 else {
1937 arg = PyBytes_FromObject(arg);
1938 if (!arg)
1939 return 0;
1940 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
1941 PyBytes_GET_SIZE(arg));
1942 Py_DECREF(arg);
1943 if (!output)
1944 return 0;
1945 if (!PyUnicode_Check(output)) {
1946 Py_DECREF(output);
1947 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
1948 return 0;
1949 }
1950 }
1951 size = PyUnicode_GET_SIZE(output);
1952 data = PyUnicode_AS_UNICODE(output);
1953 if (size != Py_UNICODE_strlen(data)) {
1954 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
1955 Py_DECREF(output);
1956 return 0;
1957 }
1958 *(PyObject**)addr = output;
1959 return Py_CLEANUP_SUPPORTED;
1960}
1961
1962
Martin v. Löwis5b222132007-06-10 09:51:05 +00001963char*
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001964_PyUnicode_AsStringAndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00001965{
Christian Heimesf3863112007-11-22 07:46:41 +00001966 PyObject *bytes;
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00001967 if (!PyUnicode_Check(unicode)) {
1968 PyErr_BadArgument();
1969 return NULL;
1970 }
Christian Heimesf3863112007-11-22 07:46:41 +00001971 bytes = _PyUnicode_AsDefaultEncodedString(unicode, NULL);
1972 if (bytes == NULL)
Martin v. Löwis5b222132007-06-10 09:51:05 +00001973 return NULL;
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001974 if (psize != NULL)
Christian Heimes72b710a2008-05-26 13:28:38 +00001975 *psize = PyBytes_GET_SIZE(bytes);
1976 return PyBytes_AS_STRING(bytes);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001977}
1978
1979char*
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001980_PyUnicode_AsString(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001981{
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001982 return _PyUnicode_AsStringAndSize(unicode, NULL);
Martin v. Löwis5b222132007-06-10 09:51:05 +00001983}
1984
Guido van Rossumd57fd912000-03-10 22:53:23 +00001985Py_UNICODE *PyUnicode_AsUnicode(PyObject *unicode)
1986{
1987 if (!PyUnicode_Check(unicode)) {
1988 PyErr_BadArgument();
1989 goto onError;
1990 }
1991 return PyUnicode_AS_UNICODE(unicode);
1992
Benjamin Peterson29060642009-01-31 22:14:21 +00001993 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001994 return NULL;
1995}
1996
Martin v. Löwis18e16552006-02-15 17:27:45 +00001997Py_ssize_t PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001998{
1999 if (!PyUnicode_Check(unicode)) {
2000 PyErr_BadArgument();
2001 goto onError;
2002 }
2003 return PyUnicode_GET_SIZE(unicode);
2004
Benjamin Peterson29060642009-01-31 22:14:21 +00002005 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002006 return -1;
2007}
2008
Thomas Wouters78890102000-07-22 19:25:51 +00002009const char *PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00002010{
Victor Stinner42cb4622010-09-01 19:39:01 +00002011 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00002012}
2013
Victor Stinner554f3f02010-06-16 23:33:54 +00002014/* create or adjust a UnicodeDecodeError */
2015static void
2016make_decode_exception(PyObject **exceptionObject,
2017 const char *encoding,
2018 const char *input, Py_ssize_t length,
2019 Py_ssize_t startpos, Py_ssize_t endpos,
2020 const char *reason)
2021{
2022 if (*exceptionObject == NULL) {
2023 *exceptionObject = PyUnicodeDecodeError_Create(
2024 encoding, input, length, startpos, endpos, reason);
2025 }
2026 else {
2027 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
2028 goto onError;
2029 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
2030 goto onError;
2031 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
2032 goto onError;
2033 }
2034 return;
2035
2036onError:
2037 Py_DECREF(*exceptionObject);
2038 *exceptionObject = NULL;
2039}
2040
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002041/* error handling callback helper:
2042 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00002043 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002044 and adjust various state variables.
2045 return 0 on success, -1 on error
2046*/
2047
2048static
2049int unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00002050 const char *encoding, const char *reason,
2051 const char **input, const char **inend, Py_ssize_t *startinpos,
2052 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
2053 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002054{
Benjamin Peterson142957c2008-07-04 19:55:29 +00002055 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002056
2057 PyObject *restuple = NULL;
2058 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002059 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002060 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002061 Py_ssize_t requiredsize;
2062 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002063 Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002064 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002065 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002066 int res = -1;
2067
2068 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002069 *errorHandler = PyCodec_LookupError(errors);
2070 if (*errorHandler == NULL)
2071 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002072 }
2073
Victor Stinner554f3f02010-06-16 23:33:54 +00002074 make_decode_exception(exceptionObject,
2075 encoding,
2076 *input, *inend - *input,
2077 *startinpos, *endinpos,
2078 reason);
2079 if (*exceptionObject == NULL)
2080 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002081
2082 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
2083 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002084 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002085 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00002086 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00002087 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002088 }
2089 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00002090 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002091
2092 /* Copy back the bytes variables, which might have been modified by the
2093 callback */
2094 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
2095 if (!inputobj)
2096 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00002097 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002098 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00002099 }
Christian Heimes72b710a2008-05-26 13:28:38 +00002100 *input = PyBytes_AS_STRING(inputobj);
2101 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002102 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00002103 /* we can DECREF safely, as the exception has another reference,
2104 so the object won't go away. */
2105 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002106
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002107 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00002108 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00002109 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002110 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
2111 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00002112 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002113
2114 /* need more space? (at least enough for what we
2115 have+the replacement+the rest of the string (starting
2116 at the new input position), so we won't have to check space
2117 when there are no errors in the rest of the string) */
2118 repptr = PyUnicode_AS_UNICODE(repunicode);
2119 repsize = PyUnicode_GET_SIZE(repunicode);
2120 requiredsize = *outpos + repsize + insize-newpos;
2121 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002122 if (requiredsize<2*outsize)
2123 requiredsize = 2*outsize;
2124 if (_PyUnicode_Resize(output, requiredsize) < 0)
2125 goto onError;
2126 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002127 }
2128 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002129 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002130 Py_UNICODE_COPY(*outptr, repptr, repsize);
2131 *outptr += repsize;
2132 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002133
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002134 /* we made it! */
2135 res = 0;
2136
Benjamin Peterson29060642009-01-31 22:14:21 +00002137 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002138 Py_XDECREF(restuple);
2139 return res;
2140}
2141
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002142/* --- UTF-7 Codec -------------------------------------------------------- */
2143
Antoine Pitrou244651a2009-05-04 18:56:13 +00002144/* See RFC2152 for details. We encode conservatively and decode liberally. */
2145
2146/* Three simple macros defining base-64. */
2147
2148/* Is c a base-64 character? */
2149
2150#define IS_BASE64(c) \
2151 (((c) >= 'A' && (c) <= 'Z') || \
2152 ((c) >= 'a' && (c) <= 'z') || \
2153 ((c) >= '0' && (c) <= '9') || \
2154 (c) == '+' || (c) == '/')
2155
2156/* given that c is a base-64 character, what is its base-64 value? */
2157
2158#define FROM_BASE64(c) \
2159 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
2160 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
2161 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
2162 (c) == '+' ? 62 : 63)
2163
2164/* What is the base-64 character of the bottom 6 bits of n? */
2165
2166#define TO_BASE64(n) \
2167 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
2168
2169/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
2170 * decoded as itself. We are permissive on decoding; the only ASCII
2171 * byte not decoding to itself is the + which begins a base64
2172 * string. */
2173
2174#define DECODE_DIRECT(c) \
2175 ((c) <= 127 && (c) != '+')
2176
2177/* The UTF-7 encoder treats ASCII characters differently according to
2178 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
2179 * the above). See RFC2152. This array identifies these different
2180 * sets:
2181 * 0 : "Set D"
2182 * alphanumeric and '(),-./:?
2183 * 1 : "Set O"
2184 * !"#$%&*;<=>@[]^_`{|}
2185 * 2 : "whitespace"
2186 * ht nl cr sp
2187 * 3 : special (must be base64 encoded)
2188 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
2189 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002190
Tim Petersced69f82003-09-16 20:30:58 +00002191static
Antoine Pitrou244651a2009-05-04 18:56:13 +00002192char utf7_category[128] = {
2193/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
2194 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
2195/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
2196 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2197/* sp ! " # $ % & ' ( ) * + , - . / */
2198 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
2199/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
2200 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
2201/* @ A B C D E F G H I J K L M N O */
2202 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2203/* P Q R S T U V W X Y Z [ \ ] ^ _ */
2204 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
2205/* ` a b c d e f g h i j k l m n o */
2206 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2207/* p q r s t u v w x y z { | } ~ del */
2208 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002209};
2210
Antoine Pitrou244651a2009-05-04 18:56:13 +00002211/* ENCODE_DIRECT: this character should be encoded as itself. The
2212 * answer depends on whether we are encoding set O as itself, and also
2213 * on whether we are encoding whitespace as itself. RFC2152 makes it
2214 * clear that the answers to these questions vary between
2215 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00002216
Antoine Pitrou244651a2009-05-04 18:56:13 +00002217#define ENCODE_DIRECT(c, directO, directWS) \
2218 ((c) < 128 && (c) > 0 && \
2219 ((utf7_category[(c)] == 0) || \
2220 (directWS && (utf7_category[(c)] == 2)) || \
2221 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002222
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002223PyObject *PyUnicode_DecodeUTF7(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002224 Py_ssize_t size,
2225 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002226{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002227 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
2228}
2229
Antoine Pitrou244651a2009-05-04 18:56:13 +00002230/* The decoder. The only state we preserve is our read position,
2231 * i.e. how many characters we have consumed. So if we end in the
2232 * middle of a shift sequence we have to back off the read position
2233 * and the output to the beginning of the sequence, otherwise we lose
2234 * all the shift state (seen bits, number of bits seen, high
2235 * surrogate). */
2236
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002237PyObject *PyUnicode_DecodeUTF7Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002238 Py_ssize_t size,
2239 const char *errors,
2240 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002241{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002242 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002243 Py_ssize_t startinpos;
2244 Py_ssize_t endinpos;
2245 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002246 const char *e;
2247 PyUnicodeObject *unicode;
2248 Py_UNICODE *p;
2249 const char *errmsg = "";
2250 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002251 Py_UNICODE *shiftOutStart;
2252 unsigned int base64bits = 0;
2253 unsigned long base64buffer = 0;
2254 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002255 PyObject *errorHandler = NULL;
2256 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002257
2258 unicode = _PyUnicode_New(size);
2259 if (!unicode)
2260 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002261 if (size == 0) {
2262 if (consumed)
2263 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002264 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002265 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002266
2267 p = unicode->str;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002268 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002269 e = s + size;
2270
2271 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002272 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00002273 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00002274 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002275
Antoine Pitrou244651a2009-05-04 18:56:13 +00002276 if (inShift) { /* in a base-64 section */
2277 if (IS_BASE64(ch)) { /* consume a base-64 character */
2278 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
2279 base64bits += 6;
2280 s++;
2281 if (base64bits >= 16) {
2282 /* we have enough bits for a UTF-16 value */
2283 Py_UNICODE outCh = (Py_UNICODE)
2284 (base64buffer >> (base64bits-16));
2285 base64bits -= 16;
2286 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
2287 if (surrogate) {
2288 /* expecting a second surrogate */
2289 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
2290#ifdef Py_UNICODE_WIDE
2291 *p++ = (((surrogate & 0x3FF)<<10)
2292 | (outCh & 0x3FF)) + 0x10000;
2293#else
2294 *p++ = surrogate;
2295 *p++ = outCh;
2296#endif
2297 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01002298 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002299 }
2300 else {
Antoine Pitrou5418ee02011-11-15 01:42:21 +01002301 *p++ = surrogate;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002302 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002303 }
2304 }
Antoine Pitrou5418ee02011-11-15 01:42:21 +01002305 if (outCh >= 0xD800 && outCh <= 0xDBFF) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00002306 /* first surrogate */
2307 surrogate = outCh;
2308 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002309 else {
2310 *p++ = outCh;
2311 }
2312 }
2313 }
2314 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002315 inShift = 0;
2316 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002317 if (surrogate) {
Antoine Pitrou5418ee02011-11-15 01:42:21 +01002318 *p++ = surrogate;
2319 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002320 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002321 if (base64bits > 0) { /* left-over bits */
2322 if (base64bits >= 6) {
2323 /* We've seen at least one base-64 character */
2324 errmsg = "partial character in shift sequence";
2325 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002326 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002327 else {
2328 /* Some bits remain; they should be zero */
2329 if (base64buffer != 0) {
2330 errmsg = "non-zero padding bits in shift sequence";
2331 goto utf7Error;
2332 }
2333 }
2334 }
2335 if (ch != '-') {
2336 /* '-' is absorbed; other terminating
2337 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002338 *p++ = ch;
2339 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002340 }
2341 }
2342 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002343 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002344 s++; /* consume '+' */
2345 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002346 s++;
2347 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00002348 }
2349 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002350 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002351 shiftOutStart = p;
2352 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002353 }
2354 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002355 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002356 *p++ = ch;
2357 s++;
2358 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002359 else {
2360 startinpos = s-starts;
2361 s++;
2362 errmsg = "unexpected special character";
2363 goto utf7Error;
2364 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002365 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002366utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002367 outpos = p-PyUnicode_AS_UNICODE(unicode);
2368 endinpos = s-starts;
2369 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00002370 errors, &errorHandler,
2371 "utf7", errmsg,
2372 &starts, &e, &startinpos, &endinpos, &exc, &s,
2373 &unicode, &outpos, &p))
2374 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002375 }
2376
Antoine Pitrou244651a2009-05-04 18:56:13 +00002377 /* end of string */
2378
2379 if (inShift && !consumed) { /* in shift sequence, no more to follow */
2380 /* if we're in an inconsistent state, that's an error */
2381 if (surrogate ||
2382 (base64bits >= 6) ||
2383 (base64bits > 0 && base64buffer != 0)) {
2384 outpos = p-PyUnicode_AS_UNICODE(unicode);
2385 endinpos = size;
2386 if (unicode_decode_call_errorhandler(
2387 errors, &errorHandler,
2388 "utf7", "unterminated shift sequence",
2389 &starts, &e, &startinpos, &endinpos, &exc, &s,
2390 &unicode, &outpos, &p))
2391 goto onError;
2392 if (s < e)
2393 goto restart;
2394 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002395 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002396
2397 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002398 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00002399 if (inShift) {
2400 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002401 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002402 }
2403 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002404 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002405 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002406 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002407
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00002408 if (_PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002409 goto onError;
2410
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002411 Py_XDECREF(errorHandler);
2412 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002413 return (PyObject *)unicode;
2414
Benjamin Peterson29060642009-01-31 22:14:21 +00002415 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002416 Py_XDECREF(errorHandler);
2417 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002418 Py_DECREF(unicode);
2419 return NULL;
2420}
2421
2422
2423PyObject *PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002424 Py_ssize_t size,
Antoine Pitrou244651a2009-05-04 18:56:13 +00002425 int base64SetO,
2426 int base64WhiteSpace,
Benjamin Peterson29060642009-01-31 22:14:21 +00002427 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002428{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002429 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002430 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00002431 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002432 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002433 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002434 unsigned int base64bits = 0;
2435 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002436 char * out;
2437 char * start;
2438
2439 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00002440 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002441
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00002442 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00002443 return PyErr_NoMemory();
2444
Antoine Pitrou244651a2009-05-04 18:56:13 +00002445 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002446 if (v == NULL)
2447 return NULL;
2448
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002449 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002450 for (;i < size; ++i) {
2451 Py_UNICODE ch = s[i];
2452
Antoine Pitrou244651a2009-05-04 18:56:13 +00002453 if (inShift) {
2454 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
2455 /* shifting out */
2456 if (base64bits) { /* output remaining bits */
2457 *out++ = TO_BASE64(base64buffer << (6-base64bits));
2458 base64buffer = 0;
2459 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002460 }
2461 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002462 /* Characters not in the BASE64 set implicitly unshift the sequence
2463 so no '-' is required, except if the character is itself a '-' */
2464 if (IS_BASE64(ch) || ch == '-') {
2465 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002466 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002467 *out++ = (char) ch;
2468 }
2469 else {
2470 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00002471 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002472 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002473 else { /* not in a shift sequence */
2474 if (ch == '+') {
2475 *out++ = '+';
2476 *out++ = '-';
2477 }
2478 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
2479 *out++ = (char) ch;
2480 }
2481 else {
2482 *out++ = '+';
2483 inShift = 1;
2484 goto encode_char;
2485 }
2486 }
2487 continue;
2488encode_char:
2489#ifdef Py_UNICODE_WIDE
2490 if (ch >= 0x10000) {
2491 /* code first surrogate */
2492 base64bits += 16;
2493 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
2494 while (base64bits >= 6) {
2495 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
2496 base64bits -= 6;
2497 }
2498 /* prepare second surrogate */
2499 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
2500 }
2501#endif
2502 base64bits += 16;
2503 base64buffer = (base64buffer << 16) | ch;
2504 while (base64bits >= 6) {
2505 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
2506 base64bits -= 6;
2507 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00002508 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002509 if (base64bits)
2510 *out++= TO_BASE64(base64buffer << (6-base64bits) );
2511 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002512 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002513 if (_PyBytes_Resize(&v, out - start) < 0)
2514 return NULL;
2515 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002516}
2517
Antoine Pitrou244651a2009-05-04 18:56:13 +00002518#undef IS_BASE64
2519#undef FROM_BASE64
2520#undef TO_BASE64
2521#undef DECODE_DIRECT
2522#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002523
Guido van Rossumd57fd912000-03-10 22:53:23 +00002524/* --- UTF-8 Codec -------------------------------------------------------- */
2525
Tim Petersced69f82003-09-16 20:30:58 +00002526static
Guido van Rossumd57fd912000-03-10 22:53:23 +00002527char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00002528 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
2529 illegal prefix. See RFC 3629 for details */
2530 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
2531 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002532 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00002533 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2534 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2535 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2536 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00002537 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
2538 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80-8F */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002539 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2540 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00002541 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
2542 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
2543 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
2544 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
2545 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0-F4 + F5-FF */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002546};
2547
Guido van Rossumd57fd912000-03-10 22:53:23 +00002548PyObject *PyUnicode_DecodeUTF8(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002549 Py_ssize_t size,
2550 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002551{
Walter Dörwald69652032004-09-07 20:24:22 +00002552 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
2553}
2554
Antoine Pitrouab868312009-01-10 15:40:25 +00002555/* Mask to check or force alignment of a pointer to C 'long' boundaries */
2556#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
2557
2558/* Mask to quickly check whether a C 'long' contains a
2559 non-ASCII, UTF8-encoded char. */
2560#if (SIZEOF_LONG == 8)
2561# define ASCII_CHAR_MASK 0x8080808080808080L
2562#elif (SIZEOF_LONG == 4)
2563# define ASCII_CHAR_MASK 0x80808080L
2564#else
2565# error C 'long' size should be either 4 or 8!
2566#endif
2567
Walter Dörwald69652032004-09-07 20:24:22 +00002568PyObject *PyUnicode_DecodeUTF8Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002569 Py_ssize_t size,
2570 const char *errors,
2571 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00002572{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002573 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002574 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00002575 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002576 Py_ssize_t startinpos;
2577 Py_ssize_t endinpos;
2578 Py_ssize_t outpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00002579 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002580 PyUnicodeObject *unicode;
2581 Py_UNICODE *p;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002582 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002583 PyObject *errorHandler = NULL;
2584 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002585
2586 /* Note: size will always be longer than the resulting Unicode
2587 character count */
2588 unicode = _PyUnicode_New(size);
2589 if (!unicode)
2590 return NULL;
Walter Dörwald69652032004-09-07 20:24:22 +00002591 if (size == 0) {
2592 if (consumed)
2593 *consumed = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002594 return (PyObject *)unicode;
Walter Dörwald69652032004-09-07 20:24:22 +00002595 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002596
2597 /* Unpack UTF-8 encoded data */
2598 p = unicode->str;
2599 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00002600 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002601
2602 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002603 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002604
2605 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00002606 /* Fast path for runs of ASCII characters. Given that common UTF-8
2607 input will consist of an overwhelming majority of ASCII
2608 characters, we try to optimize for this case by checking
2609 as many characters as a C 'long' can contain.
2610 First, check if we can do an aligned read, as most CPUs have
2611 a penalty for unaligned reads.
2612 */
2613 if (!((size_t) s & LONG_PTR_MASK)) {
2614 /* Help register allocation */
2615 register const char *_s = s;
2616 register Py_UNICODE *_p = p;
2617 while (_s < aligned_end) {
2618 /* Read a whole long at a time (either 4 or 8 bytes),
2619 and do a fast unrolled copy if it only contains ASCII
2620 characters. */
2621 unsigned long data = *(unsigned long *) _s;
2622 if (data & ASCII_CHAR_MASK)
2623 break;
2624 _p[0] = (unsigned char) _s[0];
2625 _p[1] = (unsigned char) _s[1];
2626 _p[2] = (unsigned char) _s[2];
2627 _p[3] = (unsigned char) _s[3];
2628#if (SIZEOF_LONG == 8)
2629 _p[4] = (unsigned char) _s[4];
2630 _p[5] = (unsigned char) _s[5];
2631 _p[6] = (unsigned char) _s[6];
2632 _p[7] = (unsigned char) _s[7];
2633#endif
2634 _s += SIZEOF_LONG;
2635 _p += SIZEOF_LONG;
2636 }
2637 s = _s;
2638 p = _p;
2639 if (s == e)
2640 break;
2641 ch = (unsigned char)*s;
2642 }
2643 }
2644
2645 if (ch < 0x80) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002646 *p++ = (Py_UNICODE)ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002647 s++;
2648 continue;
2649 }
2650
2651 n = utf8_code_length[ch];
2652
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002653 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002654 if (consumed)
2655 break;
2656 else {
2657 errmsg = "unexpected end of data";
2658 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002659 endinpos = startinpos+1;
2660 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
2661 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00002662 goto utf8Error;
2663 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002664 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002665
2666 switch (n) {
2667
2668 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00002669 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002670 startinpos = s-starts;
2671 endinpos = startinpos+1;
2672 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002673
2674 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002675 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00002676 startinpos = s-starts;
2677 endinpos = startinpos+1;
2678 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002679
2680 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002681 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00002682 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002683 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002684 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00002685 goto utf8Error;
2686 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002687 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00002688 assert ((ch > 0x007F) && (ch <= 0x07FF));
2689 *p++ = (Py_UNICODE)ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002690 break;
2691
2692 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00002693 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
2694 will result in surrogates in range d800-dfff. Surrogates are
2695 not valid UTF-8 so they are rejected.
2696 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
2697 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00002698 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00002699 (s[2] & 0xc0) != 0x80 ||
2700 ((unsigned char)s[0] == 0xE0 &&
2701 (unsigned char)s[1] < 0xA0) ||
2702 ((unsigned char)s[0] == 0xED &&
2703 (unsigned char)s[1] > 0x9F)) {
2704 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002705 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002706 endinpos = startinpos + 1;
2707
2708 /* if s[1] first two bits are 1 and 0, then the invalid
2709 continuation byte is s[2], so increment endinpos by 1,
2710 if not, s[1] is invalid and endinpos doesn't need to
2711 be incremented. */
2712 if ((s[1] & 0xC0) == 0x80)
2713 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00002714 goto utf8Error;
2715 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002716 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00002717 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
2718 *p++ = (Py_UNICODE)ch;
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002719 break;
2720
2721 case 4:
2722 if ((s[1] & 0xc0) != 0x80 ||
2723 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00002724 (s[3] & 0xc0) != 0x80 ||
2725 ((unsigned char)s[0] == 0xF0 &&
2726 (unsigned char)s[1] < 0x90) ||
2727 ((unsigned char)s[0] == 0xF4 &&
2728 (unsigned char)s[1] > 0x8F)) {
2729 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002730 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002731 endinpos = startinpos + 1;
2732 if ((s[1] & 0xC0) == 0x80) {
2733 endinpos++;
2734 if ((s[2] & 0xC0) == 0x80)
2735 endinpos++;
2736 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002737 goto utf8Error;
2738 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002739 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00002740 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
2741 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
2742
Fredrik Lundh8f455852001-06-27 18:59:43 +00002743#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00002744 *p++ = (Py_UNICODE)ch;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002745#else
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002746 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00002747
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002748 /* translate from 10000..10FFFF to 0..FFFF */
2749 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00002750
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002751 /* high surrogate = top 10 bits added to D800 */
2752 *p++ = (Py_UNICODE)(0xD800 + (ch >> 10));
Tim Petersced69f82003-09-16 20:30:58 +00002753
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002754 /* low surrogate = bottom 10 bits added to DC00 */
Fredrik Lundh45714e92001-06-26 16:39:36 +00002755 *p++ = (Py_UNICODE)(0xDC00 + (ch & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002756#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00002757 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002758 }
2759 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00002760 continue;
Tim Petersced69f82003-09-16 20:30:58 +00002761
Benjamin Peterson29060642009-01-31 22:14:21 +00002762 utf8Error:
2763 outpos = p-PyUnicode_AS_UNICODE(unicode);
2764 if (unicode_decode_call_errorhandler(
2765 errors, &errorHandler,
Victor Stinnercbe01342012-02-14 01:17:45 +01002766 "utf-8", errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00002767 &starts, &e, &startinpos, &endinpos, &exc, &s,
2768 &unicode, &outpos, &p))
2769 goto onError;
2770 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002771 }
Walter Dörwald69652032004-09-07 20:24:22 +00002772 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00002773 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002774
2775 /* Adjust length */
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00002776 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002777 goto onError;
2778
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002779 Py_XDECREF(errorHandler);
2780 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002781 return (PyObject *)unicode;
2782
Benjamin Peterson29060642009-01-31 22:14:21 +00002783 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002784 Py_XDECREF(errorHandler);
2785 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002786 Py_DECREF(unicode);
2787 return NULL;
2788}
2789
Antoine Pitrouab868312009-01-10 15:40:25 +00002790#undef ASCII_CHAR_MASK
2791
Victor Stinnerf933e1a2010-10-20 22:58:25 +00002792#ifdef __APPLE__
2793
2794/* Simplified UTF-8 decoder using surrogateescape error handler,
2795 used to decode the command line arguments on Mac OS X. */
2796
2797wchar_t*
2798_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
2799{
2800 int n;
2801 const char *e;
2802 wchar_t *unicode, *p;
2803
2804 /* Note: size will always be longer than the resulting Unicode
2805 character count */
2806 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
2807 PyErr_NoMemory();
2808 return NULL;
2809 }
2810 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
2811 if (!unicode)
2812 return NULL;
2813
2814 /* Unpack UTF-8 encoded data */
2815 p = unicode;
2816 e = s + size;
2817 while (s < e) {
2818 Py_UCS4 ch = (unsigned char)*s;
2819
2820 if (ch < 0x80) {
2821 *p++ = (wchar_t)ch;
2822 s++;
2823 continue;
2824 }
2825
2826 n = utf8_code_length[ch];
2827 if (s + n > e) {
2828 goto surrogateescape;
2829 }
2830
2831 switch (n) {
2832 case 0:
2833 case 1:
2834 goto surrogateescape;
2835
2836 case 2:
2837 if ((s[1] & 0xc0) != 0x80)
2838 goto surrogateescape;
2839 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
2840 assert ((ch > 0x007F) && (ch <= 0x07FF));
2841 *p++ = (wchar_t)ch;
2842 break;
2843
2844 case 3:
2845 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
2846 will result in surrogates in range d800-dfff. Surrogates are
2847 not valid UTF-8 so they are rejected.
2848 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
2849 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
2850 if ((s[1] & 0xc0) != 0x80 ||
2851 (s[2] & 0xc0) != 0x80 ||
2852 ((unsigned char)s[0] == 0xE0 &&
2853 (unsigned char)s[1] < 0xA0) ||
2854 ((unsigned char)s[0] == 0xED &&
2855 (unsigned char)s[1] > 0x9F)) {
2856
2857 goto surrogateescape;
2858 }
2859 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
2860 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
2861 *p++ = (Py_UNICODE)ch;
2862 break;
2863
2864 case 4:
2865 if ((s[1] & 0xc0) != 0x80 ||
2866 (s[2] & 0xc0) != 0x80 ||
2867 (s[3] & 0xc0) != 0x80 ||
2868 ((unsigned char)s[0] == 0xF0 &&
2869 (unsigned char)s[1] < 0x90) ||
2870 ((unsigned char)s[0] == 0xF4 &&
2871 (unsigned char)s[1] > 0x8F)) {
2872 goto surrogateescape;
2873 }
2874 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
2875 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
2876 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
2877
2878#if SIZEOF_WCHAR_T == 4
2879 *p++ = (wchar_t)ch;
2880#else
2881 /* compute and append the two surrogates: */
2882
2883 /* translate from 10000..10FFFF to 0..FFFF */
2884 ch -= 0x10000;
2885
2886 /* high surrogate = top 10 bits added to D800 */
2887 *p++ = (wchar_t)(0xD800 + (ch >> 10));
2888
2889 /* low surrogate = bottom 10 bits added to DC00 */
2890 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
2891#endif
2892 break;
2893 }
2894 s += n;
2895 continue;
2896
2897 surrogateescape:
2898 *p++ = 0xDC00 + ch;
2899 s++;
2900 }
2901 *p = L'\0';
2902 return unicode;
2903}
2904
2905#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00002906
Tim Peters602f7402002-04-27 18:03:26 +00002907/* Allocation strategy: if the string is short, convert into a stack buffer
2908 and allocate exactly as much space needed at the end. Else allocate the
2909 maximum possible needed (4 result bytes per Unicode character), and return
2910 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002911*/
Tim Peters7e3d9612002-04-21 03:26:37 +00002912PyObject *
2913PyUnicode_EncodeUTF8(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002914 Py_ssize_t size,
2915 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002916{
Tim Peters602f7402002-04-27 18:03:26 +00002917#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00002918
Guido van Rossum98297ee2007-11-06 21:34:58 +00002919 Py_ssize_t i; /* index into s of next input byte */
2920 PyObject *result; /* result string object */
2921 char *p; /* next free byte in output buffer */
2922 Py_ssize_t nallocated; /* number of result bytes allocated */
2923 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00002924 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002925 PyObject *errorHandler = NULL;
2926 PyObject *exc = NULL;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00002927
Tim Peters602f7402002-04-27 18:03:26 +00002928 assert(s != NULL);
2929 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002930
Tim Peters602f7402002-04-27 18:03:26 +00002931 if (size <= MAX_SHORT_UNICHARS) {
2932 /* Write into the stack buffer; nallocated can't overflow.
2933 * At the end, we'll allocate exactly as much heap space as it
2934 * turns out we need.
2935 */
2936 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002937 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00002938 p = stackbuf;
2939 }
2940 else {
2941 /* Overallocate on the heap, and give the excess back at the end. */
2942 nallocated = size * 4;
2943 if (nallocated / 4 != size) /* overflow! */
2944 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00002945 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002946 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00002947 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00002948 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00002949 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002950
Tim Peters602f7402002-04-27 18:03:26 +00002951 for (i = 0; i < size;) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002952 Py_UCS4 ch = s[i++];
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002953
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002954 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00002955 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002956 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002957
Guido van Rossumd57fd912000-03-10 22:53:23 +00002958 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00002959 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00002960 *p++ = (char)(0xc0 | (ch >> 6));
2961 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00002962 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002963#ifndef Py_UNICODE_WIDE
Victor Stinner31be90b2010-04-22 19:38:16 +00002964 /* Special case: check for high and low surrogate */
2965 if (ch <= 0xDBFF && i != size && 0xDC00 <= s[i] && s[i] <= 0xDFFF) {
2966 Py_UCS4 ch2 = s[i];
2967 /* Combine the two surrogates to form a UCS4 value */
2968 ch = ((ch - 0xD800) << 10 | (ch2 - 0xDC00)) + 0x10000;
2969 i++;
2970
2971 /* Encode UCS4 Unicode ordinals */
2972 *p++ = (char)(0xf0 | (ch >> 18));
2973 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
Tim Peters602f7402002-04-27 18:03:26 +00002974 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2975 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00002976 } else {
Victor Stinner445a6232010-04-22 20:01:57 +00002977#endif
Victor Stinner31be90b2010-04-22 19:38:16 +00002978 Py_ssize_t newpos;
2979 PyObject *rep;
2980 Py_ssize_t repsize, k;
2981 rep = unicode_encode_call_errorhandler
2982 (errors, &errorHandler, "utf-8", "surrogates not allowed",
2983 s, size, &exc, i-1, i, &newpos);
2984 if (!rep)
2985 goto error;
2986
2987 if (PyBytes_Check(rep))
2988 repsize = PyBytes_GET_SIZE(rep);
2989 else
2990 repsize = PyUnicode_GET_SIZE(rep);
2991
2992 if (repsize > 4) {
2993 Py_ssize_t offset;
2994
2995 if (result == NULL)
2996 offset = p - stackbuf;
2997 else
2998 offset = p - PyBytes_AS_STRING(result);
2999
3000 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
3001 /* integer overflow */
3002 PyErr_NoMemory();
3003 goto error;
3004 }
3005 nallocated += repsize - 4;
3006 if (result != NULL) {
3007 if (_PyBytes_Resize(&result, nallocated) < 0)
3008 goto error;
3009 } else {
3010 result = PyBytes_FromStringAndSize(NULL, nallocated);
3011 if (result == NULL)
3012 goto error;
3013 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
3014 }
3015 p = PyBytes_AS_STRING(result) + offset;
3016 }
3017
3018 if (PyBytes_Check(rep)) {
3019 char *prep = PyBytes_AS_STRING(rep);
3020 for(k = repsize; k > 0; k--)
3021 *p++ = *prep++;
3022 } else /* rep is unicode */ {
3023 Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
3024 Py_UNICODE c;
3025
3026 for(k=0; k<repsize; k++) {
3027 c = prep[k];
3028 if (0x80 <= c) {
3029 raise_encode_exception(&exc, "utf-8", s, size,
3030 i-1, i, "surrogates not allowed");
3031 goto error;
3032 }
3033 *p++ = (char)prep[k];
3034 }
3035 }
3036 Py_DECREF(rep);
Victor Stinner445a6232010-04-22 20:01:57 +00003037#ifndef Py_UNICODE_WIDE
Victor Stinner31be90b2010-04-22 19:38:16 +00003038 }
Victor Stinner445a6232010-04-22 20:01:57 +00003039#endif
Victor Stinner31be90b2010-04-22 19:38:16 +00003040 } else if (ch < 0x10000) {
3041 *p++ = (char)(0xe0 | (ch >> 12));
3042 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
3043 *p++ = (char)(0x80 | (ch & 0x3f));
3044 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00003045 /* Encode UCS4 Unicode ordinals */
3046 *p++ = (char)(0xf0 | (ch >> 18));
3047 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
3048 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
3049 *p++ = (char)(0x80 | (ch & 0x3f));
3050 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003051 }
Tim Peters0eca65c2002-04-21 17:28:06 +00003052
Guido van Rossum98297ee2007-11-06 21:34:58 +00003053 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00003054 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003055 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00003056 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00003057 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00003058 }
3059 else {
Christian Heimesf3863112007-11-22 07:46:41 +00003060 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00003061 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00003062 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00003063 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00003064 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00003065 Py_XDECREF(errorHandler);
3066 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003067 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00003068 error:
3069 Py_XDECREF(errorHandler);
3070 Py_XDECREF(exc);
3071 Py_XDECREF(result);
3072 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00003073
Tim Peters602f7402002-04-27 18:03:26 +00003074#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00003075}
3076
Guido van Rossumd57fd912000-03-10 22:53:23 +00003077PyObject *PyUnicode_AsUTF8String(PyObject *unicode)
3078{
Guido van Rossumd57fd912000-03-10 22:53:23 +00003079 if (!PyUnicode_Check(unicode)) {
3080 PyErr_BadArgument();
3081 return NULL;
3082 }
Barry Warsaw2dd4abf2000-08-18 06:58:15 +00003083 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003084 PyUnicode_GET_SIZE(unicode),
3085 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003086}
3087
Walter Dörwald41980ca2007-08-16 21:55:45 +00003088/* --- UTF-32 Codec ------------------------------------------------------- */
3089
3090PyObject *
3091PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003092 Py_ssize_t size,
3093 const char *errors,
3094 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00003095{
3096 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
3097}
3098
3099PyObject *
3100PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003101 Py_ssize_t size,
3102 const char *errors,
3103 int *byteorder,
3104 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00003105{
3106 const char *starts = s;
3107 Py_ssize_t startinpos;
3108 Py_ssize_t endinpos;
3109 Py_ssize_t outpos;
3110 PyUnicodeObject *unicode;
3111 Py_UNICODE *p;
3112#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00003113 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00003114 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003115#else
3116 const int pairs = 0;
3117#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00003118 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003119 int bo = 0; /* assume native ordering by default */
3120 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00003121 /* Offsets from q for retrieving bytes in the right order. */
3122#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3123 int iorder[] = {0, 1, 2, 3};
3124#else
3125 int iorder[] = {3, 2, 1, 0};
3126#endif
3127 PyObject *errorHandler = NULL;
3128 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00003129
Walter Dörwald41980ca2007-08-16 21:55:45 +00003130 q = (unsigned char *)s;
3131 e = q + size;
3132
3133 if (byteorder)
3134 bo = *byteorder;
3135
3136 /* Check for BOM marks (U+FEFF) in the input and adjust current
3137 byte order setting accordingly. In native mode, the leading BOM
3138 mark is skipped, in all other modes, it is copied to the output
3139 stream as-is (giving a ZWNBSP character). */
3140 if (bo == 0) {
3141 if (size >= 4) {
3142 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00003143 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00003144#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00003145 if (bom == 0x0000FEFF) {
3146 q += 4;
3147 bo = -1;
3148 }
3149 else if (bom == 0xFFFE0000) {
3150 q += 4;
3151 bo = 1;
3152 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003153#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003154 if (bom == 0x0000FEFF) {
3155 q += 4;
3156 bo = 1;
3157 }
3158 else if (bom == 0xFFFE0000) {
3159 q += 4;
3160 bo = -1;
3161 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003162#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003163 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003164 }
3165
3166 if (bo == -1) {
3167 /* force LE */
3168 iorder[0] = 0;
3169 iorder[1] = 1;
3170 iorder[2] = 2;
3171 iorder[3] = 3;
3172 }
3173 else if (bo == 1) {
3174 /* force BE */
3175 iorder[0] = 3;
3176 iorder[1] = 2;
3177 iorder[2] = 1;
3178 iorder[3] = 0;
3179 }
3180
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00003181 /* On narrow builds we split characters outside the BMP into two
3182 codepoints => count how much extra space we need. */
3183#ifndef Py_UNICODE_WIDE
3184 for (qq = q; qq < e; qq += 4)
3185 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
3186 pairs++;
3187#endif
3188
3189 /* This might be one to much, because of a BOM */
3190 unicode = _PyUnicode_New((size+3)/4+pairs);
3191 if (!unicode)
3192 return NULL;
3193 if (size == 0)
3194 return (PyObject *)unicode;
3195
3196 /* Unpack UTF-32 encoded data */
3197 p = unicode->str;
3198
Walter Dörwald41980ca2007-08-16 21:55:45 +00003199 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003200 Py_UCS4 ch;
3201 /* remaining bytes at the end? (size should be divisible by 4) */
3202 if (e-q<4) {
3203 if (consumed)
3204 break;
3205 errmsg = "truncated data";
3206 startinpos = ((const char *)q)-starts;
3207 endinpos = ((const char *)e)-starts;
3208 goto utf32Error;
3209 /* The remaining input chars are ignored if the callback
3210 chooses to skip the input */
3211 }
3212 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
3213 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00003214
Benjamin Peterson29060642009-01-31 22:14:21 +00003215 if (ch >= 0x110000)
3216 {
3217 errmsg = "codepoint not in range(0x110000)";
3218 startinpos = ((const char *)q)-starts;
3219 endinpos = startinpos+4;
3220 goto utf32Error;
3221 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003222#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003223 if (ch >= 0x10000)
3224 {
3225 *p++ = 0xD800 | ((ch-0x10000) >> 10);
3226 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
3227 }
3228 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00003229#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003230 *p++ = ch;
3231 q += 4;
3232 continue;
3233 utf32Error:
3234 outpos = p-PyUnicode_AS_UNICODE(unicode);
3235 if (unicode_decode_call_errorhandler(
3236 errors, &errorHandler,
3237 "utf32", errmsg,
3238 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
3239 &unicode, &outpos, &p))
3240 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003241 }
3242
3243 if (byteorder)
3244 *byteorder = bo;
3245
3246 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00003247 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003248
3249 /* Adjust length */
3250 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
3251 goto onError;
3252
3253 Py_XDECREF(errorHandler);
3254 Py_XDECREF(exc);
3255 return (PyObject *)unicode;
3256
Benjamin Peterson29060642009-01-31 22:14:21 +00003257 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00003258 Py_DECREF(unicode);
3259 Py_XDECREF(errorHandler);
3260 Py_XDECREF(exc);
3261 return NULL;
3262}
3263
3264PyObject *
3265PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003266 Py_ssize_t size,
3267 const char *errors,
3268 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00003269{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003270 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003271 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003272 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003273#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003274 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003275#else
3276 const int pairs = 0;
3277#endif
3278 /* Offsets from p for storing byte pairs in the right order. */
3279#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3280 int iorder[] = {0, 1, 2, 3};
3281#else
3282 int iorder[] = {3, 2, 1, 0};
3283#endif
3284
Benjamin Peterson29060642009-01-31 22:14:21 +00003285#define STORECHAR(CH) \
3286 do { \
3287 p[iorder[3]] = ((CH) >> 24) & 0xff; \
3288 p[iorder[2]] = ((CH) >> 16) & 0xff; \
3289 p[iorder[1]] = ((CH) >> 8) & 0xff; \
3290 p[iorder[0]] = (CH) & 0xff; \
3291 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00003292 } while(0)
3293
3294 /* In narrow builds we can output surrogate pairs as one codepoint,
3295 so we need less space. */
3296#ifndef Py_UNICODE_WIDE
3297 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00003298 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
3299 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
3300 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003301#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003302 nsize = (size - pairs + (byteorder == 0));
3303 bytesize = nsize * 4;
3304 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003305 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003306 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003307 if (v == NULL)
3308 return NULL;
3309
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003310 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003311 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003312 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003313 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00003314 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003315
3316 if (byteorder == -1) {
3317 /* force LE */
3318 iorder[0] = 0;
3319 iorder[1] = 1;
3320 iorder[2] = 2;
3321 iorder[3] = 3;
3322 }
3323 else if (byteorder == 1) {
3324 /* force BE */
3325 iorder[0] = 3;
3326 iorder[1] = 2;
3327 iorder[2] = 1;
3328 iorder[3] = 0;
3329 }
3330
3331 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003332 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003333#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003334 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
3335 Py_UCS4 ch2 = *s;
3336 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
3337 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
3338 s++;
3339 size--;
3340 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00003341 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003342#endif
3343 STORECHAR(ch);
3344 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003345
3346 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003347 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003348#undef STORECHAR
3349}
3350
3351PyObject *PyUnicode_AsUTF32String(PyObject *unicode)
3352{
3353 if (!PyUnicode_Check(unicode)) {
3354 PyErr_BadArgument();
3355 return NULL;
3356 }
3357 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003358 PyUnicode_GET_SIZE(unicode),
3359 NULL,
3360 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003361}
3362
Guido van Rossumd57fd912000-03-10 22:53:23 +00003363/* --- UTF-16 Codec ------------------------------------------------------- */
3364
Tim Peters772747b2001-08-09 22:21:55 +00003365PyObject *
3366PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003367 Py_ssize_t size,
3368 const char *errors,
3369 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003370{
Walter Dörwald69652032004-09-07 20:24:22 +00003371 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
3372}
3373
Antoine Pitrouab868312009-01-10 15:40:25 +00003374/* Two masks for fast checking of whether a C 'long' may contain
3375 UTF16-encoded surrogate characters. This is an efficient heuristic,
3376 assuming that non-surrogate characters with a code point >= 0x8000 are
3377 rare in most input.
3378 FAST_CHAR_MASK is used when the input is in native byte ordering,
3379 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00003380*/
Antoine Pitrouab868312009-01-10 15:40:25 +00003381#if (SIZEOF_LONG == 8)
3382# define FAST_CHAR_MASK 0x8000800080008000L
3383# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
3384#elif (SIZEOF_LONG == 4)
3385# define FAST_CHAR_MASK 0x80008000L
3386# define SWAPPED_FAST_CHAR_MASK 0x00800080L
3387#else
3388# error C 'long' size should be either 4 or 8!
3389#endif
3390
Walter Dörwald69652032004-09-07 20:24:22 +00003391PyObject *
3392PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003393 Py_ssize_t size,
3394 const char *errors,
3395 int *byteorder,
3396 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00003397{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003398 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003399 Py_ssize_t startinpos;
3400 Py_ssize_t endinpos;
3401 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003402 PyUnicodeObject *unicode;
3403 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00003404 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00003405 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00003406 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003407 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00003408 /* Offsets from q for retrieving byte pairs in the right order. */
3409#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3410 int ihi = 1, ilo = 0;
3411#else
3412 int ihi = 0, ilo = 1;
3413#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003414 PyObject *errorHandler = NULL;
3415 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003416
3417 /* Note: size will always be longer than the resulting Unicode
3418 character count */
3419 unicode = _PyUnicode_New(size);
3420 if (!unicode)
3421 return NULL;
3422 if (size == 0)
3423 return (PyObject *)unicode;
3424
3425 /* Unpack UTF-16 encoded data */
3426 p = unicode->str;
Tim Peters772747b2001-08-09 22:21:55 +00003427 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00003428 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003429
3430 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00003431 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003432
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003433 /* Check for BOM marks (U+FEFF) in the input and adjust current
3434 byte order setting accordingly. In native mode, the leading BOM
3435 mark is skipped, in all other modes, it is copied to the output
3436 stream as-is (giving a ZWNBSP character). */
3437 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00003438 if (size >= 2) {
3439 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003440#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00003441 if (bom == 0xFEFF) {
3442 q += 2;
3443 bo = -1;
3444 }
3445 else if (bom == 0xFFFE) {
3446 q += 2;
3447 bo = 1;
3448 }
Tim Petersced69f82003-09-16 20:30:58 +00003449#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003450 if (bom == 0xFEFF) {
3451 q += 2;
3452 bo = 1;
3453 }
3454 else if (bom == 0xFFFE) {
3455 q += 2;
3456 bo = -1;
3457 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003458#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003459 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003460 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003461
Tim Peters772747b2001-08-09 22:21:55 +00003462 if (bo == -1) {
3463 /* force LE */
3464 ihi = 1;
3465 ilo = 0;
3466 }
3467 else if (bo == 1) {
3468 /* force BE */
3469 ihi = 0;
3470 ilo = 1;
3471 }
Antoine Pitrouab868312009-01-10 15:40:25 +00003472#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3473 native_ordering = ilo < ihi;
3474#else
3475 native_ordering = ilo > ihi;
3476#endif
Tim Peters772747b2001-08-09 22:21:55 +00003477
Antoine Pitrouab868312009-01-10 15:40:25 +00003478 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00003479 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003480 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00003481 /* First check for possible aligned read of a C 'long'. Unaligned
3482 reads are more expensive, better to defer to another iteration. */
3483 if (!((size_t) q & LONG_PTR_MASK)) {
3484 /* Fast path for runs of non-surrogate chars. */
3485 register const unsigned char *_q = q;
3486 Py_UNICODE *_p = p;
3487 if (native_ordering) {
3488 /* Native ordering is simple: as long as the input cannot
3489 possibly contain a surrogate char, do an unrolled copy
3490 of several 16-bit code points to the target object.
3491 The non-surrogate check is done on several input bytes
3492 at a time (as many as a C 'long' can contain). */
3493 while (_q < aligned_end) {
3494 unsigned long data = * (unsigned long *) _q;
3495 if (data & FAST_CHAR_MASK)
3496 break;
3497 _p[0] = ((unsigned short *) _q)[0];
3498 _p[1] = ((unsigned short *) _q)[1];
3499#if (SIZEOF_LONG == 8)
3500 _p[2] = ((unsigned short *) _q)[2];
3501 _p[3] = ((unsigned short *) _q)[3];
3502#endif
3503 _q += SIZEOF_LONG;
3504 _p += SIZEOF_LONG / 2;
3505 }
3506 }
3507 else {
3508 /* Byteswapped ordering is similar, but we must decompose
3509 the copy bytewise, and take care of zero'ing out the
3510 upper bytes if the target object is in 32-bit units
3511 (that is, in UCS-4 builds). */
3512 while (_q < aligned_end) {
3513 unsigned long data = * (unsigned long *) _q;
3514 if (data & SWAPPED_FAST_CHAR_MASK)
3515 break;
3516 /* Zero upper bytes in UCS-4 builds */
3517#if (Py_UNICODE_SIZE > 2)
3518 _p[0] = 0;
3519 _p[1] = 0;
3520#if (SIZEOF_LONG == 8)
3521 _p[2] = 0;
3522 _p[3] = 0;
3523#endif
3524#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00003525 /* Issue #4916; UCS-4 builds on big endian machines must
3526 fill the two last bytes of each 4-byte unit. */
3527#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
3528# define OFF 2
3529#else
3530# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00003531#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00003532 ((unsigned char *) _p)[OFF + 1] = _q[0];
3533 ((unsigned char *) _p)[OFF + 0] = _q[1];
3534 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
3535 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
3536#if (SIZEOF_LONG == 8)
3537 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
3538 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
3539 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
3540 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
3541#endif
3542#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00003543 _q += SIZEOF_LONG;
3544 _p += SIZEOF_LONG / 2;
3545 }
3546 }
3547 p = _p;
3548 q = _q;
3549 if (q >= e)
3550 break;
3551 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003552 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003553
Benjamin Peterson14339b62009-01-31 16:36:08 +00003554 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00003555
3556 if (ch < 0xD800 || ch > 0xDFFF) {
3557 *p++ = ch;
3558 continue;
3559 }
3560
3561 /* UTF-16 code pair: */
3562 if (q > e) {
3563 errmsg = "unexpected end of data";
3564 startinpos = (((const char *)q) - 2) - starts;
3565 endinpos = ((const char *)e) + 1 - starts;
3566 goto utf16Error;
3567 }
3568 if (0xD800 <= ch && ch <= 0xDBFF) {
3569 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
3570 q += 2;
3571 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00003572#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003573 *p++ = ch;
3574 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003575#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003576 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003577#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003578 continue;
3579 }
3580 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003581 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00003582 startinpos = (((const char *)q)-4)-starts;
3583 endinpos = startinpos+2;
3584 goto utf16Error;
3585 }
3586
Benjamin Peterson14339b62009-01-31 16:36:08 +00003587 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003588 errmsg = "illegal encoding";
3589 startinpos = (((const char *)q)-2)-starts;
3590 endinpos = startinpos+2;
3591 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003592
Benjamin Peterson29060642009-01-31 22:14:21 +00003593 utf16Error:
3594 outpos = p - PyUnicode_AS_UNICODE(unicode);
3595 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00003596 errors,
3597 &errorHandler,
3598 "utf16", errmsg,
3599 &starts,
3600 (const char **)&e,
3601 &startinpos,
3602 &endinpos,
3603 &exc,
3604 (const char **)&q,
3605 &unicode,
3606 &outpos,
3607 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00003608 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003609 }
Antoine Pitrouab868312009-01-10 15:40:25 +00003610 /* remaining byte at the end? (size should be even) */
3611 if (e == q) {
3612 if (!consumed) {
3613 errmsg = "truncated data";
3614 startinpos = ((const char *)q) - starts;
3615 endinpos = ((const char *)e) + 1 - starts;
3616 outpos = p - PyUnicode_AS_UNICODE(unicode);
3617 if (unicode_decode_call_errorhandler(
3618 errors,
3619 &errorHandler,
3620 "utf16", errmsg,
3621 &starts,
3622 (const char **)&e,
3623 &startinpos,
3624 &endinpos,
3625 &exc,
3626 (const char **)&q,
3627 &unicode,
3628 &outpos,
3629 &p))
3630 goto onError;
3631 /* The remaining input chars are ignored if the callback
3632 chooses to skip the input */
3633 }
3634 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003635
3636 if (byteorder)
3637 *byteorder = bo;
3638
Walter Dörwald69652032004-09-07 20:24:22 +00003639 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00003640 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00003641
Guido van Rossumd57fd912000-03-10 22:53:23 +00003642 /* Adjust length */
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00003643 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003644 goto onError;
3645
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003646 Py_XDECREF(errorHandler);
3647 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003648 return (PyObject *)unicode;
3649
Benjamin Peterson29060642009-01-31 22:14:21 +00003650 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003651 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003652 Py_XDECREF(errorHandler);
3653 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003654 return NULL;
3655}
3656
Antoine Pitrouab868312009-01-10 15:40:25 +00003657#undef FAST_CHAR_MASK
3658#undef SWAPPED_FAST_CHAR_MASK
3659
Tim Peters772747b2001-08-09 22:21:55 +00003660PyObject *
3661PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003662 Py_ssize_t size,
3663 const char *errors,
3664 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003665{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003666 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00003667 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003668 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003669#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003670 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003671#else
3672 const int pairs = 0;
3673#endif
Tim Peters772747b2001-08-09 22:21:55 +00003674 /* Offsets from p for storing byte pairs in the right order. */
3675#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3676 int ihi = 1, ilo = 0;
3677#else
3678 int ihi = 0, ilo = 1;
3679#endif
3680
Benjamin Peterson29060642009-01-31 22:14:21 +00003681#define STORECHAR(CH) \
3682 do { \
3683 p[ihi] = ((CH) >> 8) & 0xff; \
3684 p[ilo] = (CH) & 0xff; \
3685 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00003686 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003687
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003688#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003689 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00003690 if (s[i] >= 0x10000)
3691 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003692#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003693 /* 2 * (size + pairs + (byteorder == 0)) */
3694 if (size > PY_SSIZE_T_MAX ||
3695 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00003696 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003697 nsize = size + pairs + (byteorder == 0);
3698 bytesize = nsize * 2;
3699 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003700 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003701 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003702 if (v == NULL)
3703 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003704
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003705 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003706 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003707 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00003708 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00003709 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00003710
3711 if (byteorder == -1) {
3712 /* force LE */
3713 ihi = 1;
3714 ilo = 0;
3715 }
3716 else if (byteorder == 1) {
3717 /* force BE */
3718 ihi = 0;
3719 ilo = 1;
3720 }
3721
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003722 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003723 Py_UNICODE ch = *s++;
3724 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003725#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003726 if (ch >= 0x10000) {
3727 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
3728 ch = 0xD800 | ((ch-0x10000) >> 10);
3729 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003730#endif
Tim Peters772747b2001-08-09 22:21:55 +00003731 STORECHAR(ch);
3732 if (ch2)
3733 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003734 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003735
3736 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003737 return v;
Tim Peters772747b2001-08-09 22:21:55 +00003738#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00003739}
3740
3741PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
3742{
3743 if (!PyUnicode_Check(unicode)) {
3744 PyErr_BadArgument();
3745 return NULL;
3746 }
3747 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003748 PyUnicode_GET_SIZE(unicode),
3749 NULL,
3750 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003751}
3752
3753/* --- Unicode Escape Codec ----------------------------------------------- */
3754
Fredrik Lundh06d12682001-01-24 07:59:11 +00003755static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00003756
Guido van Rossumd57fd912000-03-10 22:53:23 +00003757PyObject *PyUnicode_DecodeUnicodeEscape(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003758 Py_ssize_t size,
3759 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003760{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003761 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003762 Py_ssize_t startinpos;
3763 Py_ssize_t endinpos;
3764 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003765 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003766 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003767 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003768 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003769 char* message;
3770 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003771 PyObject *errorHandler = NULL;
3772 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003773
Guido van Rossumd57fd912000-03-10 22:53:23 +00003774 /* Escaped strings will always be longer than the resulting
3775 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003776 length after conversion to the true value.
3777 (but if the error callback returns a long replacement string
3778 we'll have to allocate more space) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003779 v = _PyUnicode_New(size);
3780 if (v == NULL)
3781 goto onError;
3782 if (size == 0)
3783 return (PyObject *)v;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003784
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003785 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003786 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003787
Guido van Rossumd57fd912000-03-10 22:53:23 +00003788 while (s < end) {
3789 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00003790 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003791 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003792
3793 /* Non-escape characters are interpreted as Unicode ordinals */
3794 if (*s != '\\') {
Fredrik Lundhccc74732001-02-18 22:13:49 +00003795 *p++ = (unsigned char) *s++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003796 continue;
3797 }
3798
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003799 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003800 /* \ - Escapes */
3801 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003802 c = *s++;
3803 if (s > end)
3804 c = '\0'; /* Invalid after \ */
3805 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003806
Benjamin Peterson29060642009-01-31 22:14:21 +00003807 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003808 case '\n': break;
3809 case '\\': *p++ = '\\'; break;
3810 case '\'': *p++ = '\''; break;
3811 case '\"': *p++ = '\"'; break;
3812 case 'b': *p++ = '\b'; break;
3813 case 'f': *p++ = '\014'; break; /* FF */
3814 case 't': *p++ = '\t'; break;
3815 case 'n': *p++ = '\n'; break;
3816 case 'r': *p++ = '\r'; break;
3817 case 'v': *p++ = '\013'; break; /* VT */
3818 case 'a': *p++ = '\007'; break; /* BEL, not classic C */
3819
Benjamin Peterson29060642009-01-31 22:14:21 +00003820 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003821 case '0': case '1': case '2': case '3':
3822 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003823 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003824 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003825 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003826 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003827 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00003828 }
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003829 *p++ = x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003830 break;
3831
Benjamin Peterson29060642009-01-31 22:14:21 +00003832 /* hex escapes */
3833 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003834 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003835 digits = 2;
3836 message = "truncated \\xXX escape";
3837 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003838
Benjamin Peterson29060642009-01-31 22:14:21 +00003839 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003840 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003841 digits = 4;
3842 message = "truncated \\uXXXX escape";
3843 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003844
Benjamin Peterson29060642009-01-31 22:14:21 +00003845 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00003846 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003847 digits = 8;
3848 message = "truncated \\UXXXXXXXX escape";
3849 hexescape:
3850 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003851 outpos = p-PyUnicode_AS_UNICODE(v);
3852 if (s+digits>end) {
3853 endinpos = size;
3854 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003855 errors, &errorHandler,
3856 "unicodeescape", "end of string in escape sequence",
3857 &starts, &end, &startinpos, &endinpos, &exc, &s,
3858 &v, &outpos, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003859 goto onError;
3860 goto nextByte;
3861 }
3862 for (i = 0; i < digits; ++i) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00003863 c = (unsigned char) s[i];
David Malcolm96960882010-11-05 17:23:41 +00003864 if (!Py_ISXDIGIT(c)) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003865 endinpos = (s+i+1)-starts;
3866 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003867 errors, &errorHandler,
3868 "unicodeescape", message,
3869 &starts, &end, &startinpos, &endinpos, &exc, &s,
3870 &v, &outpos, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00003871 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003872 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00003873 }
3874 chr = (chr<<4) & ~0xF;
3875 if (c >= '0' && c <= '9')
3876 chr += c - '0';
3877 else if (c >= 'a' && c <= 'f')
3878 chr += 10 + c - 'a';
3879 else
3880 chr += 10 + c - 'A';
3881 }
3882 s += i;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00003883 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003884 /* _decoding_error will have already written into the
3885 target buffer. */
3886 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003887 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00003888 /* when we get here, chr is a 32-bit unicode character */
3889 if (chr <= 0xffff)
3890 /* UCS-2 character */
3891 *p++ = (Py_UNICODE) chr;
3892 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00003893 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00003894 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00003895#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003896 *p++ = chr;
3897#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00003898 chr -= 0x10000L;
3899 *p++ = 0xD800 + (Py_UNICODE) (chr >> 10);
Fredrik Lundh45714e92001-06-26 16:39:36 +00003900 *p++ = 0xDC00 + (Py_UNICODE) (chr & 0x03FF);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003901#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00003902 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003903 endinpos = s-starts;
3904 outpos = p-PyUnicode_AS_UNICODE(v);
3905 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003906 errors, &errorHandler,
3907 "unicodeescape", "illegal Unicode character",
3908 &starts, &end, &startinpos, &endinpos, &exc, &s,
3909 &v, &outpos, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00003910 goto onError;
3911 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00003912 break;
3913
Benjamin Peterson29060642009-01-31 22:14:21 +00003914 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00003915 case 'N':
3916 message = "malformed \\N character escape";
3917 if (ucnhash_CAPI == NULL) {
3918 /* load the unicode data module */
Benjamin Petersonb173f782009-05-05 22:31:58 +00003919 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00003920 if (ucnhash_CAPI == NULL)
3921 goto ucnhashError;
3922 }
3923 if (*s == '{') {
3924 const char *start = s+1;
3925 /* look for the closing brace */
3926 while (*s != '}' && s < end)
3927 s++;
3928 if (s > start && s < end && *s == '}') {
3929 /* found a name. look it up in the unicode database */
3930 message = "unknown Unicode character name";
3931 s++;
Martin v. Löwis480f1bb2006-03-09 23:38:20 +00003932 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1), &chr))
Fredrik Lundhccc74732001-02-18 22:13:49 +00003933 goto store;
3934 }
3935 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003936 endinpos = s-starts;
3937 outpos = p-PyUnicode_AS_UNICODE(v);
3938 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003939 errors, &errorHandler,
3940 "unicodeescape", message,
3941 &starts, &end, &startinpos, &endinpos, &exc, &s,
3942 &v, &outpos, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00003943 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003944 break;
3945
3946 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00003947 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003948 message = "\\ at end of string";
3949 s--;
3950 endinpos = s-starts;
3951 outpos = p-PyUnicode_AS_UNICODE(v);
3952 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003953 errors, &errorHandler,
3954 "unicodeescape", message,
3955 &starts, &end, &startinpos, &endinpos, &exc, &s,
3956 &v, &outpos, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00003957 goto onError;
3958 }
3959 else {
3960 *p++ = '\\';
3961 *p++ = (unsigned char)s[-1];
3962 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00003963 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003964 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003965 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003966 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003967 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003968 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003969 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00003970 Py_XDECREF(errorHandler);
3971 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003972 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00003973
Benjamin Peterson29060642009-01-31 22:14:21 +00003974 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00003975 PyErr_SetString(
3976 PyExc_UnicodeError,
3977 "\\N escapes not supported (can't load unicodedata module)"
3978 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003979 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003980 Py_XDECREF(errorHandler);
3981 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00003982 return NULL;
3983
Benjamin Peterson29060642009-01-31 22:14:21 +00003984 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003985 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003986 Py_XDECREF(errorHandler);
3987 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003988 return NULL;
3989}
3990
3991/* Return a Unicode-Escape string version of the Unicode object.
3992
3993 If quotes is true, the string is enclosed in u"" or u'' quotes as
3994 appropriate.
3995
3996*/
3997
Thomas Wouters477c8d52006-05-27 19:21:47 +00003998Py_LOCAL_INLINE(const Py_UNICODE *) findchar(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003999 Py_ssize_t size,
4000 Py_UNICODE ch)
Thomas Wouters477c8d52006-05-27 19:21:47 +00004001{
4002 /* like wcschr, but doesn't stop at NULL characters */
4003
4004 while (size-- > 0) {
4005 if (*s == ch)
4006 return s;
4007 s++;
4008 }
4009
4010 return NULL;
4011}
Barry Warsaw51ac5802000-03-20 16:36:48 +00004012
Walter Dörwald79e913e2007-05-12 11:08:06 +00004013static const char *hexdigits = "0123456789abcdef";
4014
4015PyObject *PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004016 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004017{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004018 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004019 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004020
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004021#ifdef Py_UNICODE_WIDE
4022 const Py_ssize_t expandsize = 10;
4023#else
4024 const Py_ssize_t expandsize = 6;
4025#endif
4026
Thomas Wouters89f507f2006-12-13 04:49:30 +00004027 /* XXX(nnorwitz): rather than over-allocating, it would be
4028 better to choose a different scheme. Perhaps scan the
4029 first N-chars of the string and allocate based on that size.
4030 */
4031 /* Initial allocation is based on the longest-possible unichr
4032 escape.
4033
4034 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
4035 unichr, so in this case it's the longest unichr escape. In
4036 narrow (UTF-16) builds this is five chars per source unichr
4037 since there are two unichrs in the surrogate pair, so in narrow
4038 (UTF-16) builds it's not the longest unichr escape.
4039
4040 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
4041 so in the narrow (UTF-16) build case it's the longest unichr
4042 escape.
4043 */
4044
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004045 if (size == 0)
4046 return PyBytes_FromStringAndSize(NULL, 0);
4047
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004048 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00004049 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004050
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004051 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00004052 2
4053 + expandsize*size
4054 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004055 if (repr == NULL)
4056 return NULL;
4057
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004058 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004059
Guido van Rossumd57fd912000-03-10 22:53:23 +00004060 while (size-- > 0) {
4061 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004062
Walter Dörwald79e913e2007-05-12 11:08:06 +00004063 /* Escape backslashes */
4064 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004065 *p++ = '\\';
4066 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00004067 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004068 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004069
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00004070#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004071 /* Map 21-bit characters to '\U00xxxxxx' */
4072 else if (ch >= 0x10000) {
4073 *p++ = '\\';
4074 *p++ = 'U';
Walter Dörwald79e913e2007-05-12 11:08:06 +00004075 *p++ = hexdigits[(ch >> 28) & 0x0000000F];
4076 *p++ = hexdigits[(ch >> 24) & 0x0000000F];
4077 *p++ = hexdigits[(ch >> 20) & 0x0000000F];
4078 *p++ = hexdigits[(ch >> 16) & 0x0000000F];
4079 *p++ = hexdigits[(ch >> 12) & 0x0000000F];
4080 *p++ = hexdigits[(ch >> 8) & 0x0000000F];
4081 *p++ = hexdigits[(ch >> 4) & 0x0000000F];
4082 *p++ = hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00004083 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004084 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00004085#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004086 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
4087 else if (ch >= 0xD800 && ch < 0xDC00) {
4088 Py_UNICODE ch2;
4089 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00004090
Benjamin Peterson29060642009-01-31 22:14:21 +00004091 ch2 = *s++;
4092 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00004093 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004094 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
4095 *p++ = '\\';
4096 *p++ = 'U';
4097 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
4098 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
4099 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
4100 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
4101 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
4102 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
4103 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
4104 *p++ = hexdigits[ucs & 0x0000000F];
4105 continue;
4106 }
4107 /* Fall through: isolated surrogates are copied as-is */
4108 s--;
4109 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004110 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00004111#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00004112
Guido van Rossumd57fd912000-03-10 22:53:23 +00004113 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00004114 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004115 *p++ = '\\';
4116 *p++ = 'u';
Walter Dörwald79e913e2007-05-12 11:08:06 +00004117 *p++ = hexdigits[(ch >> 12) & 0x000F];
4118 *p++ = hexdigits[(ch >> 8) & 0x000F];
4119 *p++ = hexdigits[(ch >> 4) & 0x000F];
4120 *p++ = hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00004121 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004122
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00004123 /* Map special whitespace to '\t', \n', '\r' */
4124 else if (ch == '\t') {
4125 *p++ = '\\';
4126 *p++ = 't';
4127 }
4128 else if (ch == '\n') {
4129 *p++ = '\\';
4130 *p++ = 'n';
4131 }
4132 else if (ch == '\r') {
4133 *p++ = '\\';
4134 *p++ = 'r';
4135 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004136
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00004137 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00004138 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004139 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00004140 *p++ = 'x';
Walter Dörwald79e913e2007-05-12 11:08:06 +00004141 *p++ = hexdigits[(ch >> 4) & 0x000F];
4142 *p++ = hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00004143 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004144
Guido van Rossumd57fd912000-03-10 22:53:23 +00004145 /* Copy everything else as-is */
4146 else
4147 *p++ = (char) ch;
4148 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004149
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004150 assert(p - PyBytes_AS_STRING(repr) > 0);
4151 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
4152 return NULL;
4153 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004154}
4155
Alexandre Vassalotti2056bed2008-12-27 19:46:35 +00004156PyObject *PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004157{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004158 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004159 if (!PyUnicode_Check(unicode)) {
4160 PyErr_BadArgument();
4161 return NULL;
4162 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00004163 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
4164 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004165 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004166}
4167
4168/* --- Raw Unicode Escape Codec ------------------------------------------- */
4169
4170PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004171 Py_ssize_t size,
4172 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004173{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004174 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004175 Py_ssize_t startinpos;
4176 Py_ssize_t endinpos;
4177 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004178 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004179 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004180 const char *end;
4181 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004182 PyObject *errorHandler = NULL;
4183 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00004184
Guido van Rossumd57fd912000-03-10 22:53:23 +00004185 /* Escaped strings will always be longer than the resulting
4186 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004187 length after conversion to the true value. (But decoding error
4188 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004189 v = _PyUnicode_New(size);
4190 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004191 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004192 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004193 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004194 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004195 end = s + size;
4196 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004197 unsigned char c;
4198 Py_UCS4 x;
4199 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004200 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004201
Benjamin Peterson29060642009-01-31 22:14:21 +00004202 /* Non-escape characters are interpreted as Unicode ordinals */
4203 if (*s != '\\') {
4204 *p++ = (unsigned char)*s++;
4205 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004206 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004207 startinpos = s-starts;
4208
4209 /* \u-escapes are only interpreted iff the number of leading
4210 backslashes if odd */
4211 bs = s;
4212 for (;s < end;) {
4213 if (*s != '\\')
4214 break;
4215 *p++ = (unsigned char)*s++;
4216 }
4217 if (((s - bs) & 1) == 0 ||
4218 s >= end ||
4219 (*s != 'u' && *s != 'U')) {
4220 continue;
4221 }
4222 p--;
4223 count = *s=='u' ? 4 : 8;
4224 s++;
4225
4226 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
4227 outpos = p-PyUnicode_AS_UNICODE(v);
4228 for (x = 0, i = 0; i < count; ++i, ++s) {
4229 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00004230 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004231 endinpos = s-starts;
4232 if (unicode_decode_call_errorhandler(
4233 errors, &errorHandler,
4234 "rawunicodeescape", "truncated \\uXXXX",
4235 &starts, &end, &startinpos, &endinpos, &exc, &s,
4236 &v, &outpos, &p))
4237 goto onError;
4238 goto nextByte;
4239 }
4240 x = (x<<4) & ~0xF;
4241 if (c >= '0' && c <= '9')
4242 x += c - '0';
4243 else if (c >= 'a' && c <= 'f')
4244 x += 10 + c - 'a';
4245 else
4246 x += 10 + c - 'A';
4247 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00004248 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00004249 /* UCS-2 character */
4250 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004251 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004252 /* UCS-4 character. Either store directly, or as
4253 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00004254#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004255 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004256#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004257 x -= 0x10000L;
4258 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
4259 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00004260#endif
4261 } else {
4262 endinpos = s-starts;
4263 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004264 if (unicode_decode_call_errorhandler(
4265 errors, &errorHandler,
4266 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00004267 &starts, &end, &startinpos, &endinpos, &exc, &s,
4268 &v, &outpos, &p))
4269 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004270 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004271 nextByte:
4272 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004273 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004274 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004275 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004276 Py_XDECREF(errorHandler);
4277 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004278 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004279
Benjamin Peterson29060642009-01-31 22:14:21 +00004280 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004281 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004282 Py_XDECREF(errorHandler);
4283 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004284 return NULL;
4285}
4286
4287PyObject *PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004288 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004289{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004290 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004291 char *p;
4292 char *q;
4293
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004294#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004295 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004296#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004297 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004298#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00004299
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004300 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00004301 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00004302
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004303 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004304 if (repr == NULL)
4305 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00004306 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004307 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004308
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004309 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004310 while (size-- > 0) {
4311 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004312#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004313 /* Map 32-bit characters to '\Uxxxxxxxx' */
4314 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004315 *p++ = '\\';
4316 *p++ = 'U';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00004317 *p++ = hexdigits[(ch >> 28) & 0xf];
4318 *p++ = hexdigits[(ch >> 24) & 0xf];
4319 *p++ = hexdigits[(ch >> 20) & 0xf];
4320 *p++ = hexdigits[(ch >> 16) & 0xf];
4321 *p++ = hexdigits[(ch >> 12) & 0xf];
4322 *p++ = hexdigits[(ch >> 8) & 0xf];
4323 *p++ = hexdigits[(ch >> 4) & 0xf];
4324 *p++ = hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00004325 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004326 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00004327#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004328 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
4329 if (ch >= 0xD800 && ch < 0xDC00) {
4330 Py_UNICODE ch2;
4331 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004332
Benjamin Peterson29060642009-01-31 22:14:21 +00004333 ch2 = *s++;
4334 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00004335 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004336 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
4337 *p++ = '\\';
4338 *p++ = 'U';
4339 *p++ = hexdigits[(ucs >> 28) & 0xf];
4340 *p++ = hexdigits[(ucs >> 24) & 0xf];
4341 *p++ = hexdigits[(ucs >> 20) & 0xf];
4342 *p++ = hexdigits[(ucs >> 16) & 0xf];
4343 *p++ = hexdigits[(ucs >> 12) & 0xf];
4344 *p++ = hexdigits[(ucs >> 8) & 0xf];
4345 *p++ = hexdigits[(ucs >> 4) & 0xf];
4346 *p++ = hexdigits[ucs & 0xf];
4347 continue;
4348 }
4349 /* Fall through: isolated surrogates are copied as-is */
4350 s--;
4351 size++;
4352 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004353#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004354 /* Map 16-bit characters to '\uxxxx' */
4355 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004356 *p++ = '\\';
4357 *p++ = 'u';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00004358 *p++ = hexdigits[(ch >> 12) & 0xf];
4359 *p++ = hexdigits[(ch >> 8) & 0xf];
4360 *p++ = hexdigits[(ch >> 4) & 0xf];
4361 *p++ = hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00004362 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004363 /* Copy everything else as-is */
4364 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00004365 *p++ = (char) ch;
4366 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00004367 size = p - q;
4368
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004369 assert(size > 0);
4370 if (_PyBytes_Resize(&repr, size) < 0)
4371 return NULL;
4372 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004373}
4374
4375PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
4376{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004377 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004378 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00004379 PyErr_BadArgument();
4380 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004381 }
Walter Dörwald711005d2007-05-12 12:03:26 +00004382 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
4383 PyUnicode_GET_SIZE(unicode));
4384
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004385 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004386}
4387
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004388/* --- Unicode Internal Codec ------------------------------------------- */
4389
4390PyObject *_PyUnicode_DecodeUnicodeInternal(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004391 Py_ssize_t size,
4392 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004393{
4394 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004395 Py_ssize_t startinpos;
4396 Py_ssize_t endinpos;
4397 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004398 PyUnicodeObject *v;
4399 Py_UNICODE *p;
4400 const char *end;
4401 const char *reason;
4402 PyObject *errorHandler = NULL;
4403 PyObject *exc = NULL;
4404
Neal Norwitzd43069c2006-01-08 01:12:10 +00004405#ifdef Py_UNICODE_WIDE
4406 Py_UNICODE unimax = PyUnicode_GetMax();
4407#endif
4408
Thomas Wouters89f507f2006-12-13 04:49:30 +00004409 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004410 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
4411 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004412 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004413 if (PyUnicode_GetSize((PyObject *)v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004414 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004415 p = PyUnicode_AS_UNICODE(v);
4416 end = s + size;
4417
4418 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00004419 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004420 /* We have to sanity check the raw data, otherwise doom looms for
4421 some malformed UCS-4 data. */
4422 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00004423#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004424 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00004425#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004426 end-s < Py_UNICODE_SIZE
4427 )
Benjamin Peterson29060642009-01-31 22:14:21 +00004428 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004429 startinpos = s - starts;
4430 if (end-s < Py_UNICODE_SIZE) {
4431 endinpos = end-starts;
4432 reason = "truncated input";
4433 }
4434 else {
4435 endinpos = s - starts + Py_UNICODE_SIZE;
4436 reason = "illegal code point (> 0x10FFFF)";
4437 }
4438 outpos = p - PyUnicode_AS_UNICODE(v);
4439 if (unicode_decode_call_errorhandler(
4440 errors, &errorHandler,
4441 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00004442 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00004443 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004444 goto onError;
4445 }
4446 }
4447 else {
4448 p++;
4449 s += Py_UNICODE_SIZE;
4450 }
4451 }
4452
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004453 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004454 goto onError;
4455 Py_XDECREF(errorHandler);
4456 Py_XDECREF(exc);
4457 return (PyObject *)v;
4458
Benjamin Peterson29060642009-01-31 22:14:21 +00004459 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004460 Py_XDECREF(v);
4461 Py_XDECREF(errorHandler);
4462 Py_XDECREF(exc);
4463 return NULL;
4464}
4465
Guido van Rossumd57fd912000-03-10 22:53:23 +00004466/* --- Latin-1 Codec ------------------------------------------------------ */
4467
4468PyObject *PyUnicode_DecodeLatin1(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004469 Py_ssize_t size,
4470 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004471{
4472 PyUnicodeObject *v;
4473 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00004474 const char *e, *unrolled_end;
Tim Petersced69f82003-09-16 20:30:58 +00004475
Guido van Rossumd57fd912000-03-10 22:53:23 +00004476 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004477 if (size == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004478 Py_UNICODE r = *(unsigned char*)s;
4479 return PyUnicode_FromUnicode(&r, 1);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004480 }
4481
Guido van Rossumd57fd912000-03-10 22:53:23 +00004482 v = _PyUnicode_New(size);
4483 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004484 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004485 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004486 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004487 p = PyUnicode_AS_UNICODE(v);
Antoine Pitrouab868312009-01-10 15:40:25 +00004488 e = s + size;
4489 /* Unrolling the copy makes it much faster by reducing the looping
4490 overhead. This is similar to what many memcpy() implementations do. */
4491 unrolled_end = e - 4;
4492 while (s < unrolled_end) {
4493 p[0] = (unsigned char) s[0];
4494 p[1] = (unsigned char) s[1];
4495 p[2] = (unsigned char) s[2];
4496 p[3] = (unsigned char) s[3];
4497 s += 4;
4498 p += 4;
4499 }
4500 while (s < e)
4501 *p++ = (unsigned char) *s++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004502 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004503
Benjamin Peterson29060642009-01-31 22:14:21 +00004504 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004505 Py_XDECREF(v);
4506 return NULL;
4507}
4508
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004509/* create or adjust a UnicodeEncodeError */
4510static void make_encode_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004511 const char *encoding,
4512 const Py_UNICODE *unicode, Py_ssize_t size,
4513 Py_ssize_t startpos, Py_ssize_t endpos,
4514 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004515{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004516 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004517 *exceptionObject = PyUnicodeEncodeError_Create(
4518 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004519 }
4520 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004521 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
4522 goto onError;
4523 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
4524 goto onError;
4525 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
4526 goto onError;
4527 return;
4528 onError:
4529 Py_DECREF(*exceptionObject);
4530 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004531 }
4532}
4533
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004534/* raises a UnicodeEncodeError */
4535static void raise_encode_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004536 const char *encoding,
4537 const Py_UNICODE *unicode, Py_ssize_t size,
4538 Py_ssize_t startpos, Py_ssize_t endpos,
4539 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004540{
4541 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004542 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004543 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004544 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004545}
4546
4547/* error handling callback helper:
4548 build arguments, call the callback and check the arguments,
4549 put the result into newpos and return the replacement string, which
4550 has to be freed by the caller */
4551static PyObject *unicode_encode_call_errorhandler(const char *errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00004552 PyObject **errorHandler,
4553 const char *encoding, const char *reason,
4554 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
4555 Py_ssize_t startpos, Py_ssize_t endpos,
4556 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004557{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004558 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004559
4560 PyObject *restuple;
4561 PyObject *resunicode;
4562
4563 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004564 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004565 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004566 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004567 }
4568
4569 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004570 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004571 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004572 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004573
4574 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00004575 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004576 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004577 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004578 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004579 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004580 Py_DECREF(restuple);
4581 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004582 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004583 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00004584 &resunicode, newpos)) {
4585 Py_DECREF(restuple);
4586 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004587 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004588 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
4589 PyErr_SetString(PyExc_TypeError, &argparse[3]);
4590 Py_DECREF(restuple);
4591 return NULL;
4592 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004593 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004594 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004595 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004596 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
4597 Py_DECREF(restuple);
4598 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004599 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004600 Py_INCREF(resunicode);
4601 Py_DECREF(restuple);
4602 return resunicode;
4603}
4604
4605static PyObject *unicode_encode_ucs1(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004606 Py_ssize_t size,
4607 const char *errors,
4608 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004609{
4610 /* output object */
4611 PyObject *res;
4612 /* pointers to the beginning and end+1 of input */
4613 const Py_UNICODE *startp = p;
4614 const Py_UNICODE *endp = p + size;
4615 /* pointer to the beginning of the unencodable characters */
4616 /* const Py_UNICODE *badp = NULL; */
4617 /* pointer into the output */
4618 char *str;
4619 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00004620 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004621 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
4622 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004623 PyObject *errorHandler = NULL;
4624 PyObject *exc = NULL;
4625 /* the following variable is used for caching string comparisons
4626 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
4627 int known_errorHandler = -1;
4628
4629 /* allocate enough for a simple encoding without
4630 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00004631 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00004632 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004633 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004634 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00004635 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004636 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004637 ressize = size;
4638
4639 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004640 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004641
Benjamin Peterson29060642009-01-31 22:14:21 +00004642 /* can we encode this? */
4643 if (c<limit) {
4644 /* no overflow check, because we know that the space is enough */
4645 *str++ = (char)c;
4646 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004647 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004648 else {
4649 Py_ssize_t unicodepos = p-startp;
4650 Py_ssize_t requiredsize;
4651 PyObject *repunicode;
4652 Py_ssize_t repsize;
4653 Py_ssize_t newpos;
4654 Py_ssize_t respos;
4655 Py_UNICODE *uni2;
4656 /* startpos for collecting unencodable chars */
4657 const Py_UNICODE *collstart = p;
4658 const Py_UNICODE *collend = p;
4659 /* find all unecodable characters */
4660 while ((collend < endp) && ((*collend)>=limit))
4661 ++collend;
4662 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
4663 if (known_errorHandler==-1) {
4664 if ((errors==NULL) || (!strcmp(errors, "strict")))
4665 known_errorHandler = 1;
4666 else if (!strcmp(errors, "replace"))
4667 known_errorHandler = 2;
4668 else if (!strcmp(errors, "ignore"))
4669 known_errorHandler = 3;
4670 else if (!strcmp(errors, "xmlcharrefreplace"))
4671 known_errorHandler = 4;
4672 else
4673 known_errorHandler = 0;
4674 }
4675 switch (known_errorHandler) {
4676 case 1: /* strict */
4677 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
4678 goto onError;
4679 case 2: /* replace */
4680 while (collstart++<collend)
4681 *str++ = '?'; /* fall through */
4682 case 3: /* ignore */
4683 p = collend;
4684 break;
4685 case 4: /* xmlcharrefreplace */
4686 respos = str - PyBytes_AS_STRING(res);
4687 /* determine replacement size (temporarily (mis)uses p) */
4688 for (p = collstart, repsize = 0; p < collend; ++p) {
4689 if (*p<10)
4690 repsize += 2+1+1;
4691 else if (*p<100)
4692 repsize += 2+2+1;
4693 else if (*p<1000)
4694 repsize += 2+3+1;
4695 else if (*p<10000)
4696 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00004697#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004698 else
4699 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00004700#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004701 else if (*p<100000)
4702 repsize += 2+5+1;
4703 else if (*p<1000000)
4704 repsize += 2+6+1;
4705 else
4706 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004707#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004708 }
4709 requiredsize = respos+repsize+(endp-collend);
4710 if (requiredsize > ressize) {
4711 if (requiredsize<2*ressize)
4712 requiredsize = 2*ressize;
4713 if (_PyBytes_Resize(&res, requiredsize))
4714 goto onError;
4715 str = PyBytes_AS_STRING(res) + respos;
4716 ressize = requiredsize;
4717 }
4718 /* generate replacement (temporarily (mis)uses p) */
4719 for (p = collstart; p < collend; ++p) {
4720 str += sprintf(str, "&#%d;", (int)*p);
4721 }
4722 p = collend;
4723 break;
4724 default:
4725 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
4726 encoding, reason, startp, size, &exc,
4727 collstart-startp, collend-startp, &newpos);
4728 if (repunicode == NULL)
4729 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004730 if (PyBytes_Check(repunicode)) {
4731 /* Directly copy bytes result to output. */
4732 repsize = PyBytes_Size(repunicode);
4733 if (repsize > 1) {
4734 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00004735 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00004736 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
4737 Py_DECREF(repunicode);
4738 goto onError;
4739 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00004740 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004741 ressize += repsize-1;
4742 }
4743 memcpy(str, PyBytes_AsString(repunicode), repsize);
4744 str += repsize;
4745 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004746 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00004747 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004748 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004749 /* need more space? (at least enough for what we
4750 have+the replacement+the rest of the string, so
4751 we won't have to check space for encodable characters) */
4752 respos = str - PyBytes_AS_STRING(res);
4753 repsize = PyUnicode_GET_SIZE(repunicode);
4754 requiredsize = respos+repsize+(endp-collend);
4755 if (requiredsize > ressize) {
4756 if (requiredsize<2*ressize)
4757 requiredsize = 2*ressize;
4758 if (_PyBytes_Resize(&res, requiredsize)) {
4759 Py_DECREF(repunicode);
4760 goto onError;
4761 }
4762 str = PyBytes_AS_STRING(res) + respos;
4763 ressize = requiredsize;
4764 }
4765 /* check if there is anything unencodable in the replacement
4766 and copy it to the output */
4767 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
4768 c = *uni2;
4769 if (c >= limit) {
4770 raise_encode_exception(&exc, encoding, startp, size,
4771 unicodepos, unicodepos+1, reason);
4772 Py_DECREF(repunicode);
4773 goto onError;
4774 }
4775 *str = (char)c;
4776 }
4777 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004778 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00004779 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004780 }
4781 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004782 /* Resize if we allocated to much */
4783 size = str - PyBytes_AS_STRING(res);
4784 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00004785 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004786 if (_PyBytes_Resize(&res, size) < 0)
4787 goto onError;
4788 }
4789
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004790 Py_XDECREF(errorHandler);
4791 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004792 return res;
4793
4794 onError:
4795 Py_XDECREF(res);
4796 Py_XDECREF(errorHandler);
4797 Py_XDECREF(exc);
4798 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004799}
4800
Guido van Rossumd57fd912000-03-10 22:53:23 +00004801PyObject *PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004802 Py_ssize_t size,
4803 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004804{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004805 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004806}
4807
4808PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
4809{
4810 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004811 PyErr_BadArgument();
4812 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004813 }
4814 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004815 PyUnicode_GET_SIZE(unicode),
4816 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004817}
4818
4819/* --- 7-bit ASCII Codec -------------------------------------------------- */
4820
Guido van Rossumd57fd912000-03-10 22:53:23 +00004821PyObject *PyUnicode_DecodeASCII(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004822 Py_ssize_t size,
4823 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004824{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004825 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004826 PyUnicodeObject *v;
4827 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004828 Py_ssize_t startinpos;
4829 Py_ssize_t endinpos;
4830 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004831 const char *e;
4832 PyObject *errorHandler = NULL;
4833 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00004834
Guido van Rossumd57fd912000-03-10 22:53:23 +00004835 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004836 if (size == 1 && *(unsigned char*)s < 128) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004837 Py_UNICODE r = *(unsigned char*)s;
4838 return PyUnicode_FromUnicode(&r, 1);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004839 }
Tim Petersced69f82003-09-16 20:30:58 +00004840
Guido van Rossumd57fd912000-03-10 22:53:23 +00004841 v = _PyUnicode_New(size);
4842 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004843 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004844 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004845 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004846 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004847 e = s + size;
4848 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004849 register unsigned char c = (unsigned char)*s;
4850 if (c < 128) {
4851 *p++ = c;
4852 ++s;
4853 }
4854 else {
4855 startinpos = s-starts;
4856 endinpos = startinpos + 1;
4857 outpos = p - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
4858 if (unicode_decode_call_errorhandler(
4859 errors, &errorHandler,
4860 "ascii", "ordinal not in range(128)",
4861 &starts, &e, &startinpos, &endinpos, &exc, &s,
4862 &v, &outpos, &p))
4863 goto onError;
4864 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004865 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00004866 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00004867 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
4868 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004869 Py_XDECREF(errorHandler);
4870 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004871 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004872
Benjamin Peterson29060642009-01-31 22:14:21 +00004873 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004874 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004875 Py_XDECREF(errorHandler);
4876 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004877 return NULL;
4878}
4879
Guido van Rossumd57fd912000-03-10 22:53:23 +00004880PyObject *PyUnicode_EncodeASCII(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004881 Py_ssize_t size,
4882 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004883{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004884 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004885}
4886
4887PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
4888{
4889 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004890 PyErr_BadArgument();
4891 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004892 }
4893 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004894 PyUnicode_GET_SIZE(unicode),
4895 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004896}
4897
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004898#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004899
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004900/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004901
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00004902#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004903#define NEED_RETRY
4904#endif
4905
4906/* XXX This code is limited to "true" double-byte encodings, as
4907 a) it assumes an incomplete character consists of a single byte, and
4908 b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
Benjamin Peterson29060642009-01-31 22:14:21 +00004909 encodings, see IsDBCSLeadByteEx documentation. */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004910
4911static int is_dbcs_lead_byte(const char *s, int offset)
4912{
4913 const char *curr = s + offset;
4914
4915 if (IsDBCSLeadByte(*curr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004916 const char *prev = CharPrev(s, curr);
4917 return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004918 }
4919 return 0;
4920}
4921
4922/*
4923 * Decode MBCS string into unicode object. If 'final' is set, converts
4924 * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
4925 */
4926static int decode_mbcs(PyUnicodeObject **v,
Benjamin Peterson29060642009-01-31 22:14:21 +00004927 const char *s, /* MBCS string */
4928 int size, /* sizeof MBCS string */
Victor Stinner554f3f02010-06-16 23:33:54 +00004929 int final,
4930 const char *errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004931{
4932 Py_UNICODE *p;
Victor Stinner554f3f02010-06-16 23:33:54 +00004933 Py_ssize_t n;
4934 DWORD usize;
4935 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004936
4937 assert(size >= 0);
4938
Victor Stinner554f3f02010-06-16 23:33:54 +00004939 /* check and handle 'errors' arg */
4940 if (errors==NULL || strcmp(errors, "strict")==0)
4941 flags = MB_ERR_INVALID_CHARS;
4942 else if (strcmp(errors, "ignore")==0)
4943 flags = 0;
4944 else {
4945 PyErr_Format(PyExc_ValueError,
4946 "mbcs encoding does not support errors='%s'",
4947 errors);
4948 return -1;
4949 }
4950
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004951 /* Skip trailing lead-byte unless 'final' is set */
4952 if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
Benjamin Peterson29060642009-01-31 22:14:21 +00004953 --size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004954
4955 /* First get the size of the result */
4956 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00004957 usize = MultiByteToWideChar(CP_ACP, flags, s, size, NULL, 0);
4958 if (usize==0)
4959 goto mbcs_decode_error;
4960 } else
4961 usize = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004962
4963 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004964 /* Create unicode object */
4965 *v = _PyUnicode_New(usize);
4966 if (*v == NULL)
4967 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00004968 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004969 }
4970 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004971 /* Extend unicode object */
4972 n = PyUnicode_GET_SIZE(*v);
4973 if (_PyUnicode_Resize(v, n + usize) < 0)
4974 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004975 }
4976
4977 /* Do the conversion */
Victor Stinner554f3f02010-06-16 23:33:54 +00004978 if (usize > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004979 p = PyUnicode_AS_UNICODE(*v) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00004980 if (0 == MultiByteToWideChar(CP_ACP, flags, s, size, p, usize)) {
4981 goto mbcs_decode_error;
Benjamin Peterson29060642009-01-31 22:14:21 +00004982 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004983 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004984 return size;
Victor Stinner554f3f02010-06-16 23:33:54 +00004985
4986mbcs_decode_error:
4987 /* If the last error was ERROR_NO_UNICODE_TRANSLATION, then
4988 we raise a UnicodeDecodeError - else it is a 'generic'
4989 windows error
4990 */
4991 if (GetLastError()==ERROR_NO_UNICODE_TRANSLATION) {
4992 /* Ideally, we should get reason from FormatMessage - this
4993 is the Windows 2000 English version of the message
4994 */
4995 PyObject *exc = NULL;
4996 const char *reason = "No mapping for the Unicode character exists "
4997 "in the target multi-byte code page.";
4998 make_decode_exception(&exc, "mbcs", s, size, 0, 0, reason);
4999 if (exc != NULL) {
5000 PyCodec_StrictErrors(exc);
5001 Py_DECREF(exc);
5002 }
5003 } else {
5004 PyErr_SetFromWindowsErrWithFilename(0, NULL);
5005 }
5006 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005007}
5008
5009PyObject *PyUnicode_DecodeMBCSStateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005010 Py_ssize_t size,
5011 const char *errors,
5012 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005013{
5014 PyUnicodeObject *v = NULL;
5015 int done;
5016
5017 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005018 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005019
5020#ifdef NEED_RETRY
5021 retry:
5022 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00005023 done = decode_mbcs(&v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005024 else
5025#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00005026 done = decode_mbcs(&v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005027
5028 if (done < 0) {
5029 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00005030 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005031 }
5032
5033 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005034 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005035
5036#ifdef NEED_RETRY
5037 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005038 s += done;
5039 size -= done;
5040 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005041 }
5042#endif
5043
5044 return (PyObject *)v;
5045}
5046
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005047PyObject *PyUnicode_DecodeMBCS(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005048 Py_ssize_t size,
5049 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005050{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005051 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
5052}
5053
5054/*
5055 * Convert unicode into string object (MBCS).
5056 * Returns 0 if succeed, -1 otherwise.
5057 */
5058static int encode_mbcs(PyObject **repr,
Benjamin Peterson29060642009-01-31 22:14:21 +00005059 const Py_UNICODE *p, /* unicode */
Victor Stinner554f3f02010-06-16 23:33:54 +00005060 int size, /* size of unicode */
5061 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005062{
Victor Stinner554f3f02010-06-16 23:33:54 +00005063 BOOL usedDefaultChar = FALSE;
5064 BOOL *pusedDefaultChar;
5065 int mbcssize;
5066 Py_ssize_t n;
5067 PyObject *exc = NULL;
5068 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005069
5070 assert(size >= 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005071
Victor Stinner554f3f02010-06-16 23:33:54 +00005072 /* check and handle 'errors' arg */
5073 if (errors==NULL || strcmp(errors, "strict")==0) {
5074 flags = WC_NO_BEST_FIT_CHARS;
5075 pusedDefaultChar = &usedDefaultChar;
5076 } else if (strcmp(errors, "replace")==0) {
5077 flags = 0;
5078 pusedDefaultChar = NULL;
5079 } else {
5080 PyErr_Format(PyExc_ValueError,
5081 "mbcs encoding does not support errors='%s'",
5082 errors);
5083 return -1;
5084 }
5085
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005086 /* First get the size of the result */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005087 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00005088 mbcssize = WideCharToMultiByte(CP_ACP, flags, p, size, NULL, 0,
5089 NULL, pusedDefaultChar);
Benjamin Peterson29060642009-01-31 22:14:21 +00005090 if (mbcssize == 0) {
5091 PyErr_SetFromWindowsErrWithFilename(0, NULL);
5092 return -1;
5093 }
Victor Stinner554f3f02010-06-16 23:33:54 +00005094 /* If we used a default char, then we failed! */
5095 if (pusedDefaultChar && *pusedDefaultChar)
5096 goto mbcs_encode_error;
5097 } else {
5098 mbcssize = 0;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005099 }
5100
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005101 if (*repr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005102 /* Create string object */
5103 *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
5104 if (*repr == NULL)
5105 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00005106 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005107 }
5108 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005109 /* Extend string object */
5110 n = PyBytes_Size(*repr);
5111 if (_PyBytes_Resize(repr, n + mbcssize) < 0)
5112 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005113 }
5114
5115 /* Do the conversion */
5116 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005117 char *s = PyBytes_AS_STRING(*repr) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00005118 if (0 == WideCharToMultiByte(CP_ACP, flags, p, size, s, mbcssize,
5119 NULL, pusedDefaultChar)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005120 PyErr_SetFromWindowsErrWithFilename(0, NULL);
5121 return -1;
5122 }
Victor Stinner554f3f02010-06-16 23:33:54 +00005123 if (pusedDefaultChar && *pusedDefaultChar)
5124 goto mbcs_encode_error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005125 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005126 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00005127
5128mbcs_encode_error:
5129 raise_encode_exception(&exc, "mbcs", p, size, 0, 0, "invalid character");
5130 Py_XDECREF(exc);
5131 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005132}
5133
5134PyObject *PyUnicode_EncodeMBCS(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00005135 Py_ssize_t size,
5136 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005137{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005138 PyObject *repr = NULL;
5139 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00005140
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005141#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00005142 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005143 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00005144 ret = encode_mbcs(&repr, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005145 else
5146#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00005147 ret = encode_mbcs(&repr, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005148
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005149 if (ret < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005150 Py_XDECREF(repr);
5151 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005152 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005153
5154#ifdef NEED_RETRY
5155 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005156 p += INT_MAX;
5157 size -= INT_MAX;
5158 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005159 }
5160#endif
5161
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005162 return repr;
5163}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00005164
Mark Hammond0ccda1e2003-07-01 00:13:27 +00005165PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
5166{
5167 if (!PyUnicode_Check(unicode)) {
5168 PyErr_BadArgument();
5169 return NULL;
5170 }
5171 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005172 PyUnicode_GET_SIZE(unicode),
5173 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00005174}
5175
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005176#undef NEED_RETRY
5177
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00005178#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005179
Guido van Rossumd57fd912000-03-10 22:53:23 +00005180/* --- Character Mapping Codec -------------------------------------------- */
5181
Guido van Rossumd57fd912000-03-10 22:53:23 +00005182PyObject *PyUnicode_DecodeCharmap(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005183 Py_ssize_t size,
5184 PyObject *mapping,
5185 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005186{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005187 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005188 Py_ssize_t startinpos;
5189 Py_ssize_t endinpos;
5190 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005191 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005192 PyUnicodeObject *v;
5193 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005194 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005195 PyObject *errorHandler = NULL;
5196 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005197 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005198 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00005199
Guido van Rossumd57fd912000-03-10 22:53:23 +00005200 /* Default to Latin-1 */
5201 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005202 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005203
5204 v = _PyUnicode_New(size);
5205 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005206 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005207 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005208 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005209 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005210 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005211 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005212 mapstring = PyUnicode_AS_UNICODE(mapping);
5213 maplen = PyUnicode_GET_SIZE(mapping);
5214 while (s < e) {
5215 unsigned char ch = *s;
5216 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005217
Benjamin Peterson29060642009-01-31 22:14:21 +00005218 if (ch < maplen)
5219 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005220
Benjamin Peterson29060642009-01-31 22:14:21 +00005221 if (x == 0xfffe) {
5222 /* undefined mapping */
5223 outpos = p-PyUnicode_AS_UNICODE(v);
5224 startinpos = s-starts;
5225 endinpos = startinpos+1;
5226 if (unicode_decode_call_errorhandler(
5227 errors, &errorHandler,
5228 "charmap", "character maps to <undefined>",
5229 &starts, &e, &startinpos, &endinpos, &exc, &s,
5230 &v, &outpos, &p)) {
5231 goto onError;
5232 }
5233 continue;
5234 }
5235 *p++ = x;
5236 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005237 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005238 }
5239 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005240 while (s < e) {
5241 unsigned char ch = *s;
5242 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005243
Benjamin Peterson29060642009-01-31 22:14:21 +00005244 /* Get mapping (char ordinal -> integer, Unicode char or None) */
5245 w = PyLong_FromLong((long)ch);
5246 if (w == NULL)
5247 goto onError;
5248 x = PyObject_GetItem(mapping, w);
5249 Py_DECREF(w);
5250 if (x == NULL) {
5251 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5252 /* No mapping found means: mapping is undefined. */
5253 PyErr_Clear();
5254 x = Py_None;
5255 Py_INCREF(x);
5256 } else
5257 goto onError;
5258 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005259
Benjamin Peterson29060642009-01-31 22:14:21 +00005260 /* Apply mapping */
5261 if (PyLong_Check(x)) {
5262 long value = PyLong_AS_LONG(x);
5263 if (value < 0 || value > 65535) {
5264 PyErr_SetString(PyExc_TypeError,
5265 "character mapping must be in range(65536)");
5266 Py_DECREF(x);
5267 goto onError;
5268 }
5269 *p++ = (Py_UNICODE)value;
5270 }
5271 else if (x == Py_None) {
5272 /* undefined mapping */
5273 outpos = p-PyUnicode_AS_UNICODE(v);
5274 startinpos = s-starts;
5275 endinpos = startinpos+1;
5276 if (unicode_decode_call_errorhandler(
5277 errors, &errorHandler,
5278 "charmap", "character maps to <undefined>",
5279 &starts, &e, &startinpos, &endinpos, &exc, &s,
5280 &v, &outpos, &p)) {
5281 Py_DECREF(x);
5282 goto onError;
5283 }
5284 Py_DECREF(x);
5285 continue;
5286 }
5287 else if (PyUnicode_Check(x)) {
5288 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005289
Benjamin Peterson29060642009-01-31 22:14:21 +00005290 if (targetsize == 1)
5291 /* 1-1 mapping */
5292 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005293
Benjamin Peterson29060642009-01-31 22:14:21 +00005294 else if (targetsize > 1) {
5295 /* 1-n mapping */
5296 if (targetsize > extrachars) {
5297 /* resize first */
5298 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
5299 Py_ssize_t needed = (targetsize - extrachars) + \
5300 (targetsize << 2);
5301 extrachars += needed;
5302 /* XXX overflow detection missing */
5303 if (_PyUnicode_Resize(&v,
5304 PyUnicode_GET_SIZE(v) + needed) < 0) {
5305 Py_DECREF(x);
5306 goto onError;
5307 }
5308 p = PyUnicode_AS_UNICODE(v) + oldpos;
5309 }
5310 Py_UNICODE_COPY(p,
5311 PyUnicode_AS_UNICODE(x),
5312 targetsize);
5313 p += targetsize;
5314 extrachars -= targetsize;
5315 }
5316 /* 1-0 mapping: skip the character */
5317 }
5318 else {
5319 /* wrong return value */
5320 PyErr_SetString(PyExc_TypeError,
5321 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00005322 Py_DECREF(x);
5323 goto onError;
5324 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005325 Py_DECREF(x);
5326 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005327 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005328 }
5329 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00005330 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
5331 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005332 Py_XDECREF(errorHandler);
5333 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005334 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00005335
Benjamin Peterson29060642009-01-31 22:14:21 +00005336 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005337 Py_XDECREF(errorHandler);
5338 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005339 Py_XDECREF(v);
5340 return NULL;
5341}
5342
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005343/* Charmap encoding: the lookup table */
5344
5345struct encoding_map{
Benjamin Peterson29060642009-01-31 22:14:21 +00005346 PyObject_HEAD
5347 unsigned char level1[32];
5348 int count2, count3;
5349 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005350};
5351
5352static PyObject*
5353encoding_map_size(PyObject *obj, PyObject* args)
5354{
5355 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005356 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00005357 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005358}
5359
5360static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005361 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00005362 PyDoc_STR("Return the size (in bytes) of this object") },
5363 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005364};
5365
5366static void
5367encoding_map_dealloc(PyObject* o)
5368{
Benjamin Peterson14339b62009-01-31 16:36:08 +00005369 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005370}
5371
5372static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005373 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005374 "EncodingMap", /*tp_name*/
5375 sizeof(struct encoding_map), /*tp_basicsize*/
5376 0, /*tp_itemsize*/
5377 /* methods */
5378 encoding_map_dealloc, /*tp_dealloc*/
5379 0, /*tp_print*/
5380 0, /*tp_getattr*/
5381 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00005382 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00005383 0, /*tp_repr*/
5384 0, /*tp_as_number*/
5385 0, /*tp_as_sequence*/
5386 0, /*tp_as_mapping*/
5387 0, /*tp_hash*/
5388 0, /*tp_call*/
5389 0, /*tp_str*/
5390 0, /*tp_getattro*/
5391 0, /*tp_setattro*/
5392 0, /*tp_as_buffer*/
5393 Py_TPFLAGS_DEFAULT, /*tp_flags*/
5394 0, /*tp_doc*/
5395 0, /*tp_traverse*/
5396 0, /*tp_clear*/
5397 0, /*tp_richcompare*/
5398 0, /*tp_weaklistoffset*/
5399 0, /*tp_iter*/
5400 0, /*tp_iternext*/
5401 encoding_map_methods, /*tp_methods*/
5402 0, /*tp_members*/
5403 0, /*tp_getset*/
5404 0, /*tp_base*/
5405 0, /*tp_dict*/
5406 0, /*tp_descr_get*/
5407 0, /*tp_descr_set*/
5408 0, /*tp_dictoffset*/
5409 0, /*tp_init*/
5410 0, /*tp_alloc*/
5411 0, /*tp_new*/
5412 0, /*tp_free*/
5413 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005414};
5415
5416PyObject*
5417PyUnicode_BuildEncodingMap(PyObject* string)
5418{
5419 Py_UNICODE *decode;
5420 PyObject *result;
5421 struct encoding_map *mresult;
5422 int i;
5423 int need_dict = 0;
5424 unsigned char level1[32];
5425 unsigned char level2[512];
5426 unsigned char *mlevel1, *mlevel2, *mlevel3;
5427 int count2 = 0, count3 = 0;
5428
5429 if (!PyUnicode_Check(string) || PyUnicode_GetSize(string) != 256) {
5430 PyErr_BadArgument();
5431 return NULL;
5432 }
5433 decode = PyUnicode_AS_UNICODE(string);
5434 memset(level1, 0xFF, sizeof level1);
5435 memset(level2, 0xFF, sizeof level2);
5436
5437 /* If there isn't a one-to-one mapping of NULL to \0,
5438 or if there are non-BMP characters, we need to use
5439 a mapping dictionary. */
5440 if (decode[0] != 0)
5441 need_dict = 1;
5442 for (i = 1; i < 256; i++) {
5443 int l1, l2;
5444 if (decode[i] == 0
Benjamin Peterson29060642009-01-31 22:14:21 +00005445#ifdef Py_UNICODE_WIDE
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005446 || decode[i] > 0xFFFF
Benjamin Peterson29060642009-01-31 22:14:21 +00005447#endif
5448 ) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005449 need_dict = 1;
5450 break;
5451 }
5452 if (decode[i] == 0xFFFE)
5453 /* unmapped character */
5454 continue;
5455 l1 = decode[i] >> 11;
5456 l2 = decode[i] >> 7;
5457 if (level1[l1] == 0xFF)
5458 level1[l1] = count2++;
5459 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00005460 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005461 }
5462
5463 if (count2 >= 0xFF || count3 >= 0xFF)
5464 need_dict = 1;
5465
5466 if (need_dict) {
5467 PyObject *result = PyDict_New();
5468 PyObject *key, *value;
5469 if (!result)
5470 return NULL;
5471 for (i = 0; i < 256; i++) {
5472 key = value = NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00005473 key = PyLong_FromLong(decode[i]);
5474 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005475 if (!key || !value)
5476 goto failed1;
5477 if (PyDict_SetItem(result, key, value) == -1)
5478 goto failed1;
5479 Py_DECREF(key);
5480 Py_DECREF(value);
5481 }
5482 return result;
5483 failed1:
5484 Py_XDECREF(key);
5485 Py_XDECREF(value);
5486 Py_DECREF(result);
5487 return NULL;
5488 }
5489
5490 /* Create a three-level trie */
5491 result = PyObject_MALLOC(sizeof(struct encoding_map) +
5492 16*count2 + 128*count3 - 1);
5493 if (!result)
5494 return PyErr_NoMemory();
5495 PyObject_Init(result, &EncodingMapType);
5496 mresult = (struct encoding_map*)result;
5497 mresult->count2 = count2;
5498 mresult->count3 = count3;
5499 mlevel1 = mresult->level1;
5500 mlevel2 = mresult->level23;
5501 mlevel3 = mresult->level23 + 16*count2;
5502 memcpy(mlevel1, level1, 32);
5503 memset(mlevel2, 0xFF, 16*count2);
5504 memset(mlevel3, 0, 128*count3);
5505 count3 = 0;
5506 for (i = 1; i < 256; i++) {
5507 int o1, o2, o3, i2, i3;
5508 if (decode[i] == 0xFFFE)
5509 /* unmapped character */
5510 continue;
5511 o1 = decode[i]>>11;
5512 o2 = (decode[i]>>7) & 0xF;
5513 i2 = 16*mlevel1[o1] + o2;
5514 if (mlevel2[i2] == 0xFF)
5515 mlevel2[i2] = count3++;
5516 o3 = decode[i] & 0x7F;
5517 i3 = 128*mlevel2[i2] + o3;
5518 mlevel3[i3] = i;
5519 }
5520 return result;
5521}
5522
5523static int
5524encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
5525{
5526 struct encoding_map *map = (struct encoding_map*)mapping;
5527 int l1 = c>>11;
5528 int l2 = (c>>7) & 0xF;
5529 int l3 = c & 0x7F;
5530 int i;
5531
5532#ifdef Py_UNICODE_WIDE
5533 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005534 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005535 }
5536#endif
5537 if (c == 0)
5538 return 0;
5539 /* level 1*/
5540 i = map->level1[l1];
5541 if (i == 0xFF) {
5542 return -1;
5543 }
5544 /* level 2*/
5545 i = map->level23[16*i+l2];
5546 if (i == 0xFF) {
5547 return -1;
5548 }
5549 /* level 3 */
5550 i = map->level23[16*map->count2 + 128*i + l3];
5551 if (i == 0) {
5552 return -1;
5553 }
5554 return i;
5555}
5556
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005557/* Lookup the character ch in the mapping. If the character
5558 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00005559 error occurred). */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005560static PyObject *charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005561{
Christian Heimes217cfd12007-12-02 14:31:20 +00005562 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005563 PyObject *x;
5564
5565 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005566 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005567 x = PyObject_GetItem(mapping, w);
5568 Py_DECREF(w);
5569 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005570 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5571 /* No mapping found means: mapping is undefined. */
5572 PyErr_Clear();
5573 x = Py_None;
5574 Py_INCREF(x);
5575 return x;
5576 } else
5577 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005578 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00005579 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00005580 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00005581 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005582 long value = PyLong_AS_LONG(x);
5583 if (value < 0 || value > 255) {
5584 PyErr_SetString(PyExc_TypeError,
5585 "character mapping must be in range(256)");
5586 Py_DECREF(x);
5587 return NULL;
5588 }
5589 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005590 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005591 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00005592 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005593 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005594 /* wrong return value */
5595 PyErr_Format(PyExc_TypeError,
5596 "character mapping must return integer, bytes or None, not %.400s",
5597 x->ob_type->tp_name);
5598 Py_DECREF(x);
5599 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005600 }
5601}
5602
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005603static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00005604charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005605{
Benjamin Peterson14339b62009-01-31 16:36:08 +00005606 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
5607 /* exponentially overallocate to minimize reallocations */
5608 if (requiredsize < 2*outsize)
5609 requiredsize = 2*outsize;
5610 if (_PyBytes_Resize(outobj, requiredsize))
5611 return -1;
5612 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005613}
5614
Benjamin Peterson14339b62009-01-31 16:36:08 +00005615typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00005616 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005617}charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005618/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00005619 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005620 space is available. Return a new reference to the object that
5621 was put in the output buffer, or Py_None, if the mapping was undefined
5622 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00005623 reallocation error occurred. The caller must decref the result */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005624static
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005625charmapencode_result charmapencode_output(Py_UNICODE c, PyObject *mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00005626 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005627{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005628 PyObject *rep;
5629 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00005630 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005631
Christian Heimes90aa7642007-12-19 02:45:37 +00005632 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005633 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00005634 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005635 if (res == -1)
5636 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00005637 if (outsize<requiredsize)
5638 if (charmapencode_resize(outobj, outpos, requiredsize))
5639 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00005640 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005641 outstart[(*outpos)++] = (char)res;
5642 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005643 }
5644
5645 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005646 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005647 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005648 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005649 Py_DECREF(rep);
5650 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005651 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005652 if (PyLong_Check(rep)) {
5653 Py_ssize_t requiredsize = *outpos+1;
5654 if (outsize<requiredsize)
5655 if (charmapencode_resize(outobj, outpos, requiredsize)) {
5656 Py_DECREF(rep);
5657 return enc_EXCEPTION;
5658 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005659 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005660 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005661 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005662 else {
5663 const char *repchars = PyBytes_AS_STRING(rep);
5664 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
5665 Py_ssize_t requiredsize = *outpos+repsize;
5666 if (outsize<requiredsize)
5667 if (charmapencode_resize(outobj, outpos, requiredsize)) {
5668 Py_DECREF(rep);
5669 return enc_EXCEPTION;
5670 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005671 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005672 memcpy(outstart + *outpos, repchars, repsize);
5673 *outpos += repsize;
5674 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005675 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005676 Py_DECREF(rep);
5677 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005678}
5679
5680/* handle an error in PyUnicode_EncodeCharmap
5681 Return 0 on success, -1 on error */
5682static
5683int charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00005684 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005685 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00005686 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00005687 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005688{
5689 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005690 Py_ssize_t repsize;
5691 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005692 Py_UNICODE *uni2;
5693 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005694 Py_ssize_t collstartpos = *inpos;
5695 Py_ssize_t collendpos = *inpos+1;
5696 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005697 char *encoding = "charmap";
5698 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005699 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005700
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005701 /* find all unencodable characters */
5702 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005703 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00005704 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005705 int res = encoding_map_lookup(p[collendpos], mapping);
5706 if (res != -1)
5707 break;
5708 ++collendpos;
5709 continue;
5710 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005711
Benjamin Peterson29060642009-01-31 22:14:21 +00005712 rep = charmapencode_lookup(p[collendpos], mapping);
5713 if (rep==NULL)
5714 return -1;
5715 else if (rep!=Py_None) {
5716 Py_DECREF(rep);
5717 break;
5718 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005719 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00005720 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005721 }
5722 /* cache callback name lookup
5723 * (if not done yet, i.e. it's the first error) */
5724 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005725 if ((errors==NULL) || (!strcmp(errors, "strict")))
5726 *known_errorHandler = 1;
5727 else if (!strcmp(errors, "replace"))
5728 *known_errorHandler = 2;
5729 else if (!strcmp(errors, "ignore"))
5730 *known_errorHandler = 3;
5731 else if (!strcmp(errors, "xmlcharrefreplace"))
5732 *known_errorHandler = 4;
5733 else
5734 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005735 }
5736 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005737 case 1: /* strict */
5738 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5739 return -1;
5740 case 2: /* replace */
5741 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005742 x = charmapencode_output('?', mapping, res, respos);
5743 if (x==enc_EXCEPTION) {
5744 return -1;
5745 }
5746 else if (x==enc_FAILED) {
5747 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5748 return -1;
5749 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005750 }
5751 /* fall through */
5752 case 3: /* ignore */
5753 *inpos = collendpos;
5754 break;
5755 case 4: /* xmlcharrefreplace */
5756 /* generate replacement (temporarily (mis)uses p) */
5757 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005758 char buffer[2+29+1+1];
5759 char *cp;
5760 sprintf(buffer, "&#%d;", (int)p[collpos]);
5761 for (cp = buffer; *cp; ++cp) {
5762 x = charmapencode_output(*cp, mapping, res, respos);
5763 if (x==enc_EXCEPTION)
5764 return -1;
5765 else if (x==enc_FAILED) {
5766 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5767 return -1;
5768 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005769 }
5770 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005771 *inpos = collendpos;
5772 break;
5773 default:
5774 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00005775 encoding, reason, p, size, exceptionObject,
5776 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005777 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005778 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005779 if (PyBytes_Check(repunicode)) {
5780 /* Directly copy bytes result to output. */
5781 Py_ssize_t outsize = PyBytes_Size(*res);
5782 Py_ssize_t requiredsize;
5783 repsize = PyBytes_Size(repunicode);
5784 requiredsize = *respos + repsize;
5785 if (requiredsize > outsize)
5786 /* Make room for all additional bytes. */
5787 if (charmapencode_resize(res, respos, requiredsize)) {
5788 Py_DECREF(repunicode);
5789 return -1;
5790 }
5791 memcpy(PyBytes_AsString(*res) + *respos,
5792 PyBytes_AsString(repunicode), repsize);
5793 *respos += repsize;
5794 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005795 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00005796 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005797 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005798 /* generate replacement */
5799 repsize = PyUnicode_GET_SIZE(repunicode);
5800 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005801 x = charmapencode_output(*uni2, mapping, res, respos);
5802 if (x==enc_EXCEPTION) {
5803 return -1;
5804 }
5805 else if (x==enc_FAILED) {
5806 Py_DECREF(repunicode);
5807 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5808 return -1;
5809 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005810 }
5811 *inpos = newpos;
5812 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005813 }
5814 return 0;
5815}
5816
Guido van Rossumd57fd912000-03-10 22:53:23 +00005817PyObject *PyUnicode_EncodeCharmap(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00005818 Py_ssize_t size,
5819 PyObject *mapping,
5820 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005821{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005822 /* output object */
5823 PyObject *res = NULL;
5824 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005825 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005826 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005827 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005828 PyObject *errorHandler = NULL;
5829 PyObject *exc = NULL;
5830 /* the following variable is used for caching string comparisons
5831 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
5832 * 3=ignore, 4=xmlcharrefreplace */
5833 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005834
5835 /* Default to Latin-1 */
5836 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005837 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005838
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005839 /* allocate enough for a simple encoding without
5840 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00005841 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005842 if (res == NULL)
5843 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00005844 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005845 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005846
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005847 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005848 /* try to encode it */
5849 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
5850 if (x==enc_EXCEPTION) /* error */
5851 goto onError;
5852 if (x==enc_FAILED) { /* unencodable character */
5853 if (charmap_encoding_error(p, size, &inpos, mapping,
5854 &exc,
5855 &known_errorHandler, &errorHandler, errors,
5856 &res, &respos)) {
5857 goto onError;
5858 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005859 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005860 else
5861 /* done with this character => adjust input position */
5862 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005863 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005864
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005865 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00005866 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005867 if (_PyBytes_Resize(&res, respos) < 0)
5868 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005869
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005870 Py_XDECREF(exc);
5871 Py_XDECREF(errorHandler);
5872 return res;
5873
Benjamin Peterson29060642009-01-31 22:14:21 +00005874 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005875 Py_XDECREF(res);
5876 Py_XDECREF(exc);
5877 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005878 return NULL;
5879}
5880
5881PyObject *PyUnicode_AsCharmapString(PyObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00005882 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005883{
5884 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005885 PyErr_BadArgument();
5886 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005887 }
5888 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005889 PyUnicode_GET_SIZE(unicode),
5890 mapping,
5891 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005892}
5893
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005894/* create or adjust a UnicodeTranslateError */
5895static void make_translate_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005896 const Py_UNICODE *unicode, Py_ssize_t size,
5897 Py_ssize_t startpos, Py_ssize_t endpos,
5898 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005899{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005900 if (*exceptionObject == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005901 *exceptionObject = PyUnicodeTranslateError_Create(
Benjamin Peterson29060642009-01-31 22:14:21 +00005902 unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005903 }
5904 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005905 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
5906 goto onError;
5907 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
5908 goto onError;
5909 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
5910 goto onError;
5911 return;
5912 onError:
5913 Py_DECREF(*exceptionObject);
5914 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005915 }
5916}
5917
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005918/* raises a UnicodeTranslateError */
5919static void raise_translate_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005920 const Py_UNICODE *unicode, Py_ssize_t size,
5921 Py_ssize_t startpos, Py_ssize_t endpos,
5922 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005923{
5924 make_translate_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005925 unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005926 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005927 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005928}
5929
5930/* error handling callback helper:
5931 build arguments, call the callback and check the arguments,
5932 put the result into newpos and return the replacement string, which
5933 has to be freed by the caller */
5934static PyObject *unicode_translate_call_errorhandler(const char *errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00005935 PyObject **errorHandler,
5936 const char *reason,
5937 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
5938 Py_ssize_t startpos, Py_ssize_t endpos,
5939 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005940{
Benjamin Peterson142957c2008-07-04 19:55:29 +00005941 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005942
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005943 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005944 PyObject *restuple;
5945 PyObject *resunicode;
5946
5947 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005948 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005949 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005950 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005951 }
5952
5953 make_translate_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005954 unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005955 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005956 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005957
5958 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00005959 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005960 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005961 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005962 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00005963 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00005964 Py_DECREF(restuple);
5965 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005966 }
5967 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00005968 &resunicode, &i_newpos)) {
5969 Py_DECREF(restuple);
5970 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005971 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00005972 if (i_newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005973 *newpos = size+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005974 else
5975 *newpos = i_newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005976 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005977 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
5978 Py_DECREF(restuple);
5979 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005980 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005981 Py_INCREF(resunicode);
5982 Py_DECREF(restuple);
5983 return resunicode;
5984}
5985
5986/* Lookup the character ch in the mapping and put the result in result,
5987 which must be decrefed by the caller.
5988 Return 0 on success, -1 on error */
5989static
5990int charmaptranslate_lookup(Py_UNICODE c, PyObject *mapping, PyObject **result)
5991{
Christian Heimes217cfd12007-12-02 14:31:20 +00005992 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005993 PyObject *x;
5994
5995 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005996 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005997 x = PyObject_GetItem(mapping, w);
5998 Py_DECREF(w);
5999 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006000 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
6001 /* No mapping found means: use 1:1 mapping. */
6002 PyErr_Clear();
6003 *result = NULL;
6004 return 0;
6005 } else
6006 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006007 }
6008 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006009 *result = x;
6010 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006011 }
Christian Heimes217cfd12007-12-02 14:31:20 +00006012 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006013 long value = PyLong_AS_LONG(x);
6014 long max = PyUnicode_GetMax();
6015 if (value < 0 || value > max) {
6016 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00006017 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00006018 Py_DECREF(x);
6019 return -1;
6020 }
6021 *result = x;
6022 return 0;
6023 }
6024 else if (PyUnicode_Check(x)) {
6025 *result = x;
6026 return 0;
6027 }
6028 else {
6029 /* wrong return value */
6030 PyErr_SetString(PyExc_TypeError,
6031 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00006032 Py_DECREF(x);
6033 return -1;
6034 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006035}
6036/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00006037 if not reallocate and adjust various state variables.
6038 Return 0 on success, -1 on error */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006039static
Walter Dörwald4894c302003-10-24 14:25:28 +00006040int charmaptranslate_makespace(PyObject **outobj, Py_UNICODE **outp,
Benjamin Peterson29060642009-01-31 22:14:21 +00006041 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006042{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006043 Py_ssize_t oldsize = PyUnicode_GET_SIZE(*outobj);
Walter Dörwald4894c302003-10-24 14:25:28 +00006044 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006045 /* remember old output position */
6046 Py_ssize_t outpos = *outp-PyUnicode_AS_UNICODE(*outobj);
6047 /* exponentially overallocate to minimize reallocations */
6048 if (requiredsize < 2 * oldsize)
6049 requiredsize = 2 * oldsize;
6050 if (PyUnicode_Resize(outobj, requiredsize) < 0)
6051 return -1;
6052 *outp = PyUnicode_AS_UNICODE(*outobj) + outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006053 }
6054 return 0;
6055}
6056/* lookup the character, put the result in the output string and adjust
6057 various state variables. Return a new reference to the object that
6058 was put in the output buffer in *result, or Py_None, if the mapping was
6059 undefined (in which case no character was written).
6060 The called must decref result.
6061 Return 0 on success, -1 on error. */
6062static
Walter Dörwald4894c302003-10-24 14:25:28 +00006063int charmaptranslate_output(const Py_UNICODE *startinp, const Py_UNICODE *curinp,
Benjamin Peterson29060642009-01-31 22:14:21 +00006064 Py_ssize_t insize, PyObject *mapping, PyObject **outobj, Py_UNICODE **outp,
6065 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006066{
Walter Dörwald4894c302003-10-24 14:25:28 +00006067 if (charmaptranslate_lookup(*curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00006068 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006069 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006070 /* not found => default to 1:1 mapping */
6071 *(*outp)++ = *curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006072 }
6073 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00006074 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00006075 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006076 /* no overflow check, because we know that the space is enough */
6077 *(*outp)++ = (Py_UNICODE)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006078 }
6079 else if (PyUnicode_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006080 Py_ssize_t repsize = PyUnicode_GET_SIZE(*res);
6081 if (repsize==1) {
6082 /* no overflow check, because we know that the space is enough */
6083 *(*outp)++ = *PyUnicode_AS_UNICODE(*res);
6084 }
6085 else if (repsize!=0) {
6086 /* more than one character */
6087 Py_ssize_t requiredsize = (*outp-PyUnicode_AS_UNICODE(*outobj)) +
6088 (insize - (curinp-startinp)) +
6089 repsize - 1;
6090 if (charmaptranslate_makespace(outobj, outp, requiredsize))
6091 return -1;
6092 memcpy(*outp, PyUnicode_AS_UNICODE(*res), sizeof(Py_UNICODE)*repsize);
6093 *outp += repsize;
6094 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006095 }
6096 else
Benjamin Peterson29060642009-01-31 22:14:21 +00006097 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006098 return 0;
6099}
6100
6101PyObject *PyUnicode_TranslateCharmap(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00006102 Py_ssize_t size,
6103 PyObject *mapping,
6104 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006105{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006106 /* output object */
6107 PyObject *res = NULL;
6108 /* pointers to the beginning and end+1 of input */
6109 const Py_UNICODE *startp = p;
6110 const Py_UNICODE *endp = p + size;
6111 /* pointer into the output */
6112 Py_UNICODE *str;
6113 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006114 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006115 char *reason = "character maps to <undefined>";
6116 PyObject *errorHandler = NULL;
6117 PyObject *exc = NULL;
6118 /* the following variable is used for caching string comparisons
6119 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
6120 * 3=ignore, 4=xmlcharrefreplace */
6121 int known_errorHandler = -1;
6122
Guido van Rossumd57fd912000-03-10 22:53:23 +00006123 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006124 PyErr_BadArgument();
6125 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006126 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006127
6128 /* allocate enough for a simple 1:1 translation without
6129 replacements, if we need more, we'll resize */
6130 res = PyUnicode_FromUnicode(NULL, size);
6131 if (res == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006132 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006133 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006134 return res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006135 str = PyUnicode_AS_UNICODE(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006136
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006137 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006138 /* try to encode it */
6139 PyObject *x = NULL;
6140 if (charmaptranslate_output(startp, p, size, mapping, &res, &str, &x)) {
6141 Py_XDECREF(x);
6142 goto onError;
6143 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006144 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00006145 if (x!=Py_None) /* it worked => adjust input pointer */
6146 ++p;
6147 else { /* untranslatable character */
6148 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
6149 Py_ssize_t repsize;
6150 Py_ssize_t newpos;
6151 Py_UNICODE *uni2;
6152 /* startpos for collecting untranslatable chars */
6153 const Py_UNICODE *collstart = p;
6154 const Py_UNICODE *collend = p+1;
6155 const Py_UNICODE *coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006156
Benjamin Peterson29060642009-01-31 22:14:21 +00006157 /* find all untranslatable characters */
6158 while (collend < endp) {
6159 if (charmaptranslate_lookup(*collend, mapping, &x))
6160 goto onError;
6161 Py_XDECREF(x);
6162 if (x!=Py_None)
6163 break;
6164 ++collend;
6165 }
6166 /* cache callback name lookup
6167 * (if not done yet, i.e. it's the first error) */
6168 if (known_errorHandler==-1) {
6169 if ((errors==NULL) || (!strcmp(errors, "strict")))
6170 known_errorHandler = 1;
6171 else if (!strcmp(errors, "replace"))
6172 known_errorHandler = 2;
6173 else if (!strcmp(errors, "ignore"))
6174 known_errorHandler = 3;
6175 else if (!strcmp(errors, "xmlcharrefreplace"))
6176 known_errorHandler = 4;
6177 else
6178 known_errorHandler = 0;
6179 }
6180 switch (known_errorHandler) {
6181 case 1: /* strict */
6182 raise_translate_exception(&exc, startp, size, collstart-startp, collend-startp, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006183 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006184 case 2: /* replace */
6185 /* No need to check for space, this is a 1:1 replacement */
6186 for (coll = collstart; coll<collend; ++coll)
6187 *str++ = '?';
6188 /* fall through */
6189 case 3: /* ignore */
6190 p = collend;
6191 break;
6192 case 4: /* xmlcharrefreplace */
6193 /* generate replacement (temporarily (mis)uses p) */
6194 for (p = collstart; p < collend; ++p) {
6195 char buffer[2+29+1+1];
6196 char *cp;
6197 sprintf(buffer, "&#%d;", (int)*p);
6198 if (charmaptranslate_makespace(&res, &str,
6199 (str-PyUnicode_AS_UNICODE(res))+strlen(buffer)+(endp-collend)))
6200 goto onError;
6201 for (cp = buffer; *cp; ++cp)
6202 *str++ = *cp;
6203 }
6204 p = collend;
6205 break;
6206 default:
6207 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
6208 reason, startp, size, &exc,
6209 collstart-startp, collend-startp, &newpos);
6210 if (repunicode == NULL)
6211 goto onError;
6212 /* generate replacement */
6213 repsize = PyUnicode_GET_SIZE(repunicode);
6214 if (charmaptranslate_makespace(&res, &str,
6215 (str-PyUnicode_AS_UNICODE(res))+repsize+(endp-collend))) {
6216 Py_DECREF(repunicode);
6217 goto onError;
6218 }
6219 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2)
6220 *str++ = *uni2;
6221 p = startp + newpos;
6222 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006223 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006224 }
6225 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006226 /* Resize if we allocated to much */
6227 respos = str-PyUnicode_AS_UNICODE(res);
Walter Dörwald4894c302003-10-24 14:25:28 +00006228 if (respos<PyUnicode_GET_SIZE(res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006229 if (PyUnicode_Resize(&res, respos) < 0)
6230 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006231 }
6232 Py_XDECREF(exc);
6233 Py_XDECREF(errorHandler);
6234 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006235
Benjamin Peterson29060642009-01-31 22:14:21 +00006236 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006237 Py_XDECREF(res);
6238 Py_XDECREF(exc);
6239 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006240 return NULL;
6241}
6242
6243PyObject *PyUnicode_Translate(PyObject *str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006244 PyObject *mapping,
6245 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006246{
6247 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00006248
Guido van Rossumd57fd912000-03-10 22:53:23 +00006249 str = PyUnicode_FromObject(str);
6250 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006251 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006252 result = PyUnicode_TranslateCharmap(PyUnicode_AS_UNICODE(str),
Benjamin Peterson29060642009-01-31 22:14:21 +00006253 PyUnicode_GET_SIZE(str),
6254 mapping,
6255 errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006256 Py_DECREF(str);
6257 return result;
Tim Petersced69f82003-09-16 20:30:58 +00006258
Benjamin Peterson29060642009-01-31 22:14:21 +00006259 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006260 Py_XDECREF(str);
6261 return NULL;
6262}
Tim Petersced69f82003-09-16 20:30:58 +00006263
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00006264PyObject *
6265PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
6266 Py_ssize_t length)
6267{
6268 PyObject *result;
6269 Py_UNICODE *p; /* write pointer into result */
6270 Py_ssize_t i;
6271 /* Copy to a new string */
6272 result = (PyObject *)_PyUnicode_New(length);
6273 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
6274 if (result == NULL)
6275 return result;
6276 p = PyUnicode_AS_UNICODE(result);
6277 /* Iterate over code points */
6278 for (i = 0; i < length; i++) {
6279 Py_UNICODE ch =s[i];
6280 if (ch > 127) {
6281 int decimal = Py_UNICODE_TODECIMAL(ch);
6282 if (decimal >= 0)
6283 p[i] = '0' + decimal;
6284 }
6285 }
6286 return result;
6287}
Guido van Rossum9e896b32000-04-05 20:11:21 +00006288/* --- Decimal Encoder ---------------------------------------------------- */
6289
6290int PyUnicode_EncodeDecimal(Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00006291 Py_ssize_t length,
6292 char *output,
6293 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00006294{
6295 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006296 PyObject *errorHandler = NULL;
6297 PyObject *exc = NULL;
6298 const char *encoding = "decimal";
6299 const char *reason = "invalid decimal Unicode string";
6300 /* the following variable is used for caching string comparisons
6301 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6302 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00006303
6304 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006305 PyErr_BadArgument();
6306 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00006307 }
6308
6309 p = s;
6310 end = s + length;
6311 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006312 register Py_UNICODE ch = *p;
6313 int decimal;
6314 PyObject *repunicode;
6315 Py_ssize_t repsize;
6316 Py_ssize_t newpos;
6317 Py_UNICODE *uni2;
6318 Py_UNICODE *collstart;
6319 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00006320
Benjamin Peterson29060642009-01-31 22:14:21 +00006321 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006322 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00006323 ++p;
6324 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006325 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006326 decimal = Py_UNICODE_TODECIMAL(ch);
6327 if (decimal >= 0) {
6328 *output++ = '0' + decimal;
6329 ++p;
6330 continue;
6331 }
6332 if (0 < ch && ch < 256) {
6333 *output++ = (char)ch;
6334 ++p;
6335 continue;
6336 }
6337 /* All other characters are considered unencodable */
6338 collstart = p;
Victor Stinnerab1d16b2011-11-22 01:45:37 +01006339 for (collend = p+1; collend < end; collend++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006340 if ((0 < *collend && *collend < 256) ||
Victor Stinnerab1d16b2011-11-22 01:45:37 +01006341 Py_UNICODE_ISSPACE(*collend) ||
6342 0 <= Py_UNICODE_TODECIMAL(*collend))
Benjamin Peterson29060642009-01-31 22:14:21 +00006343 break;
6344 }
6345 /* cache callback name lookup
6346 * (if not done yet, i.e. it's the first error) */
6347 if (known_errorHandler==-1) {
6348 if ((errors==NULL) || (!strcmp(errors, "strict")))
6349 known_errorHandler = 1;
6350 else if (!strcmp(errors, "replace"))
6351 known_errorHandler = 2;
6352 else if (!strcmp(errors, "ignore"))
6353 known_errorHandler = 3;
6354 else if (!strcmp(errors, "xmlcharrefreplace"))
6355 known_errorHandler = 4;
6356 else
6357 known_errorHandler = 0;
6358 }
6359 switch (known_errorHandler) {
6360 case 1: /* strict */
6361 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
6362 goto onError;
6363 case 2: /* replace */
6364 for (p = collstart; p < collend; ++p)
6365 *output++ = '?';
6366 /* fall through */
6367 case 3: /* ignore */
6368 p = collend;
6369 break;
6370 case 4: /* xmlcharrefreplace */
6371 /* generate replacement (temporarily (mis)uses p) */
6372 for (p = collstart; p < collend; ++p)
6373 output += sprintf(output, "&#%d;", (int)*p);
6374 p = collend;
6375 break;
6376 default:
6377 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
6378 encoding, reason, s, length, &exc,
6379 collstart-s, collend-s, &newpos);
6380 if (repunicode == NULL)
6381 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006382 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006383 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006384 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
6385 Py_DECREF(repunicode);
6386 goto onError;
6387 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006388 /* generate replacement */
6389 repsize = PyUnicode_GET_SIZE(repunicode);
6390 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
6391 Py_UNICODE ch = *uni2;
6392 if (Py_UNICODE_ISSPACE(ch))
6393 *output++ = ' ';
6394 else {
6395 decimal = Py_UNICODE_TODECIMAL(ch);
6396 if (decimal >= 0)
6397 *output++ = '0' + decimal;
6398 else if (0 < ch && ch < 256)
6399 *output++ = (char)ch;
6400 else {
6401 Py_DECREF(repunicode);
6402 raise_encode_exception(&exc, encoding,
6403 s, length, collstart-s, collend-s, reason);
6404 goto onError;
6405 }
6406 }
6407 }
6408 p = s + newpos;
6409 Py_DECREF(repunicode);
6410 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00006411 }
6412 /* 0-terminate the output string */
6413 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006414 Py_XDECREF(exc);
6415 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00006416 return 0;
6417
Benjamin Peterson29060642009-01-31 22:14:21 +00006418 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006419 Py_XDECREF(exc);
6420 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00006421 return -1;
6422}
6423
Guido van Rossumd57fd912000-03-10 22:53:23 +00006424/* --- Helpers ------------------------------------------------------------ */
6425
Eric Smith8c663262007-08-25 02:26:07 +00006426#include "stringlib/unicodedefs.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00006427#include "stringlib/fastsearch.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006428
Thomas Wouters477c8d52006-05-27 19:21:47 +00006429#include "stringlib/count.h"
6430#include "stringlib/find.h"
6431#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006432#include "stringlib/split.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00006433
Eric Smith5807c412008-05-11 21:00:57 +00006434#define _Py_InsertThousandsGrouping _PyUnicode_InsertThousandsGrouping
Eric Smitha3b1ac82009-04-03 14:45:06 +00006435#define _Py_InsertThousandsGroupingLocale _PyUnicode_InsertThousandsGroupingLocale
Eric Smith5807c412008-05-11 21:00:57 +00006436#include "stringlib/localeutil.h"
6437
Thomas Wouters477c8d52006-05-27 19:21:47 +00006438/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006439#define ADJUST_INDICES(start, end, len) \
6440 if (end > len) \
6441 end = len; \
6442 else if (end < 0) { \
6443 end += len; \
6444 if (end < 0) \
6445 end = 0; \
6446 } \
6447 if (start < 0) { \
6448 start += len; \
6449 if (start < 0) \
6450 start = 0; \
6451 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00006452
Ezio Melotti93e7afc2011-08-22 14:08:38 +03006453/* _Py_UNICODE_NEXT is a private macro used to retrieve the character pointed
6454 * by 'ptr', possibly combining surrogate pairs on narrow builds.
6455 * 'ptr' and 'end' must be Py_UNICODE*, with 'ptr' pointing at the character
6456 * that should be returned and 'end' pointing to the end of the buffer.
6457 * ('end' is used on narrow builds to detect a lone surrogate at the
6458 * end of the buffer that should be returned unchanged.)
6459 * The ptr and end arguments should be side-effect free and ptr must an lvalue.
6460 * The type of the returned char is always Py_UCS4.
6461 *
6462 * Note: the macro advances ptr to next char, so it might have side-effects
6463 * (especially if used with other macros).
6464 */
6465
6466/* helper macros used by _Py_UNICODE_NEXT */
6467#define _Py_UNICODE_IS_HIGH_SURROGATE(ch) (0xD800 <= ch && ch <= 0xDBFF)
6468#define _Py_UNICODE_IS_LOW_SURROGATE(ch) (0xDC00 <= ch && ch <= 0xDFFF)
6469/* Join two surrogate characters and return a single Py_UCS4 value. */
6470#define _Py_UNICODE_JOIN_SURROGATES(high, low) \
6471 (((((Py_UCS4)(high) & 0x03FF) << 10) | \
6472 ((Py_UCS4)(low) & 0x03FF)) + 0x10000)
6473
6474#ifdef Py_UNICODE_WIDE
6475#define _Py_UNICODE_NEXT(ptr, end) *(ptr)++
6476#else
6477#define _Py_UNICODE_NEXT(ptr, end) \
6478 (((_Py_UNICODE_IS_HIGH_SURROGATE(*(ptr)) && (ptr) < (end)) && \
6479 _Py_UNICODE_IS_LOW_SURROGATE((ptr)[1])) ? \
6480 ((ptr) += 2,_Py_UNICODE_JOIN_SURROGATES((ptr)[-2], (ptr)[-1])) : \
6481 (Py_UCS4)*(ptr)++)
6482#endif
6483
Martin v. Löwis18e16552006-02-15 17:27:45 +00006484Py_ssize_t PyUnicode_Count(PyObject *str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00006485 PyObject *substr,
6486 Py_ssize_t start,
6487 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006488{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006489 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006490 PyUnicodeObject* str_obj;
6491 PyUnicodeObject* sub_obj;
Tim Petersced69f82003-09-16 20:30:58 +00006492
Thomas Wouters477c8d52006-05-27 19:21:47 +00006493 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
6494 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00006495 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006496 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
6497 if (!sub_obj) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006498 Py_DECREF(str_obj);
6499 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006500 }
Tim Petersced69f82003-09-16 20:30:58 +00006501
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006502 ADJUST_INDICES(start, end, str_obj->length);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006503 result = stringlib_count(
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006504 str_obj->str + start, end - start, sub_obj->str, sub_obj->length,
6505 PY_SSIZE_T_MAX
Thomas Wouters477c8d52006-05-27 19:21:47 +00006506 );
6507
6508 Py_DECREF(sub_obj);
6509 Py_DECREF(str_obj);
6510
Guido van Rossumd57fd912000-03-10 22:53:23 +00006511 return result;
6512}
6513
Martin v. Löwis18e16552006-02-15 17:27:45 +00006514Py_ssize_t PyUnicode_Find(PyObject *str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00006515 PyObject *sub,
6516 Py_ssize_t start,
6517 Py_ssize_t end,
6518 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006519{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006520 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00006521
Guido van Rossumd57fd912000-03-10 22:53:23 +00006522 str = PyUnicode_FromObject(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006523 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00006524 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006525 sub = PyUnicode_FromObject(sub);
6526 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006527 Py_DECREF(str);
6528 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006529 }
Tim Petersced69f82003-09-16 20:30:58 +00006530
Thomas Wouters477c8d52006-05-27 19:21:47 +00006531 if (direction > 0)
6532 result = stringlib_find_slice(
6533 PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
6534 PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
6535 start, end
6536 );
6537 else
6538 result = stringlib_rfind_slice(
6539 PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
6540 PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
6541 start, end
6542 );
6543
Guido van Rossumd57fd912000-03-10 22:53:23 +00006544 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006545 Py_DECREF(sub);
6546
Guido van Rossumd57fd912000-03-10 22:53:23 +00006547 return result;
6548}
6549
Tim Petersced69f82003-09-16 20:30:58 +00006550static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006551int tailmatch(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006552 PyUnicodeObject *substring,
6553 Py_ssize_t start,
6554 Py_ssize_t end,
6555 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006556{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006557 if (substring->length == 0)
6558 return 1;
6559
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006560 ADJUST_INDICES(start, end, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006561 end -= substring->length;
6562 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00006563 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006564
6565 if (direction > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006566 if (Py_UNICODE_MATCH(self, end, substring))
6567 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006568 } else {
6569 if (Py_UNICODE_MATCH(self, start, substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00006570 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006571 }
6572
6573 return 0;
6574}
6575
Martin v. Löwis18e16552006-02-15 17:27:45 +00006576Py_ssize_t PyUnicode_Tailmatch(PyObject *str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006577 PyObject *substr,
6578 Py_ssize_t start,
6579 Py_ssize_t end,
6580 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006581{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006582 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00006583
Guido van Rossumd57fd912000-03-10 22:53:23 +00006584 str = PyUnicode_FromObject(str);
6585 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006586 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006587 substr = PyUnicode_FromObject(substr);
6588 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006589 Py_DECREF(str);
6590 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006591 }
Tim Petersced69f82003-09-16 20:30:58 +00006592
Guido van Rossumd57fd912000-03-10 22:53:23 +00006593 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006594 (PyUnicodeObject *)substr,
6595 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006596 Py_DECREF(str);
6597 Py_DECREF(substr);
6598 return result;
6599}
6600
Guido van Rossumd57fd912000-03-10 22:53:23 +00006601/* Apply fixfct filter to the Unicode object self and return a
6602 reference to the modified object */
6603
Tim Petersced69f82003-09-16 20:30:58 +00006604static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006605PyObject *fixup(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006606 int (*fixfct)(PyUnicodeObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00006607{
6608
6609 PyUnicodeObject *u;
6610
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006611 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006612 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006613 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006614
6615 Py_UNICODE_COPY(u->str, self->str, self->length);
6616
Tim Peters7a29bd52001-09-12 03:03:31 +00006617 if (!fixfct(u) && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006618 /* fixfct should return TRUE if it modified the buffer. If
6619 FALSE, return a reference to the original buffer instead
6620 (to save space, not time) */
6621 Py_INCREF(self);
6622 Py_DECREF(u);
6623 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006624 }
6625 return (PyObject*) u;
6626}
6627
Tim Petersced69f82003-09-16 20:30:58 +00006628static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006629int fixupper(PyUnicodeObject *self)
6630{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006631 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006632 Py_UNICODE *s = self->str;
6633 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006634
Guido van Rossumd57fd912000-03-10 22:53:23 +00006635 while (len-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006636 register Py_UNICODE ch;
Tim Petersced69f82003-09-16 20:30:58 +00006637
Benjamin Peterson29060642009-01-31 22:14:21 +00006638 ch = Py_UNICODE_TOUPPER(*s);
6639 if (ch != *s) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006640 status = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006641 *s = ch;
6642 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006643 s++;
6644 }
6645
6646 return status;
6647}
6648
Tim Petersced69f82003-09-16 20:30:58 +00006649static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006650int fixlower(PyUnicodeObject *self)
6651{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006652 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006653 Py_UNICODE *s = self->str;
6654 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006655
Guido van Rossumd57fd912000-03-10 22:53:23 +00006656 while (len-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006657 register Py_UNICODE ch;
Tim Petersced69f82003-09-16 20:30:58 +00006658
Benjamin Peterson29060642009-01-31 22:14:21 +00006659 ch = Py_UNICODE_TOLOWER(*s);
6660 if (ch != *s) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006661 status = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006662 *s = ch;
6663 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006664 s++;
6665 }
6666
6667 return status;
6668}
6669
Tim Petersced69f82003-09-16 20:30:58 +00006670static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006671int fixswapcase(PyUnicodeObject *self)
6672{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006673 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006674 Py_UNICODE *s = self->str;
6675 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006676
Guido van Rossumd57fd912000-03-10 22:53:23 +00006677 while (len-- > 0) {
6678 if (Py_UNICODE_ISUPPER(*s)) {
6679 *s = Py_UNICODE_TOLOWER(*s);
6680 status = 1;
6681 } else if (Py_UNICODE_ISLOWER(*s)) {
6682 *s = Py_UNICODE_TOUPPER(*s);
6683 status = 1;
6684 }
6685 s++;
6686 }
6687
6688 return status;
6689}
6690
Tim Petersced69f82003-09-16 20:30:58 +00006691static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006692int fixcapitalize(PyUnicodeObject *self)
6693{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006694 Py_ssize_t len = self->length;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006695 Py_UNICODE *s = self->str;
6696 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006697
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006698 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006699 return 0;
Ezio Melottiee8d9982011-08-15 09:09:57 +03006700 if (!Py_UNICODE_ISUPPER(*s)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006701 *s = Py_UNICODE_TOUPPER(*s);
6702 status = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006703 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006704 s++;
6705 while (--len > 0) {
Ezio Melottiee8d9982011-08-15 09:09:57 +03006706 if (!Py_UNICODE_ISLOWER(*s)) {
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006707 *s = Py_UNICODE_TOLOWER(*s);
6708 status = 1;
6709 }
6710 s++;
6711 }
6712 return status;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006713}
6714
6715static
6716int fixtitle(PyUnicodeObject *self)
6717{
6718 register Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
6719 register Py_UNICODE *e;
6720 int previous_is_cased;
6721
6722 /* Shortcut for single character strings */
6723 if (PyUnicode_GET_SIZE(self) == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006724 Py_UNICODE ch = Py_UNICODE_TOTITLE(*p);
6725 if (*p != ch) {
6726 *p = ch;
6727 return 1;
6728 }
6729 else
6730 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006731 }
Tim Petersced69f82003-09-16 20:30:58 +00006732
Guido van Rossumd57fd912000-03-10 22:53:23 +00006733 e = p + PyUnicode_GET_SIZE(self);
6734 previous_is_cased = 0;
6735 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006736 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00006737
Benjamin Peterson29060642009-01-31 22:14:21 +00006738 if (previous_is_cased)
6739 *p = Py_UNICODE_TOLOWER(ch);
6740 else
6741 *p = Py_UNICODE_TOTITLE(ch);
Tim Petersced69f82003-09-16 20:30:58 +00006742
Benjamin Peterson29060642009-01-31 22:14:21 +00006743 if (Py_UNICODE_ISLOWER(ch) ||
6744 Py_UNICODE_ISUPPER(ch) ||
6745 Py_UNICODE_ISTITLE(ch))
6746 previous_is_cased = 1;
6747 else
6748 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006749 }
6750 return 1;
6751}
6752
Tim Peters8ce9f162004-08-27 01:49:32 +00006753PyObject *
6754PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006755{
Skip Montanaro6543b452004-09-16 03:28:13 +00006756 const Py_UNICODE blank = ' ';
6757 const Py_UNICODE *sep = &blank;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006758 Py_ssize_t seplen = 1;
Tim Peters05eba1f2004-08-27 21:32:02 +00006759 PyUnicodeObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00006760 Py_UNICODE *res_p; /* pointer to free byte in res's string area */
6761 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006762 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
6763 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00006764 PyObject *item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006765 Py_ssize_t sz, i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006766
Tim Peters05eba1f2004-08-27 21:32:02 +00006767 fseq = PySequence_Fast(seq, "");
6768 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006769 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00006770 }
6771
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006772 /* NOTE: the following code can't call back into Python code,
6773 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00006774 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006775
Tim Peters05eba1f2004-08-27 21:32:02 +00006776 seqlen = PySequence_Fast_GET_SIZE(fseq);
6777 /* If empty sequence, return u"". */
6778 if (seqlen == 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006779 res = _PyUnicode_New(0); /* empty sequence; return u"" */
6780 goto Done;
Tim Peters05eba1f2004-08-27 21:32:02 +00006781 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006782 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00006783 /* If singleton sequence with an exact Unicode, return that. */
6784 if (seqlen == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006785 item = items[0];
6786 if (PyUnicode_CheckExact(item)) {
6787 Py_INCREF(item);
6788 res = (PyUnicodeObject *)item;
6789 goto Done;
6790 }
Tim Peters8ce9f162004-08-27 01:49:32 +00006791 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006792 else {
6793 /* Set up sep and seplen */
6794 if (separator == NULL) {
6795 sep = &blank;
6796 seplen = 1;
Tim Peters05eba1f2004-08-27 21:32:02 +00006797 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006798 else {
6799 if (!PyUnicode_Check(separator)) {
6800 PyErr_Format(PyExc_TypeError,
6801 "separator: expected str instance,"
6802 " %.80s found",
6803 Py_TYPE(separator)->tp_name);
6804 goto onError;
6805 }
6806 sep = PyUnicode_AS_UNICODE(separator);
6807 seplen = PyUnicode_GET_SIZE(separator);
Tim Peters05eba1f2004-08-27 21:32:02 +00006808 }
6809 }
6810
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006811 /* There are at least two things to join, or else we have a subclass
6812 * of str in the sequence.
6813 * Do a pre-pass to figure out the total amount of space we'll
6814 * need (sz), and see whether all argument are strings.
6815 */
6816 sz = 0;
6817 for (i = 0; i < seqlen; i++) {
6818 const Py_ssize_t old_sz = sz;
6819 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00006820 if (!PyUnicode_Check(item)) {
6821 PyErr_Format(PyExc_TypeError,
6822 "sequence item %zd: expected str instance,"
6823 " %.80s found",
6824 i, Py_TYPE(item)->tp_name);
6825 goto onError;
6826 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006827 sz += PyUnicode_GET_SIZE(item);
6828 if (i != 0)
6829 sz += seplen;
6830 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
6831 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00006832 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006833 goto onError;
6834 }
6835 }
Tim Petersced69f82003-09-16 20:30:58 +00006836
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006837 res = _PyUnicode_New(sz);
6838 if (res == NULL)
6839 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00006840
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006841 /* Catenate everything. */
6842 res_p = PyUnicode_AS_UNICODE(res);
6843 for (i = 0; i < seqlen; ++i) {
6844 Py_ssize_t itemlen;
6845 item = items[i];
6846 itemlen = PyUnicode_GET_SIZE(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00006847 /* Copy item, and maybe the separator. */
6848 if (i) {
6849 Py_UNICODE_COPY(res_p, sep, seplen);
6850 res_p += seplen;
6851 }
6852 Py_UNICODE_COPY(res_p, PyUnicode_AS_UNICODE(item), itemlen);
6853 res_p += itemlen;
Tim Peters05eba1f2004-08-27 21:32:02 +00006854 }
Tim Peters8ce9f162004-08-27 01:49:32 +00006855
Benjamin Peterson29060642009-01-31 22:14:21 +00006856 Done:
Tim Peters05eba1f2004-08-27 21:32:02 +00006857 Py_DECREF(fseq);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006858 return (PyObject *)res;
6859
Benjamin Peterson29060642009-01-31 22:14:21 +00006860 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00006861 Py_DECREF(fseq);
Tim Peters8ce9f162004-08-27 01:49:32 +00006862 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006863 return NULL;
6864}
6865
Tim Petersced69f82003-09-16 20:30:58 +00006866static
6867PyUnicodeObject *pad(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006868 Py_ssize_t left,
6869 Py_ssize_t right,
6870 Py_UNICODE fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006871{
6872 PyUnicodeObject *u;
6873
6874 if (left < 0)
6875 left = 0;
6876 if (right < 0)
6877 right = 0;
6878
Tim Peters7a29bd52001-09-12 03:03:31 +00006879 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006880 Py_INCREF(self);
6881 return self;
6882 }
6883
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006884 if (left > PY_SSIZE_T_MAX - self->length ||
6885 right > PY_SSIZE_T_MAX - (left + self->length)) {
6886 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
6887 return NULL;
6888 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006889 u = _PyUnicode_New(left + self->length + right);
6890 if (u) {
6891 if (left)
6892 Py_UNICODE_FILL(u->str, fill, left);
6893 Py_UNICODE_COPY(u->str + left, self->str, self->length);
6894 if (right)
6895 Py_UNICODE_FILL(u->str + left + self->length, fill, right);
6896 }
6897
6898 return u;
6899}
6900
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006901PyObject *PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006902{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006903 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006904
6905 string = PyUnicode_FromObject(string);
6906 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006907 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006908
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006909 list = stringlib_splitlines(
6910 (PyObject*) string, PyUnicode_AS_UNICODE(string),
6911 PyUnicode_GET_SIZE(string), keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006912
6913 Py_DECREF(string);
6914 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006915}
6916
Tim Petersced69f82003-09-16 20:30:58 +00006917static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006918PyObject *split(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006919 PyUnicodeObject *substring,
6920 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006921{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006922 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006923 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006924
Guido van Rossumd57fd912000-03-10 22:53:23 +00006925 if (substring == NULL)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006926 return stringlib_split_whitespace(
6927 (PyObject*) self, self->str, self->length, maxcount
6928 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00006929
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006930 return stringlib_split(
6931 (PyObject*) self, self->str, self->length,
6932 substring->str, substring->length,
6933 maxcount
6934 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00006935}
6936
Tim Petersced69f82003-09-16 20:30:58 +00006937static
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006938PyObject *rsplit(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006939 PyUnicodeObject *substring,
6940 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006941{
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006942 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006943 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006944
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006945 if (substring == NULL)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006946 return stringlib_rsplit_whitespace(
6947 (PyObject*) self, self->str, self->length, maxcount
6948 );
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006949
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006950 return stringlib_rsplit(
6951 (PyObject*) self, self->str, self->length,
6952 substring->str, substring->length,
6953 maxcount
6954 );
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006955}
6956
6957static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006958PyObject *replace(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006959 PyUnicodeObject *str1,
6960 PyUnicodeObject *str2,
6961 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006962{
6963 PyUnicodeObject *u;
6964
6965 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006966 maxcount = PY_SSIZE_T_MAX;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006967 else if (maxcount == 0 || self->length == 0)
6968 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006969
Thomas Wouters477c8d52006-05-27 19:21:47 +00006970 if (str1->length == str2->length) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +00006971 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006972 /* same length */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006973 if (str1->length == 0)
6974 goto nothing;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006975 if (str1->length == 1) {
6976 /* replace characters */
6977 Py_UNICODE u1, u2;
6978 if (!findchar(self->str, self->length, str1->str[0]))
6979 goto nothing;
6980 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
6981 if (!u)
6982 return NULL;
6983 Py_UNICODE_COPY(u->str, self->str, self->length);
6984 u1 = str1->str[0];
6985 u2 = str2->str[0];
6986 for (i = 0; i < u->length; i++)
6987 if (u->str[i] == u1) {
6988 if (--maxcount < 0)
6989 break;
6990 u->str[i] = u2;
6991 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006992 } else {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006993 i = stringlib_find(
6994 self->str, self->length, str1->str, str1->length, 0
Guido van Rossumd57fd912000-03-10 22:53:23 +00006995 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00006996 if (i < 0)
6997 goto nothing;
6998 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
6999 if (!u)
7000 return NULL;
7001 Py_UNICODE_COPY(u->str, self->str, self->length);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007002
7003 /* change everything in-place, starting with this one */
7004 Py_UNICODE_COPY(u->str+i, str2->str, str2->length);
7005 i += str1->length;
7006
7007 while ( --maxcount > 0) {
7008 i = stringlib_find(self->str+i, self->length-i,
7009 str1->str, str1->length,
7010 i);
7011 if (i == -1)
7012 break;
7013 Py_UNICODE_COPY(u->str+i, str2->str, str2->length);
7014 i += str1->length;
7015 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007016 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007017 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00007018
Victor Stinnerab1d16b2011-11-22 01:45:37 +01007019 Py_ssize_t n, i, j;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007020 Py_ssize_t product, new_size, delta;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007021 Py_UNICODE *p;
7022
7023 /* replace strings */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007024 n = stringlib_count(self->str, self->length, str1->str, str1->length,
7025 maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007026 if (n == 0)
7027 goto nothing;
7028 /* new_size = self->length + n * (str2->length - str1->length)); */
7029 delta = (str2->length - str1->length);
7030 if (delta == 0) {
7031 new_size = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007032 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00007033 product = n * (str2->length - str1->length);
7034 if ((product / (str2->length - str1->length)) != n) {
7035 PyErr_SetString(PyExc_OverflowError,
7036 "replace string is too long");
7037 return NULL;
7038 }
7039 new_size = self->length + product;
7040 if (new_size < 0) {
7041 PyErr_SetString(PyExc_OverflowError,
7042 "replace string is too long");
7043 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007044 }
7045 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00007046 u = _PyUnicode_New(new_size);
7047 if (!u)
7048 return NULL;
7049 i = 0;
7050 p = u->str;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007051 if (str1->length > 0) {
7052 while (n-- > 0) {
7053 /* look for next match */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007054 j = stringlib_find(self->str+i, self->length-i,
7055 str1->str, str1->length,
7056 i);
7057 if (j == -1)
7058 break;
7059 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00007060 /* copy unchanged part [i:j] */
7061 Py_UNICODE_COPY(p, self->str+i, j-i);
7062 p += j - i;
7063 }
7064 /* copy substitution string */
7065 if (str2->length > 0) {
7066 Py_UNICODE_COPY(p, str2->str, str2->length);
7067 p += str2->length;
7068 }
7069 i = j + str1->length;
7070 }
7071 if (i < self->length)
7072 /* copy tail [i:] */
7073 Py_UNICODE_COPY(p, self->str+i, self->length-i);
7074 } else {
7075 /* interleave */
7076 while (n > 0) {
7077 Py_UNICODE_COPY(p, str2->str, str2->length);
7078 p += str2->length;
7079 if (--n <= 0)
7080 break;
7081 *p++ = self->str[i++];
7082 }
7083 Py_UNICODE_COPY(p, self->str+i, self->length-i);
7084 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007085 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007086 return (PyObject *) u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007087
Benjamin Peterson29060642009-01-31 22:14:21 +00007088 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00007089 /* nothing to replace; return original string (when possible) */
7090 if (PyUnicode_CheckExact(self)) {
7091 Py_INCREF(self);
7092 return (PyObject *) self;
7093 }
7094 return PyUnicode_FromUnicode(self->str, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007095}
7096
7097/* --- Unicode Object Methods --------------------------------------------- */
7098
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007099PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007100 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007101\n\
7102Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007103characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007104
7105static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007106unicode_title(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007107{
Guido van Rossumd57fd912000-03-10 22:53:23 +00007108 return fixup(self, fixtitle);
7109}
7110
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007111PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007112 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007113\n\
7114Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +00007115have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007116
7117static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007118unicode_capitalize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007119{
Guido van Rossumd57fd912000-03-10 22:53:23 +00007120 return fixup(self, fixcapitalize);
7121}
7122
7123#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007124PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007125 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007126\n\
7127Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007128normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007129
7130static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007131unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007132{
7133 PyObject *list;
7134 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007135 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007136
Guido van Rossumd57fd912000-03-10 22:53:23 +00007137 /* Split into words */
7138 list = split(self, NULL, -1);
7139 if (!list)
7140 return NULL;
7141
7142 /* Capitalize each word */
7143 for (i = 0; i < PyList_GET_SIZE(list); i++) {
7144 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00007145 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007146 if (item == NULL)
7147 goto onError;
7148 Py_DECREF(PyList_GET_ITEM(list, i));
7149 PyList_SET_ITEM(list, i, item);
7150 }
7151
7152 /* Join the words to form a new string */
7153 item = PyUnicode_Join(NULL, list);
7154
Benjamin Peterson29060642009-01-31 22:14:21 +00007155 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007156 Py_DECREF(list);
7157 return (PyObject *)item;
7158}
7159#endif
7160
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007161/* Argument converter. Coerces to a single unicode character */
7162
7163static int
7164convert_uc(PyObject *obj, void *addr)
7165{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007166 Py_UNICODE *fillcharloc = (Py_UNICODE *)addr;
7167 PyObject *uniobj;
7168 Py_UNICODE *unistr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007169
Benjamin Peterson14339b62009-01-31 16:36:08 +00007170 uniobj = PyUnicode_FromObject(obj);
7171 if (uniobj == NULL) {
7172 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00007173 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007174 return 0;
7175 }
7176 if (PyUnicode_GET_SIZE(uniobj) != 1) {
7177 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00007178 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007179 Py_DECREF(uniobj);
7180 return 0;
7181 }
7182 unistr = PyUnicode_AS_UNICODE(uniobj);
7183 *fillcharloc = unistr[0];
7184 Py_DECREF(uniobj);
7185 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007186}
7187
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007188PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007189 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007190\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007191Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007192done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007193
7194static PyObject *
7195unicode_center(PyUnicodeObject *self, PyObject *args)
7196{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007197 Py_ssize_t marg, left;
7198 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007199 Py_UNICODE fillchar = ' ';
Guido van Rossumd57fd912000-03-10 22:53:23 +00007200
Thomas Woutersde017742006-02-16 19:34:37 +00007201 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007202 return NULL;
7203
Tim Peters7a29bd52001-09-12 03:03:31 +00007204 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00007205 Py_INCREF(self);
7206 return (PyObject*) self;
7207 }
7208
7209 marg = width - self->length;
7210 left = marg / 2 + (marg & width & 1);
7211
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007212 return (PyObject*) pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007213}
7214
Marc-André Lemburge5034372000-08-08 08:04:29 +00007215#if 0
7216
7217/* This code should go into some future Unicode collation support
7218 module. The basic comparison should compare ordinals on a naive
Georg Brandlc6c31782009-06-08 13:41:29 +00007219 basis (this is what Java does and thus Jython too). */
Marc-André Lemburge5034372000-08-08 08:04:29 +00007220
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007221/* speedy UTF-16 code point order comparison */
7222/* gleaned from: */
7223/* http://www-4.ibm.com/software/developer/library/utf16.html?dwzone=unicode */
7224
Marc-André Lemburge12896e2000-07-07 17:51:08 +00007225static short utf16Fixup[32] =
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007226{
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007227 0, 0, 0, 0, 0, 0, 0, 0,
Tim Petersced69f82003-09-16 20:30:58 +00007228 0, 0, 0, 0, 0, 0, 0, 0,
7229 0, 0, 0, 0, 0, 0, 0, 0,
Marc-André Lemburge12896e2000-07-07 17:51:08 +00007230 0, 0, 0, 0x2000, -0x800, -0x800, -0x800, -0x800
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007231};
7232
Guido van Rossumd57fd912000-03-10 22:53:23 +00007233static int
7234unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
7235{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007236 Py_ssize_t len1, len2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007237
Guido van Rossumd57fd912000-03-10 22:53:23 +00007238 Py_UNICODE *s1 = str1->str;
7239 Py_UNICODE *s2 = str2->str;
7240
7241 len1 = str1->length;
7242 len2 = str2->length;
Tim Petersced69f82003-09-16 20:30:58 +00007243
Guido van Rossumd57fd912000-03-10 22:53:23 +00007244 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00007245 Py_UNICODE c1, c2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007246
7247 c1 = *s1++;
7248 c2 = *s2++;
Fredrik Lundh45714e92001-06-26 16:39:36 +00007249
Benjamin Peterson29060642009-01-31 22:14:21 +00007250 if (c1 > (1<<11) * 26)
7251 c1 += utf16Fixup[c1>>11];
7252 if (c2 > (1<<11) * 26)
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007253 c2 += utf16Fixup[c2>>11];
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007254 /* now c1 and c2 are in UTF-32-compatible order */
Fredrik Lundh45714e92001-06-26 16:39:36 +00007255
7256 if (c1 != c2)
7257 return (c1 < c2) ? -1 : 1;
Tim Petersced69f82003-09-16 20:30:58 +00007258
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007259 len1--; len2--;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007260 }
7261
7262 return (len1 < len2) ? -1 : (len1 != len2);
7263}
7264
Marc-André Lemburge5034372000-08-08 08:04:29 +00007265#else
7266
7267static int
7268unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
7269{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007270 register Py_ssize_t len1, len2;
Marc-André Lemburge5034372000-08-08 08:04:29 +00007271
7272 Py_UNICODE *s1 = str1->str;
7273 Py_UNICODE *s2 = str2->str;
7274
7275 len1 = str1->length;
7276 len2 = str2->length;
Tim Petersced69f82003-09-16 20:30:58 +00007277
Marc-André Lemburge5034372000-08-08 08:04:29 +00007278 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00007279 Py_UNICODE c1, c2;
Marc-André Lemburge5034372000-08-08 08:04:29 +00007280
Fredrik Lundh45714e92001-06-26 16:39:36 +00007281 c1 = *s1++;
7282 c2 = *s2++;
7283
7284 if (c1 != c2)
7285 return (c1 < c2) ? -1 : 1;
7286
Marc-André Lemburge5034372000-08-08 08:04:29 +00007287 len1--; len2--;
7288 }
7289
7290 return (len1 < len2) ? -1 : (len1 != len2);
7291}
7292
7293#endif
7294
Guido van Rossumd57fd912000-03-10 22:53:23 +00007295int PyUnicode_Compare(PyObject *left,
Benjamin Peterson29060642009-01-31 22:14:21 +00007296 PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007297{
Guido van Rossum09dc34f2007-05-04 04:17:33 +00007298 if (PyUnicode_Check(left) && PyUnicode_Check(right))
7299 return unicode_compare((PyUnicodeObject *)left,
7300 (PyUnicodeObject *)right);
Guido van Rossum09dc34f2007-05-04 04:17:33 +00007301 PyErr_Format(PyExc_TypeError,
7302 "Can't compare %.100s and %.100s",
7303 left->ob_type->tp_name,
7304 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007305 return -1;
7306}
7307
Martin v. Löwis5b222132007-06-10 09:51:05 +00007308int
7309PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
7310{
7311 int i;
7312 Py_UNICODE *id;
7313 assert(PyUnicode_Check(uni));
7314 id = PyUnicode_AS_UNICODE(uni);
7315 /* Compare Unicode string and source character set string */
7316 for (i = 0; id[i] && str[i]; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00007317 if (id[i] != str[i])
7318 return ((int)id[i] < (int)str[i]) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +00007319 /* This check keeps Python strings that end in '\0' from comparing equal
7320 to C strings identical up to that point. */
Benjamin Petersona23831f2010-04-25 21:54:00 +00007321 if (PyUnicode_GET_SIZE(uni) != i || id[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00007322 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00007323 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00007324 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00007325 return 0;
7326}
7327
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007328
Benjamin Peterson29060642009-01-31 22:14:21 +00007329#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +00007330 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007331
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007332PyObject *PyUnicode_RichCompare(PyObject *left,
7333 PyObject *right,
7334 int op)
7335{
7336 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007337
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007338 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
7339 PyObject *v;
7340 if (((PyUnicodeObject *) left)->length !=
7341 ((PyUnicodeObject *) right)->length) {
7342 if (op == Py_EQ) {
7343 Py_INCREF(Py_False);
7344 return Py_False;
7345 }
7346 if (op == Py_NE) {
7347 Py_INCREF(Py_True);
7348 return Py_True;
7349 }
7350 }
7351 if (left == right)
7352 result = 0;
7353 else
7354 result = unicode_compare((PyUnicodeObject *)left,
7355 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007356
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007357 /* Convert the return value to a Boolean */
7358 switch (op) {
7359 case Py_EQ:
7360 v = TEST_COND(result == 0);
7361 break;
7362 case Py_NE:
7363 v = TEST_COND(result != 0);
7364 break;
7365 case Py_LE:
7366 v = TEST_COND(result <= 0);
7367 break;
7368 case Py_GE:
7369 v = TEST_COND(result >= 0);
7370 break;
7371 case Py_LT:
7372 v = TEST_COND(result == -1);
7373 break;
7374 case Py_GT:
7375 v = TEST_COND(result == 1);
7376 break;
7377 default:
7378 PyErr_BadArgument();
7379 return NULL;
7380 }
7381 Py_INCREF(v);
7382 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007383 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007384
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007385 Py_INCREF(Py_NotImplemented);
7386 return Py_NotImplemented;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007387}
7388
Guido van Rossum403d68b2000-03-13 15:55:09 +00007389int PyUnicode_Contains(PyObject *container,
Benjamin Peterson29060642009-01-31 22:14:21 +00007390 PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +00007391{
Thomas Wouters477c8d52006-05-27 19:21:47 +00007392 PyObject *str, *sub;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007393 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007394
7395 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +00007396 sub = PyUnicode_FromObject(element);
7397 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007398 PyErr_Format(PyExc_TypeError,
7399 "'in <string>' requires string as left operand, not %s",
7400 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007401 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007402 }
7403
Thomas Wouters477c8d52006-05-27 19:21:47 +00007404 str = PyUnicode_FromObject(container);
7405 if (!str) {
7406 Py_DECREF(sub);
7407 return -1;
7408 }
7409
7410 result = stringlib_contains_obj(str, sub);
7411
7412 Py_DECREF(str);
7413 Py_DECREF(sub);
7414
Guido van Rossum403d68b2000-03-13 15:55:09 +00007415 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007416}
7417
Guido van Rossumd57fd912000-03-10 22:53:23 +00007418/* Concat to string or Unicode object giving a new Unicode object. */
7419
7420PyObject *PyUnicode_Concat(PyObject *left,
Benjamin Peterson29060642009-01-31 22:14:21 +00007421 PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007422{
7423 PyUnicodeObject *u = NULL, *v = NULL, *w;
7424
7425 /* Coerce the two arguments */
7426 u = (PyUnicodeObject *)PyUnicode_FromObject(left);
7427 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007428 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007429 v = (PyUnicodeObject *)PyUnicode_FromObject(right);
7430 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007431 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007432
7433 /* Shortcuts */
7434 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007435 Py_DECREF(v);
7436 return (PyObject *)u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007437 }
7438 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007439 Py_DECREF(u);
7440 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007441 }
7442
7443 /* Concat the two Unicode strings */
7444 w = _PyUnicode_New(u->length + v->length);
7445 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007446 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007447 Py_UNICODE_COPY(w->str, u->str, u->length);
7448 Py_UNICODE_COPY(w->str + u->length, v->str, v->length);
7449
7450 Py_DECREF(u);
7451 Py_DECREF(v);
7452 return (PyObject *)w;
7453
Benjamin Peterson29060642009-01-31 22:14:21 +00007454 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007455 Py_XDECREF(u);
7456 Py_XDECREF(v);
7457 return NULL;
7458}
7459
Walter Dörwald1ab83302007-05-18 17:15:44 +00007460void
7461PyUnicode_Append(PyObject **pleft, PyObject *right)
7462{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007463 PyObject *new;
7464 if (*pleft == NULL)
7465 return;
7466 if (right == NULL || !PyUnicode_Check(*pleft)) {
7467 Py_DECREF(*pleft);
7468 *pleft = NULL;
7469 return;
7470 }
7471 new = PyUnicode_Concat(*pleft, right);
7472 Py_DECREF(*pleft);
7473 *pleft = new;
Walter Dörwald1ab83302007-05-18 17:15:44 +00007474}
7475
7476void
7477PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
7478{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007479 PyUnicode_Append(pleft, right);
7480 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +00007481}
7482
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007483PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007484 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007485\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00007486Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007487string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007488interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007489
7490static PyObject *
7491unicode_count(PyUnicodeObject *self, PyObject *args)
7492{
7493 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007494 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007495 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007496 PyObject *result;
7497
Jesus Ceaac451502011-04-20 17:09:23 +02007498 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
7499 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +00007500 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007501
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007502 ADJUST_INDICES(start, end, self->length);
Christian Heimes217cfd12007-12-02 14:31:20 +00007503 result = PyLong_FromSsize_t(
Thomas Wouters477c8d52006-05-27 19:21:47 +00007504 stringlib_count(self->str + start, end - start,
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007505 substring->str, substring->length,
7506 PY_SSIZE_T_MAX)
Thomas Wouters477c8d52006-05-27 19:21:47 +00007507 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007508
7509 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007510
Guido van Rossumd57fd912000-03-10 22:53:23 +00007511 return result;
7512}
7513
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007514PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +00007515 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007516\n\
Victor Stinnere14e2122010-11-07 18:41:46 +00007517Encode S using the codec registered for encoding. Default encoding\n\
7518is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +00007519handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007520a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
7521'xmlcharrefreplace' as well as any other name registered with\n\
7522codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007523
7524static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +00007525unicode_encode(PyUnicodeObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007526{
Benjamin Peterson308d6372009-09-18 21:42:35 +00007527 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +00007528 char *encoding = NULL;
7529 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +00007530
Benjamin Peterson308d6372009-09-18 21:42:35 +00007531 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
7532 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007533 return NULL;
Georg Brandl3b9406b2010-12-03 07:54:09 +00007534 return PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007535}
7536
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007537PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007538 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007539\n\
7540Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007541If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007542
7543static PyObject*
7544unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
7545{
7546 Py_UNICODE *e;
7547 Py_UNICODE *p;
7548 Py_UNICODE *q;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007549 Py_UNICODE *qe;
7550 Py_ssize_t i, j, incr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007551 PyUnicodeObject *u;
7552 int tabsize = 8;
7553
7554 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00007555 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007556
Thomas Wouters7e474022000-07-16 12:04:32 +00007557 /* First pass: determine size of output string */
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007558 i = 0; /* chars up to and including most recent \n or \r */
7559 j = 0; /* chars since most recent \n or \r (use in tab calculations) */
7560 e = self->str + self->length; /* end of input */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007561 for (p = self->str; p < e; p++)
7562 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007563 if (tabsize > 0) {
7564 incr = tabsize - (j % tabsize); /* cannot overflow */
7565 if (j > PY_SSIZE_T_MAX - incr)
7566 goto overflow1;
7567 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007568 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007569 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007570 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007571 if (j > PY_SSIZE_T_MAX - 1)
7572 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007573 j++;
7574 if (*p == '\n' || *p == '\r') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007575 if (i > PY_SSIZE_T_MAX - j)
7576 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007577 i += j;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007578 j = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007579 }
7580 }
7581
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007582 if (i > PY_SSIZE_T_MAX - j)
Benjamin Peterson29060642009-01-31 22:14:21 +00007583 goto overflow1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007584
Guido van Rossumd57fd912000-03-10 22:53:23 +00007585 /* Second pass: create output string and fill it */
7586 u = _PyUnicode_New(i + j);
7587 if (!u)
7588 return NULL;
7589
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007590 j = 0; /* same as in first pass */
7591 q = u->str; /* next output char */
7592 qe = u->str + u->length; /* end of output */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007593
7594 for (p = self->str; p < e; p++)
7595 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007596 if (tabsize > 0) {
7597 i = tabsize - (j % tabsize);
7598 j += i;
7599 while (i--) {
7600 if (q >= qe)
7601 goto overflow2;
7602 *q++ = ' ';
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007603 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007604 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007605 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007606 else {
7607 if (q >= qe)
7608 goto overflow2;
7609 *q++ = *p;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007610 j++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007611 if (*p == '\n' || *p == '\r')
7612 j = 0;
7613 }
7614
7615 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007616
7617 overflow2:
7618 Py_DECREF(u);
7619 overflow1:
7620 PyErr_SetString(PyExc_OverflowError, "new string is too long");
7621 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007622}
7623
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007624PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007625 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007626\n\
7627Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08007628such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007629arguments start and end are interpreted as in slice notation.\n\
7630\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007631Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007632
7633static PyObject *
7634unicode_find(PyUnicodeObject *self, PyObject *args)
7635{
Jesus Ceaac451502011-04-20 17:09:23 +02007636 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00007637 Py_ssize_t start;
7638 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007639 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007640
Jesus Ceaac451502011-04-20 17:09:23 +02007641 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
7642 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007643 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007644
Thomas Wouters477c8d52006-05-27 19:21:47 +00007645 result = stringlib_find_slice(
7646 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
7647 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
7648 start, end
7649 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007650
7651 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007652
Christian Heimes217cfd12007-12-02 14:31:20 +00007653 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007654}
7655
7656static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00007657unicode_getitem(PyUnicodeObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007658{
7659 if (index < 0 || index >= self->length) {
7660 PyErr_SetString(PyExc_IndexError, "string index out of range");
7661 return NULL;
7662 }
7663
7664 return (PyObject*) PyUnicode_FromUnicode(&self->str[index], 1);
7665}
7666
Guido van Rossumc2504932007-09-18 19:42:40 +00007667/* Believe it or not, this produces the same value for ASCII strings
7668 as string_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00007669static Py_hash_t
Neil Schemenauerf8c37d12007-09-07 20:49:04 +00007670unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007671{
Guido van Rossumc2504932007-09-18 19:42:40 +00007672 Py_ssize_t len;
7673 Py_UNICODE *p;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00007674 Py_hash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +00007675
Benjamin Peterson69e97272012-02-21 11:08:50 -05007676 assert(_Py_HashSecret_Initialized);
Guido van Rossumc2504932007-09-18 19:42:40 +00007677 if (self->hash != -1)
7678 return self->hash;
Christian Heimes90aa7642007-12-19 02:45:37 +00007679 len = Py_SIZE(self);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01007680 /*
7681 We make the hash of the empty string be 0, rather than using
7682 (prefix ^ suffix), since this slightly obfuscates the hash secret
7683 */
7684 if (len == 0) {
7685 self->hash = 0;
7686 return 0;
7687 }
Guido van Rossumc2504932007-09-18 19:42:40 +00007688 p = self->str;
Georg Brandl2daf6ae2012-02-20 19:54:16 +01007689 x = _Py_HashSecret.prefix;
7690 x ^= *p << 7;
Guido van Rossumc2504932007-09-18 19:42:40 +00007691 while (--len >= 0)
Gregory P. Smith63e6c322012-01-14 15:31:34 -08007692 x = (_PyHASH_MULTIPLIER*x) ^ *p++;
Christian Heimes90aa7642007-12-19 02:45:37 +00007693 x ^= Py_SIZE(self);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01007694 x ^= _Py_HashSecret.suffix;
Guido van Rossumc2504932007-09-18 19:42:40 +00007695 if (x == -1)
7696 x = -2;
7697 self->hash = x;
7698 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007699}
7700
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007701PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007702 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007703\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007704Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007705
7706static PyObject *
7707unicode_index(PyUnicodeObject *self, PyObject *args)
7708{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007709 Py_ssize_t result;
Jesus Ceaac451502011-04-20 17:09:23 +02007710 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00007711 Py_ssize_t start;
7712 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007713
Jesus Ceaac451502011-04-20 17:09:23 +02007714 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
7715 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007716 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007717
Thomas Wouters477c8d52006-05-27 19:21:47 +00007718 result = stringlib_find_slice(
7719 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
7720 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
7721 start, end
7722 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007723
7724 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007725
Guido van Rossumd57fd912000-03-10 22:53:23 +00007726 if (result < 0) {
7727 PyErr_SetString(PyExc_ValueError, "substring not found");
7728 return NULL;
7729 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00007730
Christian Heimes217cfd12007-12-02 14:31:20 +00007731 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007732}
7733
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007734PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007735 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007736\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007737Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007738at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007739
7740static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007741unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007742{
7743 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7744 register const Py_UNICODE *e;
7745 int cased;
7746
Guido van Rossumd57fd912000-03-10 22:53:23 +00007747 /* Shortcut for single character strings */
7748 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007749 return PyBool_FromLong(Py_UNICODE_ISLOWER(*p));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007750
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007751 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007752 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007753 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007754
Guido van Rossumd57fd912000-03-10 22:53:23 +00007755 e = p + PyUnicode_GET_SIZE(self);
7756 cased = 0;
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007757 while (p < e) {
7758 const Py_UCS4 ch = _Py_UNICODE_NEXT(p, e);
Tim Petersced69f82003-09-16 20:30:58 +00007759
Benjamin Peterson29060642009-01-31 22:14:21 +00007760 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
7761 return PyBool_FromLong(0);
7762 else if (!cased && Py_UNICODE_ISLOWER(ch))
7763 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007764 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007765 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007766}
7767
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007768PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007769 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007770\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007771Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007772at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007773
7774static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007775unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007776{
7777 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7778 register const Py_UNICODE *e;
7779 int cased;
7780
Guido van Rossumd57fd912000-03-10 22:53:23 +00007781 /* Shortcut for single character strings */
7782 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007783 return PyBool_FromLong(Py_UNICODE_ISUPPER(*p) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007784
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007785 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007786 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007787 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007788
Guido van Rossumd57fd912000-03-10 22:53:23 +00007789 e = p + PyUnicode_GET_SIZE(self);
7790 cased = 0;
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007791 while (p < e) {
7792 const Py_UCS4 ch = _Py_UNICODE_NEXT(p, e);
Tim Petersced69f82003-09-16 20:30:58 +00007793
Benjamin Peterson29060642009-01-31 22:14:21 +00007794 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
7795 return PyBool_FromLong(0);
7796 else if (!cased && Py_UNICODE_ISUPPER(ch))
7797 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007798 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007799 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007800}
7801
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007802PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007803 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007804\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007805Return True if S is a titlecased string and there is at least one\n\
7806character in S, i.e. upper- and titlecase characters may only\n\
7807follow uncased characters and lowercase characters only cased ones.\n\
7808Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007809
7810static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007811unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007812{
7813 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7814 register const Py_UNICODE *e;
7815 int cased, previous_is_cased;
7816
Guido van Rossumd57fd912000-03-10 22:53:23 +00007817 /* Shortcut for single character strings */
7818 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007819 return PyBool_FromLong((Py_UNICODE_ISTITLE(*p) != 0) ||
7820 (Py_UNICODE_ISUPPER(*p) != 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007821
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007822 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007823 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007824 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007825
Guido van Rossumd57fd912000-03-10 22:53:23 +00007826 e = p + PyUnicode_GET_SIZE(self);
7827 cased = 0;
7828 previous_is_cased = 0;
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007829 while (p < e) {
7830 const Py_UCS4 ch = _Py_UNICODE_NEXT(p, e);
Tim Petersced69f82003-09-16 20:30:58 +00007831
Benjamin Peterson29060642009-01-31 22:14:21 +00007832 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
7833 if (previous_is_cased)
7834 return PyBool_FromLong(0);
7835 previous_is_cased = 1;
7836 cased = 1;
7837 }
7838 else if (Py_UNICODE_ISLOWER(ch)) {
7839 if (!previous_is_cased)
7840 return PyBool_FromLong(0);
7841 previous_is_cased = 1;
7842 cased = 1;
7843 }
7844 else
7845 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007846 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007847 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007848}
7849
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007850PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007851 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007852\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007853Return True if all characters in S are whitespace\n\
7854and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007855
7856static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007857unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007858{
7859 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7860 register const Py_UNICODE *e;
7861
Guido van Rossumd57fd912000-03-10 22:53:23 +00007862 /* Shortcut for single character strings */
7863 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007864 Py_UNICODE_ISSPACE(*p))
7865 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007866
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007867 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007868 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007869 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007870
Guido van Rossumd57fd912000-03-10 22:53:23 +00007871 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007872 while (p < e) {
7873 const Py_UCS4 ch = _Py_UNICODE_NEXT(p, e);
7874 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +00007875 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007876 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007877 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007878}
7879
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007880PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007881 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007882\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007883Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007884and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007885
7886static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007887unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007888{
7889 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7890 register const Py_UNICODE *e;
7891
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007892 /* Shortcut for single character strings */
7893 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007894 Py_UNICODE_ISALPHA(*p))
7895 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007896
7897 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007898 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007899 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007900
7901 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007902 while (p < e) {
7903 if (!Py_UNICODE_ISALPHA(_Py_UNICODE_NEXT(p, e)))
Benjamin Peterson29060642009-01-31 22:14:21 +00007904 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007905 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007906 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007907}
7908
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007909PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007910 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007911\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007912Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007913and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007914
7915static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007916unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007917{
7918 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7919 register const Py_UNICODE *e;
7920
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007921 /* Shortcut for single character strings */
7922 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007923 Py_UNICODE_ISALNUM(*p))
7924 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007925
7926 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007927 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007928 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007929
7930 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007931 while (p < e) {
7932 const Py_UCS4 ch = _Py_UNICODE_NEXT(p, e);
7933 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +00007934 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007935 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007936 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007937}
7938
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007939PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007940 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007941\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007942Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007943False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007944
7945static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007946unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007947{
7948 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7949 register const Py_UNICODE *e;
7950
Guido van Rossumd57fd912000-03-10 22:53:23 +00007951 /* Shortcut for single character strings */
7952 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007953 Py_UNICODE_ISDECIMAL(*p))
7954 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007955
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007956 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007957 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007958 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007959
Guido van Rossumd57fd912000-03-10 22:53:23 +00007960 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007961 while (p < e) {
7962 if (!Py_UNICODE_ISDECIMAL(_Py_UNICODE_NEXT(p, e)))
Benjamin Peterson29060642009-01-31 22:14:21 +00007963 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007964 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007965 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007966}
7967
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007968PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007969 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007970\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007971Return True if all characters in S are digits\n\
7972and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007973
7974static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007975unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007976{
7977 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7978 register const Py_UNICODE *e;
7979
Guido van Rossumd57fd912000-03-10 22:53:23 +00007980 /* Shortcut for single character strings */
7981 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007982 Py_UNICODE_ISDIGIT(*p))
7983 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007984
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007985 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007986 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007987 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007988
Guido van Rossumd57fd912000-03-10 22:53:23 +00007989 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007990 while (p < e) {
7991 if (!Py_UNICODE_ISDIGIT(_Py_UNICODE_NEXT(p, e)))
Benjamin Peterson29060642009-01-31 22:14:21 +00007992 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007993 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007994 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007995}
7996
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007997PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007998 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007999\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00008000Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008001False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008002
8003static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008004unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008005{
8006 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
8007 register const Py_UNICODE *e;
8008
Guido van Rossumd57fd912000-03-10 22:53:23 +00008009 /* Shortcut for single character strings */
8010 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00008011 Py_UNICODE_ISNUMERIC(*p))
8012 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008013
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00008014 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00008015 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008016 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00008017
Guido van Rossumd57fd912000-03-10 22:53:23 +00008018 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03008019 while (p < e) {
8020 if (!Py_UNICODE_ISNUMERIC(_Py_UNICODE_NEXT(p, e)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008021 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008022 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00008023 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008024}
8025
Martin v. Löwis47383402007-08-15 07:32:56 +00008026int
8027PyUnicode_IsIdentifier(PyObject *self)
8028{
Benjamin Petersonf413b802011-08-12 22:17:18 -05008029 const Py_UNICODE *p = PyUnicode_AS_UNICODE((PyUnicodeObject*)self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03008030 const Py_UNICODE *e;
8031 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +00008032
8033 /* Special case for empty strings */
Ezio Melotti93e7afc2011-08-22 14:08:38 +03008034 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008035 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +00008036
8037 /* PEP 3131 says that the first character must be in
8038 XID_Start and subsequent characters in XID_Continue,
8039 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +00008040 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +00008041 letters, digits, underscore). However, given the current
8042 definition of XID_Start and XID_Continue, it is sufficient
8043 to check just for these, except that _ must be allowed
8044 as starting an identifier. */
Ezio Melotti93e7afc2011-08-22 14:08:38 +03008045 e = p + PyUnicode_GET_SIZE(self);
8046 first = _Py_UNICODE_NEXT(p, e);
Benjamin Petersonf413b802011-08-12 22:17:18 -05008047 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +00008048 return 0;
8049
Ezio Melotti93e7afc2011-08-22 14:08:38 +03008050 while (p < e)
8051 if (!_PyUnicode_IsXidContinue(_Py_UNICODE_NEXT(p, e)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008052 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +00008053 return 1;
8054}
8055
8056PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008057 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +00008058\n\
8059Return True if S is a valid identifier according\n\
8060to the language definition.");
8061
8062static PyObject*
8063unicode_isidentifier(PyObject *self)
8064{
8065 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
8066}
8067
Georg Brandl559e5d72008-06-11 18:37:52 +00008068PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008069 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +00008070\n\
8071Return True if all characters in S are considered\n\
8072printable in repr() or S is empty, False otherwise.");
8073
8074static PyObject*
8075unicode_isprintable(PyObject *self)
8076{
8077 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
8078 register const Py_UNICODE *e;
8079
8080 /* Shortcut for single character strings */
8081 if (PyUnicode_GET_SIZE(self) == 1 && Py_UNICODE_ISPRINTABLE(*p)) {
8082 Py_RETURN_TRUE;
8083 }
8084
8085 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03008086 while (p < e) {
8087 if (!Py_UNICODE_ISPRINTABLE(_Py_UNICODE_NEXT(p, e))) {
Georg Brandl559e5d72008-06-11 18:37:52 +00008088 Py_RETURN_FALSE;
8089 }
8090 }
8091 Py_RETURN_TRUE;
8092}
8093
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008094PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +00008095 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008096\n\
8097Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +00008098iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008099
8100static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008101unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008102{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008103 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008104}
8105
Martin v. Löwis18e16552006-02-15 17:27:45 +00008106static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +00008107unicode_length(PyUnicodeObject *self)
8108{
8109 return self->length;
8110}
8111
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008112PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008113 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008114\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008115Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008116done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008117
8118static PyObject *
8119unicode_ljust(PyUnicodeObject *self, PyObject *args)
8120{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008121 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008122 Py_UNICODE fillchar = ' ';
8123
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008124 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008125 return NULL;
8126
Tim Peters7a29bd52001-09-12 03:03:31 +00008127 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008128 Py_INCREF(self);
8129 return (PyObject*) self;
8130 }
8131
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008132 return (PyObject*) pad(self, 0, width - self->length, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008133}
8134
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008135PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008136 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008137\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008138Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008139
8140static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008141unicode_lower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008142{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008143 return fixup(self, fixlower);
8144}
8145
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008146#define LEFTSTRIP 0
8147#define RIGHTSTRIP 1
8148#define BOTHSTRIP 2
8149
8150/* Arrays indexed by above */
8151static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
8152
8153#define STRIPNAME(i) (stripformat[i]+3)
8154
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008155/* externally visible for str.strip(unicode) */
8156PyObject *
8157_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
8158{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008159 Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
8160 Py_ssize_t len = PyUnicode_GET_SIZE(self);
8161 Py_UNICODE *sep = PyUnicode_AS_UNICODE(sepobj);
8162 Py_ssize_t seplen = PyUnicode_GET_SIZE(sepobj);
8163 Py_ssize_t i, j;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008164
Benjamin Peterson29060642009-01-31 22:14:21 +00008165 BLOOM_MASK sepmask = make_bloom_mask(sep, seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008166
Benjamin Peterson14339b62009-01-31 16:36:08 +00008167 i = 0;
8168 if (striptype != RIGHTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008169 while (i < len && BLOOM_MEMBER(sepmask, s[i], sep, seplen)) {
8170 i++;
8171 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008172 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008173
Benjamin Peterson14339b62009-01-31 16:36:08 +00008174 j = len;
8175 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008176 do {
8177 j--;
8178 } while (j >= i && BLOOM_MEMBER(sepmask, s[j], sep, seplen));
8179 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008180 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008181
Benjamin Peterson14339b62009-01-31 16:36:08 +00008182 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008183 Py_INCREF(self);
8184 return (PyObject*)self;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008185 }
8186 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008187 return PyUnicode_FromUnicode(s+i, j-i);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008188}
8189
Guido van Rossumd57fd912000-03-10 22:53:23 +00008190
8191static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008192do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008193{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008194 Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
8195 Py_ssize_t len = PyUnicode_GET_SIZE(self), i, j;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008196
Benjamin Peterson14339b62009-01-31 16:36:08 +00008197 i = 0;
8198 if (striptype != RIGHTSTRIP) {
8199 while (i < len && Py_UNICODE_ISSPACE(s[i])) {
8200 i++;
8201 }
8202 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008203
Benjamin Peterson14339b62009-01-31 16:36:08 +00008204 j = len;
8205 if (striptype != LEFTSTRIP) {
8206 do {
8207 j--;
8208 } while (j >= i && Py_UNICODE_ISSPACE(s[j]));
8209 j++;
8210 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008211
Benjamin Peterson14339b62009-01-31 16:36:08 +00008212 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
8213 Py_INCREF(self);
8214 return (PyObject*)self;
8215 }
8216 else
8217 return PyUnicode_FromUnicode(s+i, j-i);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008218}
8219
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008220
8221static PyObject *
8222do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
8223{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008224 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008225
Benjamin Peterson14339b62009-01-31 16:36:08 +00008226 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
8227 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008228
Benjamin Peterson14339b62009-01-31 16:36:08 +00008229 if (sep != NULL && sep != Py_None) {
8230 if (PyUnicode_Check(sep))
8231 return _PyUnicode_XStrip(self, striptype, sep);
8232 else {
8233 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00008234 "%s arg must be None or str",
8235 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +00008236 return NULL;
8237 }
8238 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008239
Benjamin Peterson14339b62009-01-31 16:36:08 +00008240 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008241}
8242
8243
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008244PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008245 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008246\n\
8247Return a copy of the string S with leading and trailing\n\
8248whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008249If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008250
8251static PyObject *
8252unicode_strip(PyUnicodeObject *self, PyObject *args)
8253{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008254 if (PyTuple_GET_SIZE(args) == 0)
8255 return do_strip(self, BOTHSTRIP); /* Common case */
8256 else
8257 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008258}
8259
8260
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008261PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008262 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008263\n\
8264Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008265If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008266
8267static PyObject *
8268unicode_lstrip(PyUnicodeObject *self, PyObject *args)
8269{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008270 if (PyTuple_GET_SIZE(args) == 0)
8271 return do_strip(self, LEFTSTRIP); /* Common case */
8272 else
8273 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008274}
8275
8276
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008277PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008278 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008279\n\
8280Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008281If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008282
8283static PyObject *
8284unicode_rstrip(PyUnicodeObject *self, PyObject *args)
8285{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008286 if (PyTuple_GET_SIZE(args) == 0)
8287 return do_strip(self, RIGHTSTRIP); /* Common case */
8288 else
8289 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008290}
8291
8292
Guido van Rossumd57fd912000-03-10 22:53:23 +00008293static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +00008294unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008295{
8296 PyUnicodeObject *u;
8297 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008298 Py_ssize_t nchars;
Tim Peters8f422462000-09-09 06:13:41 +00008299 size_t nbytes;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008300
Georg Brandl222de0f2009-04-12 12:01:50 +00008301 if (len < 1) {
8302 Py_INCREF(unicode_empty);
8303 return (PyObject *)unicode_empty;
8304 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008305
Tim Peters7a29bd52001-09-12 03:03:31 +00008306 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008307 /* no repeat, return original string */
8308 Py_INCREF(str);
8309 return (PyObject*) str;
8310 }
Tim Peters8f422462000-09-09 06:13:41 +00008311
8312 /* ensure # of chars needed doesn't overflow int and # of bytes
8313 * needed doesn't overflow size_t
8314 */
8315 nchars = len * str->length;
Georg Brandl222de0f2009-04-12 12:01:50 +00008316 if (nchars / len != str->length) {
Tim Peters8f422462000-09-09 06:13:41 +00008317 PyErr_SetString(PyExc_OverflowError,
8318 "repeated string is too long");
8319 return NULL;
8320 }
8321 nbytes = (nchars + 1) * sizeof(Py_UNICODE);
8322 if (nbytes / sizeof(Py_UNICODE) != (size_t)(nchars + 1)) {
8323 PyErr_SetString(PyExc_OverflowError,
8324 "repeated string is too long");
8325 return NULL;
8326 }
8327 u = _PyUnicode_New(nchars);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008328 if (!u)
8329 return NULL;
8330
8331 p = u->str;
8332
Georg Brandl222de0f2009-04-12 12:01:50 +00008333 if (str->length == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00008334 Py_UNICODE_FILL(p, str->str[0], len);
8335 } else {
Georg Brandl222de0f2009-04-12 12:01:50 +00008336 Py_ssize_t done = str->length; /* number of characters copied this far */
8337 Py_UNICODE_COPY(p, str->str, str->length);
Benjamin Peterson29060642009-01-31 22:14:21 +00008338 while (done < nchars) {
Christian Heimescc47b052008-03-25 14:56:36 +00008339 Py_ssize_t n = (done <= nchars-done) ? done : nchars-done;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008340 Py_UNICODE_COPY(p+done, p, n);
8341 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00008342 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008343 }
8344
8345 return (PyObject*) u;
8346}
8347
8348PyObject *PyUnicode_Replace(PyObject *obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00008349 PyObject *subobj,
8350 PyObject *replobj,
8351 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008352{
8353 PyObject *self;
8354 PyObject *str1;
8355 PyObject *str2;
8356 PyObject *result;
8357
8358 self = PyUnicode_FromObject(obj);
8359 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008360 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008361 str1 = PyUnicode_FromObject(subobj);
8362 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008363 Py_DECREF(self);
8364 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008365 }
8366 str2 = PyUnicode_FromObject(replobj);
8367 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008368 Py_DECREF(self);
8369 Py_DECREF(str1);
8370 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008371 }
Tim Petersced69f82003-09-16 20:30:58 +00008372 result = replace((PyUnicodeObject *)self,
Benjamin Peterson29060642009-01-31 22:14:21 +00008373 (PyUnicodeObject *)str1,
8374 (PyUnicodeObject *)str2,
8375 maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008376 Py_DECREF(self);
8377 Py_DECREF(str1);
8378 Py_DECREF(str2);
8379 return result;
8380}
8381
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008382PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +00008383 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008384\n\
8385Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +00008386old replaced by new. If the optional argument count is\n\
8387given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008388
8389static PyObject*
8390unicode_replace(PyUnicodeObject *self, PyObject *args)
8391{
8392 PyUnicodeObject *str1;
8393 PyUnicodeObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008394 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008395 PyObject *result;
8396
Martin v. Löwis18e16552006-02-15 17:27:45 +00008397 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008398 return NULL;
8399 str1 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str1);
8400 if (str1 == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008401 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008402 str2 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str2);
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +00008403 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008404 Py_DECREF(str1);
8405 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +00008406 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008407
8408 result = replace(self, str1, str2, maxcount);
8409
8410 Py_DECREF(str1);
8411 Py_DECREF(str2);
8412 return result;
8413}
8414
8415static
8416PyObject *unicode_repr(PyObject *unicode)
8417{
Walter Dörwald79e913e2007-05-12 11:08:06 +00008418 PyObject *repr;
Walter Dörwald1ab83302007-05-18 17:15:44 +00008419 Py_UNICODE *p;
Walter Dörwald79e913e2007-05-12 11:08:06 +00008420 Py_UNICODE *s = PyUnicode_AS_UNICODE(unicode);
8421 Py_ssize_t size = PyUnicode_GET_SIZE(unicode);
8422
8423 /* XXX(nnorwitz): rather than over-allocating, it would be
8424 better to choose a different scheme. Perhaps scan the
8425 first N-chars of the string and allocate based on that size.
8426 */
8427 /* Initial allocation is based on the longest-possible unichr
8428 escape.
8429
8430 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
8431 unichr, so in this case it's the longest unichr escape. In
8432 narrow (UTF-16) builds this is five chars per source unichr
8433 since there are two unichrs in the surrogate pair, so in narrow
8434 (UTF-16) builds it's not the longest unichr escape.
8435
8436 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
8437 so in the narrow (UTF-16) build case it's the longest unichr
8438 escape.
8439 */
8440
Walter Dörwald1ab83302007-05-18 17:15:44 +00008441 repr = PyUnicode_FromUnicode(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00008442 2 /* quotes */
Walter Dörwald79e913e2007-05-12 11:08:06 +00008443#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00008444 + 10*size
Walter Dörwald79e913e2007-05-12 11:08:06 +00008445#else
Benjamin Peterson29060642009-01-31 22:14:21 +00008446 + 6*size
Walter Dörwald79e913e2007-05-12 11:08:06 +00008447#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00008448 + 1);
Walter Dörwald79e913e2007-05-12 11:08:06 +00008449 if (repr == NULL)
8450 return NULL;
8451
Walter Dörwald1ab83302007-05-18 17:15:44 +00008452 p = PyUnicode_AS_UNICODE(repr);
Walter Dörwald79e913e2007-05-12 11:08:06 +00008453
8454 /* Add quote */
8455 *p++ = (findchar(s, size, '\'') &&
8456 !findchar(s, size, '"')) ? '"' : '\'';
8457 while (size-- > 0) {
8458 Py_UNICODE ch = *s++;
8459
8460 /* Escape quotes and backslashes */
Walter Dörwald1ab83302007-05-18 17:15:44 +00008461 if ((ch == PyUnicode_AS_UNICODE(repr)[0]) || (ch == '\\')) {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008462 *p++ = '\\';
Walter Dörwald1ab83302007-05-18 17:15:44 +00008463 *p++ = ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00008464 continue;
8465 }
8466
Benjamin Peterson29060642009-01-31 22:14:21 +00008467 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +00008468 if (ch == '\t') {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008469 *p++ = '\\';
8470 *p++ = 't';
8471 }
8472 else if (ch == '\n') {
8473 *p++ = '\\';
8474 *p++ = 'n';
8475 }
8476 else if (ch == '\r') {
8477 *p++ = '\\';
8478 *p++ = 'r';
8479 }
8480
8481 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +00008482 else if (ch < ' ' || ch == 0x7F) {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008483 *p++ = '\\';
8484 *p++ = 'x';
8485 *p++ = hexdigits[(ch >> 4) & 0x000F];
8486 *p++ = hexdigits[ch & 0x000F];
8487 }
8488
Georg Brandl559e5d72008-06-11 18:37:52 +00008489 /* Copy ASCII characters as-is */
8490 else if (ch < 0x7F) {
8491 *p++ = ch;
8492 }
8493
Benjamin Peterson29060642009-01-31 22:14:21 +00008494 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +00008495 else {
8496 Py_UCS4 ucs = ch;
8497
8498#ifndef Py_UNICODE_WIDE
8499 Py_UNICODE ch2 = 0;
8500 /* Get code point from surrogate pair */
8501 if (size > 0) {
8502 ch2 = *s;
8503 if (ch >= 0xD800 && ch < 0xDC00 && ch2 >= 0xDC00
Benjamin Peterson29060642009-01-31 22:14:21 +00008504 && ch2 <= 0xDFFF) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008505 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF))
Benjamin Peterson29060642009-01-31 22:14:21 +00008506 + 0x00010000;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008507 s++;
Georg Brandl559e5d72008-06-11 18:37:52 +00008508 size--;
8509 }
8510 }
8511#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00008512 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +00008513 (categories Z* and C* except ASCII space)
8514 */
8515 if (!Py_UNICODE_ISPRINTABLE(ucs)) {
8516 /* Map 8-bit characters to '\xhh' */
8517 if (ucs <= 0xff) {
8518 *p++ = '\\';
8519 *p++ = 'x';
8520 *p++ = hexdigits[(ch >> 4) & 0x000F];
8521 *p++ = hexdigits[ch & 0x000F];
8522 }
8523 /* Map 21-bit characters to '\U00xxxxxx' */
8524 else if (ucs >= 0x10000) {
8525 *p++ = '\\';
8526 *p++ = 'U';
8527 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
8528 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
8529 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
8530 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
8531 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
8532 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
8533 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
8534 *p++ = hexdigits[ucs & 0x0000000F];
8535 }
8536 /* Map 16-bit characters to '\uxxxx' */
8537 else {
8538 *p++ = '\\';
8539 *p++ = 'u';
8540 *p++ = hexdigits[(ucs >> 12) & 0x000F];
8541 *p++ = hexdigits[(ucs >> 8) & 0x000F];
8542 *p++ = hexdigits[(ucs >> 4) & 0x000F];
8543 *p++ = hexdigits[ucs & 0x000F];
8544 }
8545 }
8546 /* Copy characters as-is */
8547 else {
8548 *p++ = ch;
8549#ifndef Py_UNICODE_WIDE
8550 if (ucs >= 0x10000)
8551 *p++ = ch2;
8552#endif
8553 }
8554 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00008555 }
8556 /* Add quote */
Walter Dörwald1ab83302007-05-18 17:15:44 +00008557 *p++ = PyUnicode_AS_UNICODE(repr)[0];
Walter Dörwald79e913e2007-05-12 11:08:06 +00008558
8559 *p = '\0';
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00008560 PyUnicode_Resize(&repr, p - PyUnicode_AS_UNICODE(repr));
Walter Dörwald79e913e2007-05-12 11:08:06 +00008561 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008562}
8563
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008564PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008565 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008566\n\
8567Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08008568such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008569arguments start and end are interpreted as in slice notation.\n\
8570\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008571Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008572
8573static PyObject *
8574unicode_rfind(PyUnicodeObject *self, PyObject *args)
8575{
Jesus Ceaac451502011-04-20 17:09:23 +02008576 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00008577 Py_ssize_t start;
8578 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008579 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008580
Jesus Ceaac451502011-04-20 17:09:23 +02008581 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
8582 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008583 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008584
Thomas Wouters477c8d52006-05-27 19:21:47 +00008585 result = stringlib_rfind_slice(
8586 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
8587 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
8588 start, end
8589 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008590
8591 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008592
Christian Heimes217cfd12007-12-02 14:31:20 +00008593 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008594}
8595
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008596PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008597 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008598\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008599Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008600
8601static PyObject *
8602unicode_rindex(PyUnicodeObject *self, PyObject *args)
8603{
Jesus Ceaac451502011-04-20 17:09:23 +02008604 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00008605 Py_ssize_t start;
8606 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008607 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008608
Jesus Ceaac451502011-04-20 17:09:23 +02008609 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
8610 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008611 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008612
Thomas Wouters477c8d52006-05-27 19:21:47 +00008613 result = stringlib_rfind_slice(
8614 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
8615 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
8616 start, end
8617 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008618
8619 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008620
Guido van Rossumd57fd912000-03-10 22:53:23 +00008621 if (result < 0) {
8622 PyErr_SetString(PyExc_ValueError, "substring not found");
8623 return NULL;
8624 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008625 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008626}
8627
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008628PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008629 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008630\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008631Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008632done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008633
8634static PyObject *
8635unicode_rjust(PyUnicodeObject *self, PyObject *args)
8636{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008637 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008638 Py_UNICODE fillchar = ' ';
8639
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008640 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008641 return NULL;
8642
Tim Peters7a29bd52001-09-12 03:03:31 +00008643 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008644 Py_INCREF(self);
8645 return (PyObject*) self;
8646 }
8647
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008648 return (PyObject*) pad(self, width - self->length, 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008649}
8650
Guido van Rossumd57fd912000-03-10 22:53:23 +00008651PyObject *PyUnicode_Split(PyObject *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00008652 PyObject *sep,
8653 Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008654{
8655 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008656
Guido van Rossumd57fd912000-03-10 22:53:23 +00008657 s = PyUnicode_FromObject(s);
8658 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008659 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00008660 if (sep != NULL) {
8661 sep = PyUnicode_FromObject(sep);
8662 if (sep == NULL) {
8663 Py_DECREF(s);
8664 return NULL;
8665 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008666 }
8667
8668 result = split((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
8669
8670 Py_DECREF(s);
8671 Py_XDECREF(sep);
8672 return result;
8673}
8674
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008675PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008676 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008677\n\
8678Return a list of the words in S, using sep as the\n\
8679delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00008680splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00008681whitespace string is a separator and empty strings are\n\
8682removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008683
8684static PyObject*
8685unicode_split(PyUnicodeObject *self, PyObject *args)
8686{
8687 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008688 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008689
Martin v. Löwis18e16552006-02-15 17:27:45 +00008690 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008691 return NULL;
8692
8693 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008694 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008695 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00008696 return split(self, (PyUnicodeObject *)substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008697 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008698 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008699}
8700
Thomas Wouters477c8d52006-05-27 19:21:47 +00008701PyObject *
8702PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
8703{
8704 PyObject* str_obj;
8705 PyObject* sep_obj;
8706 PyObject* out;
8707
8708 str_obj = PyUnicode_FromObject(str_in);
8709 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008710 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008711 sep_obj = PyUnicode_FromObject(sep_in);
8712 if (!sep_obj) {
8713 Py_DECREF(str_obj);
8714 return NULL;
8715 }
8716
8717 out = stringlib_partition(
8718 str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
8719 sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
8720 );
8721
8722 Py_DECREF(sep_obj);
8723 Py_DECREF(str_obj);
8724
8725 return out;
8726}
8727
8728
8729PyObject *
8730PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
8731{
8732 PyObject* str_obj;
8733 PyObject* sep_obj;
8734 PyObject* out;
8735
8736 str_obj = PyUnicode_FromObject(str_in);
8737 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008738 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008739 sep_obj = PyUnicode_FromObject(sep_in);
8740 if (!sep_obj) {
8741 Py_DECREF(str_obj);
8742 return NULL;
8743 }
8744
8745 out = stringlib_rpartition(
8746 str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
8747 sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
8748 );
8749
8750 Py_DECREF(sep_obj);
8751 Py_DECREF(str_obj);
8752
8753 return out;
8754}
8755
8756PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008757 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008758\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00008759Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008760the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008761found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00008762
8763static PyObject*
8764unicode_partition(PyUnicodeObject *self, PyObject *separator)
8765{
8766 return PyUnicode_Partition((PyObject *)self, separator);
8767}
8768
8769PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +00008770 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008771\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00008772Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008773the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008774separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00008775
8776static PyObject*
8777unicode_rpartition(PyUnicodeObject *self, PyObject *separator)
8778{
8779 return PyUnicode_RPartition((PyObject *)self, separator);
8780}
8781
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008782PyObject *PyUnicode_RSplit(PyObject *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00008783 PyObject *sep,
8784 Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008785{
8786 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008787
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008788 s = PyUnicode_FromObject(s);
8789 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008790 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00008791 if (sep != NULL) {
8792 sep = PyUnicode_FromObject(sep);
8793 if (sep == NULL) {
8794 Py_DECREF(s);
8795 return NULL;
8796 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008797 }
8798
8799 result = rsplit((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
8800
8801 Py_DECREF(s);
8802 Py_XDECREF(sep);
8803 return result;
8804}
8805
8806PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008807 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008808\n\
8809Return a list of the words in S, using sep as the\n\
8810delimiter string, starting at the end of the string and\n\
8811working to the front. If maxsplit is given, at most maxsplit\n\
8812splits are done. If sep is not specified, any whitespace string\n\
8813is a separator.");
8814
8815static PyObject*
8816unicode_rsplit(PyUnicodeObject *self, PyObject *args)
8817{
8818 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008819 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008820
Martin v. Löwis18e16552006-02-15 17:27:45 +00008821 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008822 return NULL;
8823
8824 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008825 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008826 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00008827 return rsplit(self, (PyUnicodeObject *)substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008828 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008829 return PyUnicode_RSplit((PyObject *)self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008830}
8831
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008832PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008833 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008834\n\
8835Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +00008836Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008837is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008838
8839static PyObject*
8840unicode_splitlines(PyUnicodeObject *self, PyObject *args)
8841{
Guido van Rossum86662912000-04-11 15:38:46 +00008842 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008843
Guido van Rossum86662912000-04-11 15:38:46 +00008844 if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008845 return NULL;
8846
Guido van Rossum86662912000-04-11 15:38:46 +00008847 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008848}
8849
8850static
Guido van Rossumf15a29f2007-05-04 00:41:39 +00008851PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008852{
Walter Dörwald346737f2007-05-31 10:44:43 +00008853 if (PyUnicode_CheckExact(self)) {
8854 Py_INCREF(self);
8855 return self;
8856 } else
8857 /* Subtype -- return genuine unicode string with the same value. */
8858 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(self),
8859 PyUnicode_GET_SIZE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +00008860}
8861
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008862PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008863 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008864\n\
8865Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008866and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008867
8868static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008869unicode_swapcase(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008870{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008871 return fixup(self, fixswapcase);
8872}
8873
Georg Brandlceee0772007-11-27 23:48:05 +00008874PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008875 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +00008876\n\
8877Return a translation table usable for str.translate().\n\
8878If there is only one argument, it must be a dictionary mapping Unicode\n\
8879ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008880Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +00008881If there are two arguments, they must be strings of equal length, and\n\
8882in the resulting dictionary, each character in x will be mapped to the\n\
8883character at the same position in y. If there is a third argument, it\n\
8884must be a string, whose characters will be mapped to None in the result.");
8885
8886static PyObject*
8887unicode_maketrans(PyUnicodeObject *null, PyObject *args)
8888{
8889 PyObject *x, *y = NULL, *z = NULL;
8890 PyObject *new = NULL, *key, *value;
8891 Py_ssize_t i = 0;
8892 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008893
Georg Brandlceee0772007-11-27 23:48:05 +00008894 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
8895 return NULL;
8896 new = PyDict_New();
8897 if (!new)
8898 return NULL;
8899 if (y != NULL) {
8900 /* x must be a string too, of equal length */
8901 Py_ssize_t ylen = PyUnicode_GET_SIZE(y);
8902 if (!PyUnicode_Check(x)) {
8903 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
8904 "be a string if there is a second argument");
8905 goto err;
8906 }
8907 if (PyUnicode_GET_SIZE(x) != ylen) {
8908 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
8909 "arguments must have equal length");
8910 goto err;
8911 }
8912 /* create entries for translating chars in x to those in y */
8913 for (i = 0; i < PyUnicode_GET_SIZE(x); i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +00008914 key = PyLong_FromLong(PyUnicode_AS_UNICODE(x)[i]);
Benjamin Peterson53aa1d72011-12-20 13:29:45 -06008915 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +00008916 goto err;
Benjamin Peterson53aa1d72011-12-20 13:29:45 -06008917 value = PyLong_FromLong(PyUnicode_AS_UNICODE(y)[i]);
8918 if (!value) {
8919 Py_DECREF(key);
8920 goto err;
8921 }
Georg Brandlceee0772007-11-27 23:48:05 +00008922 res = PyDict_SetItem(new, key, value);
8923 Py_DECREF(key);
8924 Py_DECREF(value);
8925 if (res < 0)
8926 goto err;
8927 }
8928 /* create entries for deleting chars in z */
8929 if (z != NULL) {
8930 for (i = 0; i < PyUnicode_GET_SIZE(z); i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +00008931 key = PyLong_FromLong(PyUnicode_AS_UNICODE(z)[i]);
Georg Brandlceee0772007-11-27 23:48:05 +00008932 if (!key)
8933 goto err;
8934 res = PyDict_SetItem(new, key, Py_None);
8935 Py_DECREF(key);
8936 if (res < 0)
8937 goto err;
8938 }
8939 }
8940 } else {
8941 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +00008942 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +00008943 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
8944 "to maketrans it must be a dict");
8945 goto err;
8946 }
8947 /* copy entries into the new dict, converting string keys to int keys */
8948 while (PyDict_Next(x, &i, &key, &value)) {
8949 if (PyUnicode_Check(key)) {
8950 /* convert string keys to integer keys */
8951 PyObject *newkey;
8952 if (PyUnicode_GET_SIZE(key) != 1) {
8953 PyErr_SetString(PyExc_ValueError, "string keys in translate "
8954 "table must be of length 1");
8955 goto err;
8956 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008957 newkey = PyLong_FromLong(PyUnicode_AS_UNICODE(key)[0]);
Georg Brandlceee0772007-11-27 23:48:05 +00008958 if (!newkey)
8959 goto err;
8960 res = PyDict_SetItem(new, newkey, value);
8961 Py_DECREF(newkey);
8962 if (res < 0)
8963 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +00008964 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +00008965 /* just keep integer keys */
8966 if (PyDict_SetItem(new, key, value) < 0)
8967 goto err;
8968 } else {
8969 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
8970 "be strings or integers");
8971 goto err;
8972 }
8973 }
8974 }
8975 return new;
8976 err:
8977 Py_DECREF(new);
8978 return NULL;
8979}
8980
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008981PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008982 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008983\n\
8984Return a copy of the string S, where all characters have been mapped\n\
8985through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008986Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +00008987Unmapped characters are left untouched. Characters mapped to None\n\
8988are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008989
8990static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008991unicode_translate(PyUnicodeObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008992{
Georg Brandlceee0772007-11-27 23:48:05 +00008993 return PyUnicode_TranslateCharmap(self->str, self->length, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008994}
8995
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008996PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008997 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008998\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008999Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009000
9001static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009002unicode_upper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009003{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009004 return fixup(self, fixupper);
9005}
9006
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009007PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009008 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009009\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +00009010Pad a numeric string S with zeros on the left, to fill a field\n\
9011of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009012
9013static PyObject *
9014unicode_zfill(PyUnicodeObject *self, PyObject *args)
9015{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009016 Py_ssize_t fill;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009017 PyUnicodeObject *u;
9018
Martin v. Löwis18e16552006-02-15 17:27:45 +00009019 Py_ssize_t width;
9020 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009021 return NULL;
9022
9023 if (self->length >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +00009024 if (PyUnicode_CheckExact(self)) {
9025 Py_INCREF(self);
9026 return (PyObject*) self;
9027 }
9028 else
9029 return PyUnicode_FromUnicode(
9030 PyUnicode_AS_UNICODE(self),
9031 PyUnicode_GET_SIZE(self)
Benjamin Peterson29060642009-01-31 22:14:21 +00009032 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00009033 }
9034
9035 fill = width - self->length;
9036
9037 u = pad(self, fill, 0, '0');
9038
Walter Dörwald068325e2002-04-15 13:36:47 +00009039 if (u == NULL)
9040 return NULL;
9041
Guido van Rossumd57fd912000-03-10 22:53:23 +00009042 if (u->str[fill] == '+' || u->str[fill] == '-') {
9043 /* move sign to beginning of string */
9044 u->str[0] = u->str[fill];
9045 u->str[fill] = '0';
9046 }
9047
9048 return (PyObject*) u;
9049}
Guido van Rossumd57fd912000-03-10 22:53:23 +00009050
9051#if 0
9052static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009053unicode_freelistsize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009054{
Christian Heimes2202f872008-02-06 14:31:34 +00009055 return PyLong_FromLong(numfree);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009056}
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009057
9058static PyObject *
9059unicode__decimal2ascii(PyObject *self)
9060{
9061 return PyUnicode_TransformDecimalToASCII(PyUnicode_AS_UNICODE(self),
9062 PyUnicode_GET_SIZE(self));
9063}
Guido van Rossumd57fd912000-03-10 22:53:23 +00009064#endif
9065
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009066PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009067 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009068\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00009069Return True if S starts with the specified prefix, False otherwise.\n\
9070With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009071With optional end, stop comparing S at that position.\n\
9072prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009073
9074static PyObject *
9075unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00009076 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009077{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009078 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009079 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009080 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009081 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009082 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009083
Jesus Ceaac451502011-04-20 17:09:23 +02009084 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +00009085 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009086 if (PyTuple_Check(subobj)) {
9087 Py_ssize_t i;
9088 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
9089 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +00009090 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009091 if (substring == NULL)
9092 return NULL;
9093 result = tailmatch(self, substring, start, end, -1);
9094 Py_DECREF(substring);
9095 if (result) {
9096 Py_RETURN_TRUE;
9097 }
9098 }
9099 /* nothing matched */
9100 Py_RETURN_FALSE;
9101 }
9102 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +03009103 if (substring == NULL) {
9104 if (PyErr_ExceptionMatches(PyExc_TypeError))
9105 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
9106 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +00009107 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03009108 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009109 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009110 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009111 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009112}
9113
9114
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009115PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009116 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009117\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00009118Return True if S ends with the specified suffix, False otherwise.\n\
9119With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009120With optional end, stop comparing S at that position.\n\
9121suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009122
9123static PyObject *
9124unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00009125 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009126{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009127 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009128 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009129 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009130 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009131 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009132
Jesus Ceaac451502011-04-20 17:09:23 +02009133 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +00009134 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009135 if (PyTuple_Check(subobj)) {
9136 Py_ssize_t i;
9137 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
9138 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +00009139 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009140 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009141 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009142 result = tailmatch(self, substring, start, end, +1);
9143 Py_DECREF(substring);
9144 if (result) {
9145 Py_RETURN_TRUE;
9146 }
9147 }
9148 Py_RETURN_FALSE;
9149 }
9150 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +03009151 if (substring == NULL) {
9152 if (PyErr_ExceptionMatches(PyExc_TypeError))
9153 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
9154 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +00009155 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03009156 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009157 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009158 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009159 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009160}
9161
Eric Smith8c663262007-08-25 02:26:07 +00009162#include "stringlib/string_format.h"
9163
9164PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009165 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +00009166\n\
Eric Smith51d2fd92010-11-06 19:27:37 +00009167Return a formatted version of S, using substitutions from args and kwargs.\n\
9168The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +00009169
Eric Smith27bbca62010-11-04 17:06:58 +00009170PyDoc_STRVAR(format_map__doc__,
9171 "S.format_map(mapping) -> str\n\
9172\n\
Eric Smith51d2fd92010-11-06 19:27:37 +00009173Return a formatted version of S, using substitutions from mapping.\n\
9174The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +00009175
Eric Smith4a7d76d2008-05-30 18:10:19 +00009176static PyObject *
9177unicode__format__(PyObject* self, PyObject* args)
9178{
9179 PyObject *format_spec;
9180
9181 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
9182 return NULL;
9183
9184 return _PyUnicode_FormatAdvanced(self,
9185 PyUnicode_AS_UNICODE(format_spec),
9186 PyUnicode_GET_SIZE(format_spec));
9187}
9188
Eric Smith8c663262007-08-25 02:26:07 +00009189PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009190 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +00009191\n\
Eric Smith51d2fd92010-11-06 19:27:37 +00009192Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +00009193
9194static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009195unicode__sizeof__(PyUnicodeObject *v)
9196{
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00009197 return PyLong_FromSsize_t(sizeof(PyUnicodeObject) +
9198 sizeof(Py_UNICODE) * (v->length + 1));
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009199}
9200
9201PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009202 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009203
9204static PyObject *
Guido van Rossum5d9113d2003-01-29 17:58:45 +00009205unicode_getnewargs(PyUnicodeObject *v)
9206{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009207 return Py_BuildValue("(u#)", v->str, v->length);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00009208}
9209
Guido van Rossumd57fd912000-03-10 22:53:23 +00009210static PyMethodDef unicode_methods[] = {
9211
9212 /* Order is according to common usage: often used methods should
9213 appear first, since lookup is done sequentially. */
9214
Benjamin Peterson28a4dce2010-12-12 01:33:04 +00009215 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009216 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
9217 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009218 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009219 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
9220 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
9221 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
9222 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
9223 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
9224 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
9225 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00009226 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009227 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
9228 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
9229 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00009230 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009231 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
9232 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
9233 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00009234 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00009235 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009236 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00009237 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009238 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
9239 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
9240 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
9241 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
9242 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
9243 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
9244 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
9245 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
9246 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
9247 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
9248 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
9249 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
9250 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
9251 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +00009252 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +00009253 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009254 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +00009255 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +00009256 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +00009257 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +00009258 {"maketrans", (PyCFunction) unicode_maketrans,
9259 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009260 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +00009261#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009262 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +00009263#endif
9264
9265#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009266 /* These methods are just used for debugging the implementation. */
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009267 {"freelistsize", (PyCFunction) unicode_freelistsize, METH_NOARGS},
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009268 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +00009269#endif
9270
Benjamin Peterson14339b62009-01-31 16:36:08 +00009271 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +00009272 {NULL, NULL}
9273};
9274
Neil Schemenauerce30bc92002-11-18 16:10:18 +00009275static PyObject *
9276unicode_mod(PyObject *v, PyObject *w)
9277{
Benjamin Peterson29060642009-01-31 22:14:21 +00009278 if (!PyUnicode_Check(v)) {
9279 Py_INCREF(Py_NotImplemented);
9280 return Py_NotImplemented;
9281 }
9282 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +00009283}
9284
9285static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009286 0, /*nb_add*/
9287 0, /*nb_subtract*/
9288 0, /*nb_multiply*/
9289 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +00009290};
9291
Guido van Rossumd57fd912000-03-10 22:53:23 +00009292static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009293 (lenfunc) unicode_length, /* sq_length */
9294 PyUnicode_Concat, /* sq_concat */
9295 (ssizeargfunc) unicode_repeat, /* sq_repeat */
9296 (ssizeargfunc) unicode_getitem, /* sq_item */
9297 0, /* sq_slice */
9298 0, /* sq_ass_item */
9299 0, /* sq_ass_slice */
9300 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009301};
9302
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009303static PyObject*
9304unicode_subscript(PyUnicodeObject* self, PyObject* item)
9305{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009306 if (PyIndex_Check(item)) {
9307 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009308 if (i == -1 && PyErr_Occurred())
9309 return NULL;
9310 if (i < 0)
Martin v. Löwisdea59e52006-01-05 10:00:36 +00009311 i += PyUnicode_GET_SIZE(self);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009312 return unicode_getitem(self, i);
9313 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00009314 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009315 Py_UNICODE* source_buf;
9316 Py_UNICODE* result_buf;
9317 PyObject* result;
9318
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00009319 if (PySlice_GetIndicesEx(item, PyUnicode_GET_SIZE(self),
Benjamin Peterson29060642009-01-31 22:14:21 +00009320 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009321 return NULL;
9322 }
9323
9324 if (slicelength <= 0) {
9325 return PyUnicode_FromUnicode(NULL, 0);
Thomas Woutersed03b412007-08-28 21:37:11 +00009326 } else if (start == 0 && step == 1 && slicelength == self->length &&
9327 PyUnicode_CheckExact(self)) {
9328 Py_INCREF(self);
9329 return (PyObject *)self;
9330 } else if (step == 1) {
9331 return PyUnicode_FromUnicode(self->str + start, slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009332 } else {
9333 source_buf = PyUnicode_AS_UNICODE((PyObject*)self);
Christian Heimesb186d002008-03-18 15:15:01 +00009334 result_buf = (Py_UNICODE *)PyObject_MALLOC(slicelength*
9335 sizeof(Py_UNICODE));
Benjamin Peterson14339b62009-01-31 16:36:08 +00009336
Benjamin Peterson29060642009-01-31 22:14:21 +00009337 if (result_buf == NULL)
9338 return PyErr_NoMemory();
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009339
9340 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
9341 result_buf[i] = source_buf[cur];
9342 }
Tim Petersced69f82003-09-16 20:30:58 +00009343
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009344 result = PyUnicode_FromUnicode(result_buf, slicelength);
Christian Heimesb186d002008-03-18 15:15:01 +00009345 PyObject_FREE(result_buf);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009346 return result;
9347 }
9348 } else {
9349 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
9350 return NULL;
9351 }
9352}
9353
9354static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009355 (lenfunc)unicode_length, /* mp_length */
9356 (binaryfunc)unicode_subscript, /* mp_subscript */
9357 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009358};
9359
Guido van Rossumd57fd912000-03-10 22:53:23 +00009360
Guido van Rossumd57fd912000-03-10 22:53:23 +00009361/* Helpers for PyUnicode_Format() */
9362
9363static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00009364getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009365{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009366 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009367 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009368 (*p_argidx)++;
9369 if (arglen < 0)
9370 return args;
9371 else
9372 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009373 }
9374 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009375 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009376 return NULL;
9377}
9378
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009379/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009380
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009381static PyObject *
9382formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009383{
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009384 char *p;
9385 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009386 double x;
Tim Petersced69f82003-09-16 20:30:58 +00009387
Guido van Rossumd57fd912000-03-10 22:53:23 +00009388 x = PyFloat_AsDouble(v);
9389 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009390 return NULL;
9391
Guido van Rossumd57fd912000-03-10 22:53:23 +00009392 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009393 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +00009394
Eric Smith0923d1d2009-04-16 20:16:10 +00009395 p = PyOS_double_to_string(x, type, prec,
9396 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009397 if (p == NULL)
9398 return NULL;
9399 result = PyUnicode_FromStringAndSize(p, strlen(p));
Eric Smith0923d1d2009-04-16 20:16:10 +00009400 PyMem_Free(p);
9401 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009402}
9403
Tim Peters38fd5b62000-09-21 05:43:11 +00009404static PyObject*
9405formatlong(PyObject *val, int flags, int prec, int type)
9406{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009407 char *buf;
9408 int len;
9409 PyObject *str; /* temporary string object. */
9410 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +00009411
Benjamin Peterson14339b62009-01-31 16:36:08 +00009412 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
9413 if (!str)
9414 return NULL;
9415 result = PyUnicode_FromStringAndSize(buf, len);
9416 Py_DECREF(str);
9417 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +00009418}
9419
Guido van Rossumd57fd912000-03-10 22:53:23 +00009420static int
9421formatchar(Py_UNICODE *buf,
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009422 size_t buflen,
9423 PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009424{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00009425 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009426 if (PyUnicode_Check(v)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009427 if (PyUnicode_GET_SIZE(v) == 1) {
9428 buf[0] = PyUnicode_AS_UNICODE(v)[0];
9429 buf[1] = '\0';
9430 return 1;
9431 }
9432#ifndef Py_UNICODE_WIDE
9433 if (PyUnicode_GET_SIZE(v) == 2) {
9434 /* Decode a valid surrogate pair */
9435 int c0 = PyUnicode_AS_UNICODE(v)[0];
9436 int c1 = PyUnicode_AS_UNICODE(v)[1];
9437 if (0xD800 <= c0 && c0 <= 0xDBFF &&
9438 0xDC00 <= c1 && c1 <= 0xDFFF) {
9439 buf[0] = c0;
9440 buf[1] = c1;
9441 buf[2] = '\0';
9442 return 2;
9443 }
9444 }
9445#endif
9446 goto onError;
9447 }
9448 else {
9449 /* Integer input truncated to a character */
9450 long x;
9451 x = PyLong_AsLong(v);
9452 if (x == -1 && PyErr_Occurred())
9453 goto onError;
9454
9455 if (x < 0 || x > 0x10ffff) {
9456 PyErr_SetString(PyExc_OverflowError,
9457 "%c arg not in range(0x110000)");
9458 return -1;
9459 }
9460
9461#ifndef Py_UNICODE_WIDE
9462 if (x > 0xffff) {
9463 x -= 0x10000;
9464 buf[0] = (Py_UNICODE)(0xD800 | (x >> 10));
9465 buf[1] = (Py_UNICODE)(0xDC00 | (x & 0x3FF));
9466 return 2;
9467 }
9468#endif
9469 buf[0] = (Py_UNICODE) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009470 buf[1] = '\0';
9471 return 1;
9472 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00009473
Benjamin Peterson29060642009-01-31 22:14:21 +00009474 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009475 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009476 "%c requires int or char");
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009477 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009478}
9479
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009480/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009481 FORMATBUFLEN is the length of the buffer in which chars are formatted.
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009482*/
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009483#define FORMATBUFLEN (size_t)10
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009484
Guido van Rossumd57fd912000-03-10 22:53:23 +00009485PyObject *PyUnicode_Format(PyObject *format,
Benjamin Peterson29060642009-01-31 22:14:21 +00009486 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009487{
9488 Py_UNICODE *fmt, *res;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009489 Py_ssize_t fmtcnt, rescnt, reslen, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009490 int args_owned = 0;
9491 PyUnicodeObject *result = NULL;
9492 PyObject *dict = NULL;
9493 PyObject *uformat;
Tim Petersced69f82003-09-16 20:30:58 +00009494
Guido van Rossumd57fd912000-03-10 22:53:23 +00009495 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009496 PyErr_BadInternalCall();
9497 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009498 }
9499 uformat = PyUnicode_FromObject(format);
Fred Drakee4315f52000-05-09 19:53:39 +00009500 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009501 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009502 fmt = PyUnicode_AS_UNICODE(uformat);
9503 fmtcnt = PyUnicode_GET_SIZE(uformat);
9504
9505 reslen = rescnt = fmtcnt + 100;
9506 result = _PyUnicode_New(reslen);
9507 if (result == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009508 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009509 res = PyUnicode_AS_UNICODE(result);
9510
9511 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009512 arglen = PyTuple_Size(args);
9513 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009514 }
9515 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009516 arglen = -1;
9517 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009518 }
Christian Heimes90aa7642007-12-19 02:45:37 +00009519 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +00009520 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +00009521 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009522
9523 while (--fmtcnt >= 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009524 if (*fmt != '%') {
9525 if (--rescnt < 0) {
9526 rescnt = fmtcnt + 100;
9527 reslen += rescnt;
9528 if (_PyUnicode_Resize(&result, reslen) < 0)
9529 goto onError;
9530 res = PyUnicode_AS_UNICODE(result) + reslen - rescnt;
9531 --rescnt;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009532 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009533 *res++ = *fmt++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009534 }
9535 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009536 /* Got a format specifier */
9537 int flags = 0;
9538 Py_ssize_t width = -1;
9539 int prec = -1;
9540 Py_UNICODE c = '\0';
9541 Py_UNICODE fill;
9542 int isnumok;
9543 PyObject *v = NULL;
9544 PyObject *temp = NULL;
9545 Py_UNICODE *pbuf;
9546 Py_UNICODE sign;
9547 Py_ssize_t len;
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009548 Py_UNICODE formatbuf[FORMATBUFLEN]; /* For formatchar() */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009549
Benjamin Peterson29060642009-01-31 22:14:21 +00009550 fmt++;
9551 if (*fmt == '(') {
9552 Py_UNICODE *keystart;
9553 Py_ssize_t keylen;
9554 PyObject *key;
9555 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +00009556
Benjamin Peterson29060642009-01-31 22:14:21 +00009557 if (dict == NULL) {
9558 PyErr_SetString(PyExc_TypeError,
9559 "format requires a mapping");
9560 goto onError;
9561 }
9562 ++fmt;
9563 --fmtcnt;
9564 keystart = fmt;
9565 /* Skip over balanced parentheses */
9566 while (pcount > 0 && --fmtcnt >= 0) {
9567 if (*fmt == ')')
9568 --pcount;
9569 else if (*fmt == '(')
9570 ++pcount;
9571 fmt++;
9572 }
9573 keylen = fmt - keystart - 1;
9574 if (fmtcnt < 0 || pcount > 0) {
9575 PyErr_SetString(PyExc_ValueError,
9576 "incomplete format key");
9577 goto onError;
9578 }
9579#if 0
9580 /* keys are converted to strings using UTF-8 and
9581 then looked up since Python uses strings to hold
9582 variables names etc. in its namespaces and we
9583 wouldn't want to break common idioms. */
9584 key = PyUnicode_EncodeUTF8(keystart,
9585 keylen,
9586 NULL);
9587#else
9588 key = PyUnicode_FromUnicode(keystart, keylen);
9589#endif
9590 if (key == NULL)
9591 goto onError;
9592 if (args_owned) {
9593 Py_DECREF(args);
9594 args_owned = 0;
9595 }
9596 args = PyObject_GetItem(dict, key);
9597 Py_DECREF(key);
9598 if (args == NULL) {
9599 goto onError;
9600 }
9601 args_owned = 1;
9602 arglen = -1;
9603 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009604 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009605 while (--fmtcnt >= 0) {
9606 switch (c = *fmt++) {
9607 case '-': flags |= F_LJUST; continue;
9608 case '+': flags |= F_SIGN; continue;
9609 case ' ': flags |= F_BLANK; continue;
9610 case '#': flags |= F_ALT; continue;
9611 case '0': flags |= F_ZERO; continue;
9612 }
9613 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009614 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009615 if (c == '*') {
9616 v = getnextarg(args, arglen, &argidx);
9617 if (v == NULL)
9618 goto onError;
9619 if (!PyLong_Check(v)) {
9620 PyErr_SetString(PyExc_TypeError,
9621 "* wants int");
9622 goto onError;
9623 }
9624 width = PyLong_AsLong(v);
9625 if (width == -1 && PyErr_Occurred())
9626 goto onError;
9627 if (width < 0) {
9628 flags |= F_LJUST;
9629 width = -width;
9630 }
9631 if (--fmtcnt >= 0)
9632 c = *fmt++;
9633 }
9634 else if (c >= '0' && c <= '9') {
9635 width = c - '0';
9636 while (--fmtcnt >= 0) {
9637 c = *fmt++;
9638 if (c < '0' || c > '9')
9639 break;
9640 if ((width*10) / 10 != width) {
9641 PyErr_SetString(PyExc_ValueError,
9642 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009643 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00009644 }
9645 width = width*10 + (c - '0');
9646 }
9647 }
9648 if (c == '.') {
9649 prec = 0;
9650 if (--fmtcnt >= 0)
9651 c = *fmt++;
9652 if (c == '*') {
9653 v = getnextarg(args, arglen, &argidx);
9654 if (v == NULL)
9655 goto onError;
9656 if (!PyLong_Check(v)) {
9657 PyErr_SetString(PyExc_TypeError,
9658 "* wants int");
9659 goto onError;
9660 }
9661 prec = PyLong_AsLong(v);
9662 if (prec == -1 && PyErr_Occurred())
9663 goto onError;
9664 if (prec < 0)
9665 prec = 0;
9666 if (--fmtcnt >= 0)
9667 c = *fmt++;
9668 }
9669 else if (c >= '0' && c <= '9') {
9670 prec = c - '0';
9671 while (--fmtcnt >= 0) {
Stefan Krah99212f62010-07-19 17:58:26 +00009672 c = *fmt++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009673 if (c < '0' || c > '9')
9674 break;
9675 if ((prec*10) / 10 != prec) {
9676 PyErr_SetString(PyExc_ValueError,
9677 "prec too big");
9678 goto onError;
9679 }
9680 prec = prec*10 + (c - '0');
9681 }
9682 }
9683 } /* prec */
9684 if (fmtcnt >= 0) {
9685 if (c == 'h' || c == 'l' || c == 'L') {
9686 if (--fmtcnt >= 0)
9687 c = *fmt++;
9688 }
9689 }
9690 if (fmtcnt < 0) {
9691 PyErr_SetString(PyExc_ValueError,
9692 "incomplete format");
9693 goto onError;
9694 }
9695 if (c != '%') {
9696 v = getnextarg(args, arglen, &argidx);
9697 if (v == NULL)
9698 goto onError;
9699 }
9700 sign = 0;
9701 fill = ' ';
9702 switch (c) {
9703
9704 case '%':
9705 pbuf = formatbuf;
9706 /* presume that buffer length is at least 1 */
9707 pbuf[0] = '%';
9708 len = 1;
9709 break;
9710
9711 case 's':
9712 case 'r':
9713 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +00009714 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +00009715 temp = v;
9716 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009717 }
9718 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009719 if (c == 's')
9720 temp = PyObject_Str(v);
9721 else if (c == 'r')
9722 temp = PyObject_Repr(v);
9723 else
9724 temp = PyObject_ASCII(v);
9725 if (temp == NULL)
9726 goto onError;
9727 if (PyUnicode_Check(temp))
9728 /* nothing to do */;
9729 else {
9730 Py_DECREF(temp);
9731 PyErr_SetString(PyExc_TypeError,
9732 "%s argument has non-string str()");
9733 goto onError;
9734 }
9735 }
9736 pbuf = PyUnicode_AS_UNICODE(temp);
9737 len = PyUnicode_GET_SIZE(temp);
9738 if (prec >= 0 && len > prec)
9739 len = prec;
9740 break;
9741
9742 case 'i':
9743 case 'd':
9744 case 'u':
9745 case 'o':
9746 case 'x':
9747 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +00009748 isnumok = 0;
9749 if (PyNumber_Check(v)) {
9750 PyObject *iobj=NULL;
9751
9752 if (PyLong_Check(v)) {
9753 iobj = v;
9754 Py_INCREF(iobj);
9755 }
9756 else {
9757 iobj = PyNumber_Long(v);
9758 }
9759 if (iobj!=NULL) {
9760 if (PyLong_Check(iobj)) {
9761 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -07009762 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +00009763 Py_DECREF(iobj);
9764 if (!temp)
9765 goto onError;
9766 pbuf = PyUnicode_AS_UNICODE(temp);
9767 len = PyUnicode_GET_SIZE(temp);
9768 sign = 1;
9769 }
9770 else {
9771 Py_DECREF(iobj);
9772 }
9773 }
9774 }
9775 if (!isnumok) {
9776 PyErr_Format(PyExc_TypeError,
9777 "%%%c format: a number is required, "
9778 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
9779 goto onError;
9780 }
9781 if (flags & F_ZERO)
9782 fill = '0';
9783 break;
9784
9785 case 'e':
9786 case 'E':
9787 case 'f':
9788 case 'F':
9789 case 'g':
9790 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009791 temp = formatfloat(v, flags, prec, c);
9792 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +00009793 goto onError;
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009794 pbuf = PyUnicode_AS_UNICODE(temp);
9795 len = PyUnicode_GET_SIZE(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +00009796 sign = 1;
9797 if (flags & F_ZERO)
9798 fill = '0';
9799 break;
9800
9801 case 'c':
9802 pbuf = formatbuf;
9803 len = formatchar(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), v);
9804 if (len < 0)
9805 goto onError;
9806 break;
9807
9808 default:
9809 PyErr_Format(PyExc_ValueError,
9810 "unsupported format character '%c' (0x%x) "
9811 "at index %zd",
9812 (31<=c && c<=126) ? (char)c : '?',
9813 (int)c,
9814 (Py_ssize_t)(fmt - 1 -
9815 PyUnicode_AS_UNICODE(uformat)));
9816 goto onError;
9817 }
9818 if (sign) {
9819 if (*pbuf == '-' || *pbuf == '+') {
9820 sign = *pbuf++;
9821 len--;
9822 }
9823 else if (flags & F_SIGN)
9824 sign = '+';
9825 else if (flags & F_BLANK)
9826 sign = ' ';
9827 else
9828 sign = 0;
9829 }
9830 if (width < len)
9831 width = len;
9832 if (rescnt - (sign != 0) < width) {
9833 reslen -= rescnt;
9834 rescnt = width + fmtcnt + 100;
9835 reslen += rescnt;
9836 if (reslen < 0) {
9837 Py_XDECREF(temp);
9838 PyErr_NoMemory();
9839 goto onError;
9840 }
9841 if (_PyUnicode_Resize(&result, reslen) < 0) {
9842 Py_XDECREF(temp);
9843 goto onError;
9844 }
9845 res = PyUnicode_AS_UNICODE(result)
9846 + reslen - rescnt;
9847 }
9848 if (sign) {
9849 if (fill != ' ')
9850 *res++ = sign;
9851 rescnt--;
9852 if (width > len)
9853 width--;
9854 }
9855 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
9856 assert(pbuf[0] == '0');
9857 assert(pbuf[1] == c);
9858 if (fill != ' ') {
9859 *res++ = *pbuf++;
9860 *res++ = *pbuf++;
9861 }
9862 rescnt -= 2;
9863 width -= 2;
9864 if (width < 0)
9865 width = 0;
9866 len -= 2;
9867 }
9868 if (width > len && !(flags & F_LJUST)) {
9869 do {
9870 --rescnt;
9871 *res++ = fill;
9872 } while (--width > len);
9873 }
9874 if (fill == ' ') {
9875 if (sign)
9876 *res++ = sign;
9877 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
9878 assert(pbuf[0] == '0');
9879 assert(pbuf[1] == c);
9880 *res++ = *pbuf++;
9881 *res++ = *pbuf++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009882 }
9883 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009884 Py_UNICODE_COPY(res, pbuf, len);
9885 res += len;
9886 rescnt -= len;
9887 while (--width >= len) {
9888 --rescnt;
9889 *res++ = ' ';
9890 }
9891 if (dict && (argidx < arglen) && c != '%') {
9892 PyErr_SetString(PyExc_TypeError,
9893 "not all arguments converted during string formatting");
Thomas Woutersa96affe2006-03-12 00:29:36 +00009894 Py_XDECREF(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +00009895 goto onError;
9896 }
9897 Py_XDECREF(temp);
9898 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009899 } /* until end */
9900 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009901 PyErr_SetString(PyExc_TypeError,
9902 "not all arguments converted during string formatting");
9903 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009904 }
9905
Thomas Woutersa96affe2006-03-12 00:29:36 +00009906 if (_PyUnicode_Resize(&result, reslen - rescnt) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009907 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009908 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009909 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009910 }
9911 Py_DECREF(uformat);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009912 return (PyObject *)result;
9913
Benjamin Peterson29060642009-01-31 22:14:21 +00009914 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009915 Py_XDECREF(result);
9916 Py_DECREF(uformat);
9917 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009918 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009919 }
9920 return NULL;
9921}
9922
Jeremy Hylton938ace62002-07-17 16:30:39 +00009923static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +00009924unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
9925
Tim Peters6d6c1a32001-08-02 04:15:00 +00009926static PyObject *
9927unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9928{
Benjamin Peterson29060642009-01-31 22:14:21 +00009929 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009930 static char *kwlist[] = {"object", "encoding", "errors", 0};
9931 char *encoding = NULL;
9932 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00009933
Benjamin Peterson14339b62009-01-31 16:36:08 +00009934 if (type != &PyUnicode_Type)
9935 return unicode_subtype_new(type, args, kwds);
9936 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +00009937 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009938 return NULL;
9939 if (x == NULL)
9940 return (PyObject *)_PyUnicode_New(0);
9941 if (encoding == NULL && errors == NULL)
9942 return PyObject_Str(x);
9943 else
Benjamin Peterson29060642009-01-31 22:14:21 +00009944 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +00009945}
9946
Guido van Rossume023fe02001-08-30 03:12:59 +00009947static PyObject *
9948unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9949{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009950 PyUnicodeObject *tmp, *pnew;
9951 Py_ssize_t n;
Guido van Rossume023fe02001-08-30 03:12:59 +00009952
Benjamin Peterson14339b62009-01-31 16:36:08 +00009953 assert(PyType_IsSubtype(type, &PyUnicode_Type));
9954 tmp = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
9955 if (tmp == NULL)
9956 return NULL;
9957 assert(PyUnicode_Check(tmp));
9958 pnew = (PyUnicodeObject *) type->tp_alloc(type, n = tmp->length);
9959 if (pnew == NULL) {
9960 Py_DECREF(tmp);
9961 return NULL;
9962 }
9963 pnew->str = (Py_UNICODE*) PyObject_MALLOC(sizeof(Py_UNICODE) * (n+1));
9964 if (pnew->str == NULL) {
9965 _Py_ForgetReference((PyObject *)pnew);
9966 PyObject_Del(pnew);
9967 Py_DECREF(tmp);
9968 return PyErr_NoMemory();
9969 }
9970 Py_UNICODE_COPY(pnew->str, tmp->str, n+1);
9971 pnew->length = n;
9972 pnew->hash = tmp->hash;
9973 Py_DECREF(tmp);
9974 return (PyObject *)pnew;
Guido van Rossume023fe02001-08-30 03:12:59 +00009975}
9976
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009977PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +00009978 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00009979\n\
Collin Winterd474ce82007-08-07 19:42:11 +00009980Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +00009981encoding defaults to the current default string encoding.\n\
9982errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00009983
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009984static PyObject *unicode_iter(PyObject *seq);
9985
Guido van Rossumd57fd912000-03-10 22:53:23 +00009986PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00009987 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +00009988 "str", /* tp_name */
9989 sizeof(PyUnicodeObject), /* tp_size */
9990 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009991 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009992 (destructor)unicode_dealloc, /* tp_dealloc */
9993 0, /* tp_print */
9994 0, /* tp_getattr */
9995 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00009996 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009997 unicode_repr, /* tp_repr */
9998 &unicode_as_number, /* tp_as_number */
9999 &unicode_as_sequence, /* tp_as_sequence */
10000 &unicode_as_mapping, /* tp_as_mapping */
10001 (hashfunc) unicode_hash, /* tp_hash*/
10002 0, /* tp_call*/
10003 (reprfunc) unicode_str, /* tp_str */
10004 PyObject_GenericGetAttr, /* tp_getattro */
10005 0, /* tp_setattro */
10006 0, /* tp_as_buffer */
10007 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000010008 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000010009 unicode_doc, /* tp_doc */
10010 0, /* tp_traverse */
10011 0, /* tp_clear */
10012 PyUnicode_RichCompare, /* tp_richcompare */
10013 0, /* tp_weaklistoffset */
10014 unicode_iter, /* tp_iter */
10015 0, /* tp_iternext */
10016 unicode_methods, /* tp_methods */
10017 0, /* tp_members */
10018 0, /* tp_getset */
10019 &PyBaseObject_Type, /* tp_base */
10020 0, /* tp_dict */
10021 0, /* tp_descr_get */
10022 0, /* tp_descr_set */
10023 0, /* tp_dictoffset */
10024 0, /* tp_init */
10025 0, /* tp_alloc */
10026 unicode_new, /* tp_new */
10027 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000010028};
10029
10030/* Initialize the Unicode implementation */
10031
Thomas Wouters78890102000-07-22 19:25:51 +000010032void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010033{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000010034 int i;
10035
Thomas Wouters477c8d52006-05-27 19:21:47 +000010036 /* XXX - move this array to unicodectype.c ? */
10037 Py_UNICODE linebreak[] = {
10038 0x000A, /* LINE FEED */
10039 0x000D, /* CARRIAGE RETURN */
10040 0x001C, /* FILE SEPARATOR */
10041 0x001D, /* GROUP SEPARATOR */
10042 0x001E, /* RECORD SEPARATOR */
10043 0x0085, /* NEXT LINE */
10044 0x2028, /* LINE SEPARATOR */
10045 0x2029, /* PARAGRAPH SEPARATOR */
10046 };
10047
Fred Drakee4315f52000-05-09 19:53:39 +000010048 /* Init the implementation */
Christian Heimes2202f872008-02-06 14:31:34 +000010049 free_list = NULL;
10050 numfree = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010051 unicode_empty = _PyUnicode_New(0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000010052 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +000010053 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000010054
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000010055 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000010056 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000010057 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010058 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000010059
10060 /* initialize the linebreak bloom filter */
10061 bloom_linebreak = make_bloom_mask(
10062 linebreak, sizeof(linebreak) / sizeof(linebreak[0])
10063 );
Thomas Wouters0e3f5912006-08-11 14:57:12 +000010064
10065 PyType_Ready(&EncodingMapType);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010066}
10067
10068/* Finalize the Unicode implementation */
10069
Christian Heimesa156e092008-02-16 07:38:31 +000010070int
10071PyUnicode_ClearFreeList(void)
10072{
10073 int freelist_size = numfree;
10074 PyUnicodeObject *u;
10075
10076 for (u = free_list; u != NULL;) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010077 PyUnicodeObject *v = u;
10078 u = *(PyUnicodeObject **)u;
10079 if (v->str)
10080 PyObject_DEL(v->str);
10081 Py_XDECREF(v->defenc);
10082 PyObject_Del(v);
10083 numfree--;
Christian Heimesa156e092008-02-16 07:38:31 +000010084 }
10085 free_list = NULL;
10086 assert(numfree == 0);
10087 return freelist_size;
10088}
10089
Guido van Rossumd57fd912000-03-10 22:53:23 +000010090void
Thomas Wouters78890102000-07-22 19:25:51 +000010091_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010092{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000010093 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010094
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000010095 Py_XDECREF(unicode_empty);
10096 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000010097
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000010098 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010099 if (unicode_latin1[i]) {
10100 Py_DECREF(unicode_latin1[i]);
10101 unicode_latin1[i] = NULL;
10102 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000010103 }
Christian Heimesa156e092008-02-16 07:38:31 +000010104 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000010105}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000010106
Walter Dörwald16807132007-05-25 13:52:07 +000010107void
10108PyUnicode_InternInPlace(PyObject **p)
10109{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010110 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
10111 PyObject *t;
10112 if (s == NULL || !PyUnicode_Check(s))
10113 Py_FatalError(
10114 "PyUnicode_InternInPlace: unicode strings only please!");
10115 /* If it's a subclass, we don't really know what putting
10116 it in the interned dict might do. */
10117 if (!PyUnicode_CheckExact(s))
10118 return;
10119 if (PyUnicode_CHECK_INTERNED(s))
10120 return;
10121 if (interned == NULL) {
10122 interned = PyDict_New();
10123 if (interned == NULL) {
10124 PyErr_Clear(); /* Don't leave an exception */
10125 return;
10126 }
10127 }
10128 /* It might be that the GetItem call fails even
10129 though the key is present in the dictionary,
10130 namely when this happens during a stack overflow. */
10131 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000010132 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010133 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000010134
Benjamin Peterson29060642009-01-31 22:14:21 +000010135 if (t) {
10136 Py_INCREF(t);
10137 Py_DECREF(*p);
10138 *p = t;
10139 return;
10140 }
Walter Dörwald16807132007-05-25 13:52:07 +000010141
Benjamin Peterson14339b62009-01-31 16:36:08 +000010142 PyThreadState_GET()->recursion_critical = 1;
10143 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
10144 PyErr_Clear();
10145 PyThreadState_GET()->recursion_critical = 0;
10146 return;
10147 }
10148 PyThreadState_GET()->recursion_critical = 0;
10149 /* The two references in interned are not counted by refcnt.
10150 The deallocator will take care of this */
10151 Py_REFCNT(s) -= 2;
10152 PyUnicode_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000010153}
10154
10155void
10156PyUnicode_InternImmortal(PyObject **p)
10157{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010158 PyUnicode_InternInPlace(p);
10159 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
10160 PyUnicode_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
10161 Py_INCREF(*p);
10162 }
Walter Dörwald16807132007-05-25 13:52:07 +000010163}
10164
10165PyObject *
10166PyUnicode_InternFromString(const char *cp)
10167{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010168 PyObject *s = PyUnicode_FromString(cp);
10169 if (s == NULL)
10170 return NULL;
10171 PyUnicode_InternInPlace(&s);
10172 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000010173}
10174
10175void _Py_ReleaseInternedUnicodeStrings(void)
10176{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010177 PyObject *keys;
10178 PyUnicodeObject *s;
10179 Py_ssize_t i, n;
10180 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000010181
Benjamin Peterson14339b62009-01-31 16:36:08 +000010182 if (interned == NULL || !PyDict_Check(interned))
10183 return;
10184 keys = PyDict_Keys(interned);
10185 if (keys == NULL || !PyList_Check(keys)) {
10186 PyErr_Clear();
10187 return;
10188 }
Walter Dörwald16807132007-05-25 13:52:07 +000010189
Benjamin Peterson14339b62009-01-31 16:36:08 +000010190 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
10191 detector, interned unicode strings are not forcibly deallocated;
10192 rather, we give them their stolen references back, and then clear
10193 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000010194
Benjamin Peterson14339b62009-01-31 16:36:08 +000010195 n = PyList_GET_SIZE(keys);
10196 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000010197 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010198 for (i = 0; i < n; i++) {
10199 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
10200 switch (s->state) {
10201 case SSTATE_NOT_INTERNED:
10202 /* XXX Shouldn't happen */
10203 break;
10204 case SSTATE_INTERNED_IMMORTAL:
10205 Py_REFCNT(s) += 1;
10206 immortal_size += s->length;
10207 break;
10208 case SSTATE_INTERNED_MORTAL:
10209 Py_REFCNT(s) += 2;
10210 mortal_size += s->length;
10211 break;
10212 default:
10213 Py_FatalError("Inconsistent interned string state.");
10214 }
10215 s->state = SSTATE_NOT_INTERNED;
10216 }
10217 fprintf(stderr, "total size of all interned strings: "
10218 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
10219 "mortal/immortal\n", mortal_size, immortal_size);
10220 Py_DECREF(keys);
10221 PyDict_Clear(interned);
10222 Py_DECREF(interned);
10223 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000010224}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010225
10226
10227/********************* Unicode Iterator **************************/
10228
10229typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010230 PyObject_HEAD
10231 Py_ssize_t it_index;
10232 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010233} unicodeiterobject;
10234
10235static void
10236unicodeiter_dealloc(unicodeiterobject *it)
10237{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010238 _PyObject_GC_UNTRACK(it);
10239 Py_XDECREF(it->it_seq);
10240 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010241}
10242
10243static int
10244unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
10245{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010246 Py_VISIT(it->it_seq);
10247 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010248}
10249
10250static PyObject *
10251unicodeiter_next(unicodeiterobject *it)
10252{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010253 PyUnicodeObject *seq;
10254 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010255
Benjamin Peterson14339b62009-01-31 16:36:08 +000010256 assert(it != NULL);
10257 seq = it->it_seq;
10258 if (seq == NULL)
10259 return NULL;
10260 assert(PyUnicode_Check(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010261
Benjamin Peterson14339b62009-01-31 16:36:08 +000010262 if (it->it_index < PyUnicode_GET_SIZE(seq)) {
10263 item = PyUnicode_FromUnicode(
Benjamin Peterson29060642009-01-31 22:14:21 +000010264 PyUnicode_AS_UNICODE(seq)+it->it_index, 1);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010265 if (item != NULL)
10266 ++it->it_index;
10267 return item;
10268 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010269
Benjamin Peterson14339b62009-01-31 16:36:08 +000010270 Py_DECREF(seq);
10271 it->it_seq = NULL;
10272 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010273}
10274
10275static PyObject *
10276unicodeiter_len(unicodeiterobject *it)
10277{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010278 Py_ssize_t len = 0;
10279 if (it->it_seq)
10280 len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index;
10281 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010282}
10283
10284PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
10285
10286static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010287 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000010288 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000010289 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010290};
10291
10292PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010293 PyVarObject_HEAD_INIT(&PyType_Type, 0)
10294 "str_iterator", /* tp_name */
10295 sizeof(unicodeiterobject), /* tp_basicsize */
10296 0, /* tp_itemsize */
10297 /* methods */
10298 (destructor)unicodeiter_dealloc, /* tp_dealloc */
10299 0, /* tp_print */
10300 0, /* tp_getattr */
10301 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000010302 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000010303 0, /* tp_repr */
10304 0, /* tp_as_number */
10305 0, /* tp_as_sequence */
10306 0, /* tp_as_mapping */
10307 0, /* tp_hash */
10308 0, /* tp_call */
10309 0, /* tp_str */
10310 PyObject_GenericGetAttr, /* tp_getattro */
10311 0, /* tp_setattro */
10312 0, /* tp_as_buffer */
10313 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
10314 0, /* tp_doc */
10315 (traverseproc)unicodeiter_traverse, /* tp_traverse */
10316 0, /* tp_clear */
10317 0, /* tp_richcompare */
10318 0, /* tp_weaklistoffset */
10319 PyObject_SelfIter, /* tp_iter */
10320 (iternextfunc)unicodeiter_next, /* tp_iternext */
10321 unicodeiter_methods, /* tp_methods */
10322 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010323};
10324
10325static PyObject *
10326unicode_iter(PyObject *seq)
10327{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010328 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010329
Benjamin Peterson14339b62009-01-31 16:36:08 +000010330 if (!PyUnicode_Check(seq)) {
10331 PyErr_BadInternalCall();
10332 return NULL;
10333 }
10334 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
10335 if (it == NULL)
10336 return NULL;
10337 it->it_index = 0;
10338 Py_INCREF(seq);
10339 it->it_seq = (PyUnicodeObject *)seq;
10340 _PyObject_GC_TRACK(it);
10341 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010342}
10343
Martin v. Löwis5b222132007-06-10 09:51:05 +000010344size_t
10345Py_UNICODE_strlen(const Py_UNICODE *u)
10346{
10347 int res = 0;
10348 while(*u++)
10349 res++;
10350 return res;
10351}
10352
10353Py_UNICODE*
10354Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
10355{
10356 Py_UNICODE *u = s1;
10357 while ((*u++ = *s2++));
10358 return s1;
10359}
10360
10361Py_UNICODE*
10362Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
10363{
10364 Py_UNICODE *u = s1;
10365 while ((*u++ = *s2++))
10366 if (n-- == 0)
10367 break;
10368 return s1;
10369}
10370
Victor Stinnerc4eb7652010-09-01 23:43:50 +000010371Py_UNICODE*
10372Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
10373{
10374 Py_UNICODE *u1 = s1;
10375 u1 += Py_UNICODE_strlen(u1);
10376 Py_UNICODE_strcpy(u1, s2);
10377 return s1;
10378}
10379
Martin v. Löwis5b222132007-06-10 09:51:05 +000010380int
10381Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
10382{
10383 while (*s1 && *s2 && *s1 == *s2)
10384 s1++, s2++;
10385 if (*s1 && *s2)
10386 return (*s1 < *s2) ? -1 : +1;
10387 if (*s1)
10388 return 1;
10389 if (*s2)
10390 return -1;
10391 return 0;
10392}
10393
Victor Stinneref8d95c2010-08-16 22:03:11 +000010394int
10395Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
10396{
10397 register Py_UNICODE u1, u2;
10398 for (; n != 0; n--) {
10399 u1 = *s1;
10400 u2 = *s2;
10401 if (u1 != u2)
10402 return (u1 < u2) ? -1 : +1;
10403 if (u1 == '\0')
10404 return 0;
10405 s1++;
10406 s2++;
10407 }
10408 return 0;
10409}
10410
Martin v. Löwis5b222132007-06-10 09:51:05 +000010411Py_UNICODE*
10412Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
10413{
10414 const Py_UNICODE *p;
10415 for (p = s; *p; p++)
10416 if (*p == c)
10417 return (Py_UNICODE*)p;
10418 return NULL;
10419}
10420
Victor Stinner331ea922010-08-10 16:37:20 +000010421Py_UNICODE*
10422Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
10423{
10424 const Py_UNICODE *p;
10425 p = s + Py_UNICODE_strlen(s);
10426 while (p != s) {
10427 p--;
10428 if (*p == c)
10429 return (Py_UNICODE*)p;
10430 }
10431 return NULL;
10432}
10433
Victor Stinner71133ff2010-09-01 23:43:53 +000010434Py_UNICODE*
Victor Stinner46408602010-09-03 16:18:00 +000010435PyUnicode_AsUnicodeCopy(PyObject *object)
Victor Stinner71133ff2010-09-01 23:43:53 +000010436{
10437 PyUnicodeObject *unicode = (PyUnicodeObject *)object;
10438 Py_UNICODE *copy;
10439 Py_ssize_t size;
10440
10441 /* Ensure we won't overflow the size. */
10442 if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
10443 PyErr_NoMemory();
10444 return NULL;
10445 }
10446 size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
10447 size *= sizeof(Py_UNICODE);
10448 copy = PyMem_Malloc(size);
10449 if (copy == NULL) {
10450 PyErr_NoMemory();
10451 return NULL;
10452 }
10453 memcpy(copy, PyUnicode_AS_UNICODE(unicode), size);
10454 return copy;
10455}
Martin v. Löwis5b222132007-06-10 09:51:05 +000010456
Georg Brandl66c221e2010-10-14 07:04:07 +000010457/* A _string module, to export formatter_parser and formatter_field_name_split
10458 to the string.Formatter class implemented in Python. */
10459
10460static PyMethodDef _string_methods[] = {
10461 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
10462 METH_O, PyDoc_STR("split the argument as a field name")},
10463 {"formatter_parser", (PyCFunction) formatter_parser,
10464 METH_O, PyDoc_STR("parse the argument as a format string")},
10465 {NULL, NULL}
10466};
10467
10468static struct PyModuleDef _string_module = {
10469 PyModuleDef_HEAD_INIT,
10470 "_string",
10471 PyDoc_STR("string helper module"),
10472 0,
10473 _string_methods,
10474 NULL,
10475 NULL,
10476 NULL,
10477 NULL
10478};
10479
10480PyMODINIT_FUNC
10481PyInit__string(void)
10482{
10483 return PyModule_Create(&_string_module);
10484}
10485
10486
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010487#ifdef __cplusplus
10488}
10489#endif