blob: 7cd039990c7cdb203710314534ca12bb538f51ca [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. */
Victor Stinner20b654a2013-01-03 01:08:58 +01001437int
1438_Py_normalize_encoding(const char *encoding,
Victor Stinner37296e82010-06-10 13:36:23 +00001439 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 Stinner20b654a2013-01-03 01:08:58 +01001480 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Victor Stinner37296e82010-06-10 13:36:23 +00001481 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 Stinner20b654a2013-01-03 01:08:58 +01001698 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Victor Stinner37296e82010-06-10 13:36:23 +00001699 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,
Victor Stinner27b1ca22012-12-03 12:47:59 +01002795 used to decode the command line arguments on Mac OS X.
2796
2797 Return a pointer to a newly allocated wide character string (use
2798 PyMem_Free() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00002799
2800wchar_t*
2801_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
2802{
2803 int n;
2804 const char *e;
2805 wchar_t *unicode, *p;
2806
2807 /* Note: size will always be longer than the resulting Unicode
2808 character count */
Victor Stinner27b1ca22012-12-03 12:47:59 +01002809 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00002810 return NULL;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00002811 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
2812 if (!unicode)
2813 return NULL;
2814
2815 /* Unpack UTF-8 encoded data */
2816 p = unicode;
2817 e = s + size;
2818 while (s < e) {
2819 Py_UCS4 ch = (unsigned char)*s;
2820
2821 if (ch < 0x80) {
2822 *p++ = (wchar_t)ch;
2823 s++;
2824 continue;
2825 }
2826
2827 n = utf8_code_length[ch];
2828 if (s + n > e) {
2829 goto surrogateescape;
2830 }
2831
2832 switch (n) {
2833 case 0:
2834 case 1:
2835 goto surrogateescape;
2836
2837 case 2:
2838 if ((s[1] & 0xc0) != 0x80)
2839 goto surrogateescape;
2840 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
2841 assert ((ch > 0x007F) && (ch <= 0x07FF));
2842 *p++ = (wchar_t)ch;
2843 break;
2844
2845 case 3:
2846 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
2847 will result in surrogates in range d800-dfff. Surrogates are
2848 not valid UTF-8 so they are rejected.
2849 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
2850 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
2851 if ((s[1] & 0xc0) != 0x80 ||
2852 (s[2] & 0xc0) != 0x80 ||
2853 ((unsigned char)s[0] == 0xE0 &&
2854 (unsigned char)s[1] < 0xA0) ||
2855 ((unsigned char)s[0] == 0xED &&
2856 (unsigned char)s[1] > 0x9F)) {
2857
2858 goto surrogateescape;
2859 }
2860 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
2861 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
2862 *p++ = (Py_UNICODE)ch;
2863 break;
2864
2865 case 4:
2866 if ((s[1] & 0xc0) != 0x80 ||
2867 (s[2] & 0xc0) != 0x80 ||
2868 (s[3] & 0xc0) != 0x80 ||
2869 ((unsigned char)s[0] == 0xF0 &&
2870 (unsigned char)s[1] < 0x90) ||
2871 ((unsigned char)s[0] == 0xF4 &&
2872 (unsigned char)s[1] > 0x8F)) {
2873 goto surrogateescape;
2874 }
2875 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
2876 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
2877 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
2878
2879#if SIZEOF_WCHAR_T == 4
2880 *p++ = (wchar_t)ch;
2881#else
2882 /* compute and append the two surrogates: */
2883
2884 /* translate from 10000..10FFFF to 0..FFFF */
2885 ch -= 0x10000;
2886
2887 /* high surrogate = top 10 bits added to D800 */
2888 *p++ = (wchar_t)(0xD800 + (ch >> 10));
2889
2890 /* low surrogate = bottom 10 bits added to DC00 */
2891 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
2892#endif
2893 break;
2894 }
2895 s += n;
2896 continue;
2897
2898 surrogateescape:
2899 *p++ = 0xDC00 + ch;
2900 s++;
2901 }
2902 *p = L'\0';
2903 return unicode;
2904}
2905
2906#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00002907
Tim Peters602f7402002-04-27 18:03:26 +00002908/* Allocation strategy: if the string is short, convert into a stack buffer
2909 and allocate exactly as much space needed at the end. Else allocate the
2910 maximum possible needed (4 result bytes per Unicode character), and return
2911 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002912*/
Tim Peters7e3d9612002-04-21 03:26:37 +00002913PyObject *
2914PyUnicode_EncodeUTF8(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002915 Py_ssize_t size,
2916 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002917{
Tim Peters602f7402002-04-27 18:03:26 +00002918#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00002919
Guido van Rossum98297ee2007-11-06 21:34:58 +00002920 Py_ssize_t i; /* index into s of next input byte */
2921 PyObject *result; /* result string object */
2922 char *p; /* next free byte in output buffer */
2923 Py_ssize_t nallocated; /* number of result bytes allocated */
2924 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00002925 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002926 PyObject *errorHandler = NULL;
2927 PyObject *exc = NULL;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00002928
Tim Peters602f7402002-04-27 18:03:26 +00002929 assert(s != NULL);
2930 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002931
Tim Peters602f7402002-04-27 18:03:26 +00002932 if (size <= MAX_SHORT_UNICHARS) {
2933 /* Write into the stack buffer; nallocated can't overflow.
2934 * At the end, we'll allocate exactly as much heap space as it
2935 * turns out we need.
2936 */
2937 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002938 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00002939 p = stackbuf;
2940 }
2941 else {
2942 /* Overallocate on the heap, and give the excess back at the end. */
2943 nallocated = size * 4;
2944 if (nallocated / 4 != size) /* overflow! */
2945 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00002946 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002947 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00002948 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00002949 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00002950 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002951
Tim Peters602f7402002-04-27 18:03:26 +00002952 for (i = 0; i < size;) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002953 Py_UCS4 ch = s[i++];
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002954
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002955 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00002956 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002957 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002958
Guido van Rossumd57fd912000-03-10 22:53:23 +00002959 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00002960 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00002961 *p++ = (char)(0xc0 | (ch >> 6));
2962 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00002963 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002964#ifndef Py_UNICODE_WIDE
Victor Stinner31be90b2010-04-22 19:38:16 +00002965 /* Special case: check for high and low surrogate */
2966 if (ch <= 0xDBFF && i != size && 0xDC00 <= s[i] && s[i] <= 0xDFFF) {
2967 Py_UCS4 ch2 = s[i];
2968 /* Combine the two surrogates to form a UCS4 value */
2969 ch = ((ch - 0xD800) << 10 | (ch2 - 0xDC00)) + 0x10000;
2970 i++;
2971
2972 /* Encode UCS4 Unicode ordinals */
2973 *p++ = (char)(0xf0 | (ch >> 18));
2974 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
Tim Peters602f7402002-04-27 18:03:26 +00002975 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2976 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00002977 } else {
Victor Stinner445a6232010-04-22 20:01:57 +00002978#endif
Victor Stinner31be90b2010-04-22 19:38:16 +00002979 Py_ssize_t newpos;
2980 PyObject *rep;
2981 Py_ssize_t repsize, k;
2982 rep = unicode_encode_call_errorhandler
2983 (errors, &errorHandler, "utf-8", "surrogates not allowed",
2984 s, size, &exc, i-1, i, &newpos);
2985 if (!rep)
2986 goto error;
2987
2988 if (PyBytes_Check(rep))
2989 repsize = PyBytes_GET_SIZE(rep);
2990 else
2991 repsize = PyUnicode_GET_SIZE(rep);
2992
2993 if (repsize > 4) {
2994 Py_ssize_t offset;
2995
2996 if (result == NULL)
2997 offset = p - stackbuf;
2998 else
2999 offset = p - PyBytes_AS_STRING(result);
3000
3001 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
3002 /* integer overflow */
3003 PyErr_NoMemory();
3004 goto error;
3005 }
3006 nallocated += repsize - 4;
3007 if (result != NULL) {
3008 if (_PyBytes_Resize(&result, nallocated) < 0)
3009 goto error;
3010 } else {
3011 result = PyBytes_FromStringAndSize(NULL, nallocated);
3012 if (result == NULL)
3013 goto error;
3014 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
3015 }
3016 p = PyBytes_AS_STRING(result) + offset;
3017 }
3018
3019 if (PyBytes_Check(rep)) {
3020 char *prep = PyBytes_AS_STRING(rep);
3021 for(k = repsize; k > 0; k--)
3022 *p++ = *prep++;
3023 } else /* rep is unicode */ {
3024 Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
3025 Py_UNICODE c;
3026
3027 for(k=0; k<repsize; k++) {
3028 c = prep[k];
3029 if (0x80 <= c) {
3030 raise_encode_exception(&exc, "utf-8", s, size,
3031 i-1, i, "surrogates not allowed");
3032 goto error;
3033 }
3034 *p++ = (char)prep[k];
3035 }
3036 }
3037 Py_DECREF(rep);
Victor Stinner445a6232010-04-22 20:01:57 +00003038#ifndef Py_UNICODE_WIDE
Victor Stinner31be90b2010-04-22 19:38:16 +00003039 }
Victor Stinner445a6232010-04-22 20:01:57 +00003040#endif
Victor Stinner31be90b2010-04-22 19:38:16 +00003041 } else if (ch < 0x10000) {
3042 *p++ = (char)(0xe0 | (ch >> 12));
3043 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
3044 *p++ = (char)(0x80 | (ch & 0x3f));
3045 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00003046 /* Encode UCS4 Unicode ordinals */
3047 *p++ = (char)(0xf0 | (ch >> 18));
3048 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
3049 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
3050 *p++ = (char)(0x80 | (ch & 0x3f));
3051 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003052 }
Tim Peters0eca65c2002-04-21 17:28:06 +00003053
Guido van Rossum98297ee2007-11-06 21:34:58 +00003054 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00003055 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003056 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00003057 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00003058 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00003059 }
3060 else {
Christian Heimesf3863112007-11-22 07:46:41 +00003061 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00003062 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00003063 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00003064 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00003065 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00003066 Py_XDECREF(errorHandler);
3067 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003068 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00003069 error:
3070 Py_XDECREF(errorHandler);
3071 Py_XDECREF(exc);
3072 Py_XDECREF(result);
3073 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00003074
Tim Peters602f7402002-04-27 18:03:26 +00003075#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00003076}
3077
Guido van Rossumd57fd912000-03-10 22:53:23 +00003078PyObject *PyUnicode_AsUTF8String(PyObject *unicode)
3079{
Guido van Rossumd57fd912000-03-10 22:53:23 +00003080 if (!PyUnicode_Check(unicode)) {
3081 PyErr_BadArgument();
3082 return NULL;
3083 }
Barry Warsaw2dd4abf2000-08-18 06:58:15 +00003084 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003085 PyUnicode_GET_SIZE(unicode),
3086 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003087}
3088
Walter Dörwald41980ca2007-08-16 21:55:45 +00003089/* --- UTF-32 Codec ------------------------------------------------------- */
3090
3091PyObject *
3092PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003093 Py_ssize_t size,
3094 const char *errors,
3095 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00003096{
3097 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
3098}
3099
3100PyObject *
3101PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003102 Py_ssize_t size,
3103 const char *errors,
3104 int *byteorder,
3105 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00003106{
3107 const char *starts = s;
3108 Py_ssize_t startinpos;
3109 Py_ssize_t endinpos;
3110 Py_ssize_t outpos;
3111 PyUnicodeObject *unicode;
3112 Py_UNICODE *p;
3113#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00003114 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00003115 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003116#else
3117 const int pairs = 0;
3118#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00003119 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003120 int bo = 0; /* assume native ordering by default */
3121 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00003122 /* Offsets from q for retrieving bytes in the right order. */
3123#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3124 int iorder[] = {0, 1, 2, 3};
3125#else
3126 int iorder[] = {3, 2, 1, 0};
3127#endif
3128 PyObject *errorHandler = NULL;
3129 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00003130
Walter Dörwald41980ca2007-08-16 21:55:45 +00003131 q = (unsigned char *)s;
3132 e = q + size;
3133
3134 if (byteorder)
3135 bo = *byteorder;
3136
3137 /* Check for BOM marks (U+FEFF) in the input and adjust current
3138 byte order setting accordingly. In native mode, the leading BOM
3139 mark is skipped, in all other modes, it is copied to the output
3140 stream as-is (giving a ZWNBSP character). */
3141 if (bo == 0) {
3142 if (size >= 4) {
3143 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00003144 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00003145#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00003146 if (bom == 0x0000FEFF) {
3147 q += 4;
3148 bo = -1;
3149 }
3150 else if (bom == 0xFFFE0000) {
3151 q += 4;
3152 bo = 1;
3153 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003154#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003155 if (bom == 0x0000FEFF) {
3156 q += 4;
3157 bo = 1;
3158 }
3159 else if (bom == 0xFFFE0000) {
3160 q += 4;
3161 bo = -1;
3162 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003163#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003164 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003165 }
3166
3167 if (bo == -1) {
3168 /* force LE */
3169 iorder[0] = 0;
3170 iorder[1] = 1;
3171 iorder[2] = 2;
3172 iorder[3] = 3;
3173 }
3174 else if (bo == 1) {
3175 /* force BE */
3176 iorder[0] = 3;
3177 iorder[1] = 2;
3178 iorder[2] = 1;
3179 iorder[3] = 0;
3180 }
3181
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00003182 /* On narrow builds we split characters outside the BMP into two
3183 codepoints => count how much extra space we need. */
3184#ifndef Py_UNICODE_WIDE
Serhiy Storchakadec798e2013-01-08 22:45:42 +02003185 for (qq = q; e - qq >= 4; qq += 4)
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00003186 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
3187 pairs++;
3188#endif
3189
3190 /* This might be one to much, because of a BOM */
3191 unicode = _PyUnicode_New((size+3)/4+pairs);
3192 if (!unicode)
3193 return NULL;
3194 if (size == 0)
3195 return (PyObject *)unicode;
3196
3197 /* Unpack UTF-32 encoded data */
3198 p = unicode->str;
3199
Walter Dörwald41980ca2007-08-16 21:55:45 +00003200 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003201 Py_UCS4 ch;
3202 /* remaining bytes at the end? (size should be divisible by 4) */
3203 if (e-q<4) {
3204 if (consumed)
3205 break;
3206 errmsg = "truncated data";
3207 startinpos = ((const char *)q)-starts;
3208 endinpos = ((const char *)e)-starts;
3209 goto utf32Error;
3210 /* The remaining input chars are ignored if the callback
3211 chooses to skip the input */
3212 }
3213 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
3214 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00003215
Benjamin Peterson29060642009-01-31 22:14:21 +00003216 if (ch >= 0x110000)
3217 {
3218 errmsg = "codepoint not in range(0x110000)";
3219 startinpos = ((const char *)q)-starts;
3220 endinpos = startinpos+4;
3221 goto utf32Error;
3222 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003223#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003224 if (ch >= 0x10000)
3225 {
3226 *p++ = 0xD800 | ((ch-0x10000) >> 10);
3227 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
3228 }
3229 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00003230#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003231 *p++ = ch;
3232 q += 4;
3233 continue;
3234 utf32Error:
3235 outpos = p-PyUnicode_AS_UNICODE(unicode);
3236 if (unicode_decode_call_errorhandler(
3237 errors, &errorHandler,
3238 "utf32", errmsg,
3239 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
3240 &unicode, &outpos, &p))
3241 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003242 }
3243
3244 if (byteorder)
3245 *byteorder = bo;
3246
3247 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00003248 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003249
3250 /* Adjust length */
3251 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
3252 goto onError;
3253
3254 Py_XDECREF(errorHandler);
3255 Py_XDECREF(exc);
3256 return (PyObject *)unicode;
3257
Benjamin Peterson29060642009-01-31 22:14:21 +00003258 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00003259 Py_DECREF(unicode);
3260 Py_XDECREF(errorHandler);
3261 Py_XDECREF(exc);
3262 return NULL;
3263}
3264
3265PyObject *
3266PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003267 Py_ssize_t size,
3268 const char *errors,
3269 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00003270{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003271 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003272 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003273 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003274#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003275 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003276#else
3277 const int pairs = 0;
3278#endif
3279 /* Offsets from p for storing byte pairs in the right order. */
3280#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3281 int iorder[] = {0, 1, 2, 3};
3282#else
3283 int iorder[] = {3, 2, 1, 0};
3284#endif
3285
Benjamin Peterson29060642009-01-31 22:14:21 +00003286#define STORECHAR(CH) \
3287 do { \
3288 p[iorder[3]] = ((CH) >> 24) & 0xff; \
3289 p[iorder[2]] = ((CH) >> 16) & 0xff; \
3290 p[iorder[1]] = ((CH) >> 8) & 0xff; \
3291 p[iorder[0]] = (CH) & 0xff; \
3292 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00003293 } while(0)
3294
3295 /* In narrow builds we can output surrogate pairs as one codepoint,
3296 so we need less space. */
3297#ifndef Py_UNICODE_WIDE
3298 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00003299 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
3300 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
3301 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003302#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003303 nsize = (size - pairs + (byteorder == 0));
3304 bytesize = nsize * 4;
3305 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003306 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003307 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003308 if (v == NULL)
3309 return NULL;
3310
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003311 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003312 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003313 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003314 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00003315 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003316
3317 if (byteorder == -1) {
3318 /* force LE */
3319 iorder[0] = 0;
3320 iorder[1] = 1;
3321 iorder[2] = 2;
3322 iorder[3] = 3;
3323 }
3324 else if (byteorder == 1) {
3325 /* force BE */
3326 iorder[0] = 3;
3327 iorder[1] = 2;
3328 iorder[2] = 1;
3329 iorder[3] = 0;
3330 }
3331
3332 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003333 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003334#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003335 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
3336 Py_UCS4 ch2 = *s;
3337 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
3338 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
3339 s++;
3340 size--;
3341 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00003342 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003343#endif
3344 STORECHAR(ch);
3345 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003346
3347 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003348 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003349#undef STORECHAR
3350}
3351
3352PyObject *PyUnicode_AsUTF32String(PyObject *unicode)
3353{
3354 if (!PyUnicode_Check(unicode)) {
3355 PyErr_BadArgument();
3356 return NULL;
3357 }
3358 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003359 PyUnicode_GET_SIZE(unicode),
3360 NULL,
3361 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003362}
3363
Guido van Rossumd57fd912000-03-10 22:53:23 +00003364/* --- UTF-16 Codec ------------------------------------------------------- */
3365
Tim Peters772747b2001-08-09 22:21:55 +00003366PyObject *
3367PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003368 Py_ssize_t size,
3369 const char *errors,
3370 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003371{
Walter Dörwald69652032004-09-07 20:24:22 +00003372 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
3373}
3374
Antoine Pitrouab868312009-01-10 15:40:25 +00003375/* Two masks for fast checking of whether a C 'long' may contain
3376 UTF16-encoded surrogate characters. This is an efficient heuristic,
3377 assuming that non-surrogate characters with a code point >= 0x8000 are
3378 rare in most input.
3379 FAST_CHAR_MASK is used when the input is in native byte ordering,
3380 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00003381*/
Antoine Pitrouab868312009-01-10 15:40:25 +00003382#if (SIZEOF_LONG == 8)
3383# define FAST_CHAR_MASK 0x8000800080008000L
3384# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
3385#elif (SIZEOF_LONG == 4)
3386# define FAST_CHAR_MASK 0x80008000L
3387# define SWAPPED_FAST_CHAR_MASK 0x00800080L
3388#else
3389# error C 'long' size should be either 4 or 8!
3390#endif
3391
Walter Dörwald69652032004-09-07 20:24:22 +00003392PyObject *
3393PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003394 Py_ssize_t size,
3395 const char *errors,
3396 int *byteorder,
3397 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00003398{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003399 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003400 Py_ssize_t startinpos;
3401 Py_ssize_t endinpos;
3402 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003403 PyUnicodeObject *unicode;
3404 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00003405 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00003406 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00003407 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003408 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00003409 /* Offsets from q for retrieving byte pairs in the right order. */
3410#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3411 int ihi = 1, ilo = 0;
3412#else
3413 int ihi = 0, ilo = 1;
3414#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003415 PyObject *errorHandler = NULL;
3416 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003417
3418 /* Note: size will always be longer than the resulting Unicode
3419 character count */
3420 unicode = _PyUnicode_New(size);
3421 if (!unicode)
3422 return NULL;
3423 if (size == 0)
3424 return (PyObject *)unicode;
3425
3426 /* Unpack UTF-16 encoded data */
3427 p = unicode->str;
Tim Peters772747b2001-08-09 22:21:55 +00003428 q = (unsigned char *)s;
Antoine Pitroub4bbee22012-07-21 00:45:14 +02003429 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003430
3431 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00003432 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003433
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003434 /* Check for BOM marks (U+FEFF) in the input and adjust current
3435 byte order setting accordingly. In native mode, the leading BOM
3436 mark is skipped, in all other modes, it is copied to the output
3437 stream as-is (giving a ZWNBSP character). */
3438 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00003439 if (size >= 2) {
3440 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003441#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00003442 if (bom == 0xFEFF) {
3443 q += 2;
3444 bo = -1;
3445 }
3446 else if (bom == 0xFFFE) {
3447 q += 2;
3448 bo = 1;
3449 }
Tim Petersced69f82003-09-16 20:30:58 +00003450#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003451 if (bom == 0xFEFF) {
3452 q += 2;
3453 bo = 1;
3454 }
3455 else if (bom == 0xFFFE) {
3456 q += 2;
3457 bo = -1;
3458 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003459#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003460 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003461 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003462
Tim Peters772747b2001-08-09 22:21:55 +00003463 if (bo == -1) {
3464 /* force LE */
3465 ihi = 1;
3466 ilo = 0;
3467 }
3468 else if (bo == 1) {
3469 /* force BE */
3470 ihi = 0;
3471 ilo = 1;
3472 }
Antoine Pitrouab868312009-01-10 15:40:25 +00003473#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3474 native_ordering = ilo < ihi;
3475#else
3476 native_ordering = ilo > ihi;
3477#endif
Tim Peters772747b2001-08-09 22:21:55 +00003478
Antoine Pitrouab868312009-01-10 15:40:25 +00003479 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Antoine Pitroub4bbee22012-07-21 00:45:14 +02003480 while (1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003481 Py_UNICODE ch;
Antoine Pitroub4bbee22012-07-21 00:45:14 +02003482 if (e - q < 2) {
3483 /* remaining byte at the end? (size should be even) */
3484 if (q == e || consumed)
3485 break;
3486 errmsg = "truncated data";
3487 startinpos = ((const char *)q) - starts;
3488 endinpos = ((const char *)e) - starts;
3489 outpos = p - PyUnicode_AS_UNICODE(unicode);
3490 goto utf16Error;
3491 /* The remaining input chars are ignored if the callback
3492 chooses to skip the input */
3493 }
Antoine Pitrouab868312009-01-10 15:40:25 +00003494 /* First check for possible aligned read of a C 'long'. Unaligned
3495 reads are more expensive, better to defer to another iteration. */
3496 if (!((size_t) q & LONG_PTR_MASK)) {
3497 /* Fast path for runs of non-surrogate chars. */
3498 register const unsigned char *_q = q;
3499 Py_UNICODE *_p = p;
3500 if (native_ordering) {
3501 /* Native ordering is simple: as long as the input cannot
3502 possibly contain a surrogate char, do an unrolled copy
3503 of several 16-bit code points to the target object.
3504 The non-surrogate check is done on several input bytes
3505 at a time (as many as a C 'long' can contain). */
3506 while (_q < aligned_end) {
3507 unsigned long data = * (unsigned long *) _q;
3508 if (data & FAST_CHAR_MASK)
3509 break;
3510 _p[0] = ((unsigned short *) _q)[0];
3511 _p[1] = ((unsigned short *) _q)[1];
3512#if (SIZEOF_LONG == 8)
3513 _p[2] = ((unsigned short *) _q)[2];
3514 _p[3] = ((unsigned short *) _q)[3];
3515#endif
3516 _q += SIZEOF_LONG;
3517 _p += SIZEOF_LONG / 2;
3518 }
3519 }
3520 else {
3521 /* Byteswapped ordering is similar, but we must decompose
3522 the copy bytewise, and take care of zero'ing out the
3523 upper bytes if the target object is in 32-bit units
3524 (that is, in UCS-4 builds). */
3525 while (_q < aligned_end) {
3526 unsigned long data = * (unsigned long *) _q;
3527 if (data & SWAPPED_FAST_CHAR_MASK)
3528 break;
3529 /* Zero upper bytes in UCS-4 builds */
3530#if (Py_UNICODE_SIZE > 2)
3531 _p[0] = 0;
3532 _p[1] = 0;
3533#if (SIZEOF_LONG == 8)
3534 _p[2] = 0;
3535 _p[3] = 0;
3536#endif
3537#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00003538 /* Issue #4916; UCS-4 builds on big endian machines must
3539 fill the two last bytes of each 4-byte unit. */
3540#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
3541# define OFF 2
3542#else
3543# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00003544#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00003545 ((unsigned char *) _p)[OFF + 1] = _q[0];
3546 ((unsigned char *) _p)[OFF + 0] = _q[1];
3547 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
3548 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
3549#if (SIZEOF_LONG == 8)
3550 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
3551 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
3552 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
3553 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
3554#endif
3555#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00003556 _q += SIZEOF_LONG;
3557 _p += SIZEOF_LONG / 2;
3558 }
3559 }
3560 p = _p;
3561 q = _q;
Antoine Pitroub4bbee22012-07-21 00:45:14 +02003562 if (e - q < 2)
3563 continue;
Antoine Pitrouab868312009-01-10 15:40:25 +00003564 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003565 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003566
Benjamin Peterson14339b62009-01-31 16:36:08 +00003567 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00003568
3569 if (ch < 0xD800 || ch > 0xDFFF) {
3570 *p++ = ch;
3571 continue;
3572 }
3573
3574 /* UTF-16 code pair: */
Antoine Pitroub4bbee22012-07-21 00:45:14 +02003575 if (e - q < 2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003576 errmsg = "unexpected end of data";
3577 startinpos = (((const char *)q) - 2) - starts;
Antoine Pitroub4bbee22012-07-21 00:45:14 +02003578 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00003579 goto utf16Error;
3580 }
3581 if (0xD800 <= ch && ch <= 0xDBFF) {
3582 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
3583 q += 2;
3584 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00003585#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003586 *p++ = ch;
3587 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003588#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003589 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003590#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003591 continue;
3592 }
3593 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003594 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00003595 startinpos = (((const char *)q)-4)-starts;
3596 endinpos = startinpos+2;
3597 goto utf16Error;
3598 }
3599
Benjamin Peterson14339b62009-01-31 16:36:08 +00003600 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003601 errmsg = "illegal encoding";
3602 startinpos = (((const char *)q)-2)-starts;
3603 endinpos = startinpos+2;
3604 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003605
Benjamin Peterson29060642009-01-31 22:14:21 +00003606 utf16Error:
3607 outpos = p - PyUnicode_AS_UNICODE(unicode);
3608 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00003609 errors,
3610 &errorHandler,
3611 "utf16", errmsg,
3612 &starts,
3613 (const char **)&e,
3614 &startinpos,
3615 &endinpos,
3616 &exc,
3617 (const char **)&q,
3618 &unicode,
3619 &outpos,
3620 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00003621 goto onError;
Antoine Pitroub4bbee22012-07-21 00:45:14 +02003622 /* Update data because unicode_decode_call_errorhandler might have
3623 changed the input object. */
3624 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Antoine Pitrouab868312009-01-10 15:40:25 +00003625 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003626
3627 if (byteorder)
3628 *byteorder = bo;
3629
Walter Dörwald69652032004-09-07 20:24:22 +00003630 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00003631 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00003632
Guido van Rossumd57fd912000-03-10 22:53:23 +00003633 /* Adjust length */
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00003634 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003635 goto onError;
3636
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003637 Py_XDECREF(errorHandler);
3638 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003639 return (PyObject *)unicode;
3640
Benjamin Peterson29060642009-01-31 22:14:21 +00003641 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003642 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003643 Py_XDECREF(errorHandler);
3644 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003645 return NULL;
3646}
3647
Antoine Pitrouab868312009-01-10 15:40:25 +00003648#undef FAST_CHAR_MASK
3649#undef SWAPPED_FAST_CHAR_MASK
3650
Tim Peters772747b2001-08-09 22:21:55 +00003651PyObject *
3652PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003653 Py_ssize_t size,
3654 const char *errors,
3655 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003656{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003657 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00003658 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003659 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003660#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003661 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003662#else
3663 const int pairs = 0;
3664#endif
Tim Peters772747b2001-08-09 22:21:55 +00003665 /* Offsets from p for storing byte pairs in the right order. */
3666#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3667 int ihi = 1, ilo = 0;
3668#else
3669 int ihi = 0, ilo = 1;
3670#endif
3671
Benjamin Peterson29060642009-01-31 22:14:21 +00003672#define STORECHAR(CH) \
3673 do { \
3674 p[ihi] = ((CH) >> 8) & 0xff; \
3675 p[ilo] = (CH) & 0xff; \
3676 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00003677 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003678
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003679#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003680 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00003681 if (s[i] >= 0x10000)
3682 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003683#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003684 /* 2 * (size + pairs + (byteorder == 0)) */
3685 if (size > PY_SSIZE_T_MAX ||
3686 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00003687 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003688 nsize = size + pairs + (byteorder == 0);
3689 bytesize = nsize * 2;
3690 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003691 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003692 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003693 if (v == NULL)
3694 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003695
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003696 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003697 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003698 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00003699 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00003700 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00003701
3702 if (byteorder == -1) {
3703 /* force LE */
3704 ihi = 1;
3705 ilo = 0;
3706 }
3707 else if (byteorder == 1) {
3708 /* force BE */
3709 ihi = 0;
3710 ilo = 1;
3711 }
3712
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003713 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003714 Py_UNICODE ch = *s++;
3715 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003716#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003717 if (ch >= 0x10000) {
3718 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
3719 ch = 0xD800 | ((ch-0x10000) >> 10);
3720 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003721#endif
Tim Peters772747b2001-08-09 22:21:55 +00003722 STORECHAR(ch);
3723 if (ch2)
3724 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003725 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003726
3727 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003728 return v;
Tim Peters772747b2001-08-09 22:21:55 +00003729#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00003730}
3731
3732PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
3733{
3734 if (!PyUnicode_Check(unicode)) {
3735 PyErr_BadArgument();
3736 return NULL;
3737 }
3738 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003739 PyUnicode_GET_SIZE(unicode),
3740 NULL,
3741 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003742}
3743
3744/* --- Unicode Escape Codec ----------------------------------------------- */
3745
Fredrik Lundh06d12682001-01-24 07:59:11 +00003746static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00003747
Guido van Rossumd57fd912000-03-10 22:53:23 +00003748PyObject *PyUnicode_DecodeUnicodeEscape(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003749 Py_ssize_t size,
3750 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003751{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003752 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003753 Py_ssize_t startinpos;
3754 Py_ssize_t endinpos;
3755 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003756 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003757 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003758 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003759 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003760 char* message;
3761 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003762 PyObject *errorHandler = NULL;
3763 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003764
Guido van Rossumd57fd912000-03-10 22:53:23 +00003765 /* Escaped strings will always be longer than the resulting
3766 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003767 length after conversion to the true value.
3768 (but if the error callback returns a long replacement string
3769 we'll have to allocate more space) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003770 v = _PyUnicode_New(size);
3771 if (v == NULL)
3772 goto onError;
3773 if (size == 0)
3774 return (PyObject *)v;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003775
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003776 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003777 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003778
Guido van Rossumd57fd912000-03-10 22:53:23 +00003779 while (s < end) {
3780 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00003781 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003782 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003783
3784 /* Non-escape characters are interpreted as Unicode ordinals */
3785 if (*s != '\\') {
Fredrik Lundhccc74732001-02-18 22:13:49 +00003786 *p++ = (unsigned char) *s++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003787 continue;
3788 }
3789
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003790 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003791 /* \ - Escapes */
3792 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003793 c = *s++;
3794 if (s > end)
3795 c = '\0'; /* Invalid after \ */
3796 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003797
Benjamin Peterson29060642009-01-31 22:14:21 +00003798 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003799 case '\n': break;
3800 case '\\': *p++ = '\\'; break;
3801 case '\'': *p++ = '\''; break;
3802 case '\"': *p++ = '\"'; break;
3803 case 'b': *p++ = '\b'; break;
3804 case 'f': *p++ = '\014'; break; /* FF */
3805 case 't': *p++ = '\t'; break;
3806 case 'n': *p++ = '\n'; break;
3807 case 'r': *p++ = '\r'; break;
3808 case 'v': *p++ = '\013'; break; /* VT */
3809 case 'a': *p++ = '\007'; break; /* BEL, not classic C */
3810
Benjamin Peterson29060642009-01-31 22:14:21 +00003811 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003812 case '0': case '1': case '2': case '3':
3813 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003814 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003815 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003816 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003817 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003818 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00003819 }
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003820 *p++ = x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003821 break;
3822
Benjamin Peterson29060642009-01-31 22:14:21 +00003823 /* hex escapes */
3824 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003825 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003826 digits = 2;
3827 message = "truncated \\xXX escape";
3828 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003829
Benjamin Peterson29060642009-01-31 22:14:21 +00003830 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003831 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003832 digits = 4;
3833 message = "truncated \\uXXXX escape";
3834 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003835
Benjamin Peterson29060642009-01-31 22:14:21 +00003836 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00003837 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003838 digits = 8;
3839 message = "truncated \\UXXXXXXXX escape";
3840 hexescape:
3841 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003842 outpos = p-PyUnicode_AS_UNICODE(v);
3843 if (s+digits>end) {
3844 endinpos = size;
3845 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003846 errors, &errorHandler,
3847 "unicodeescape", "end of string in escape sequence",
3848 &starts, &end, &startinpos, &endinpos, &exc, &s,
3849 &v, &outpos, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003850 goto onError;
3851 goto nextByte;
3852 }
3853 for (i = 0; i < digits; ++i) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00003854 c = (unsigned char) s[i];
David Malcolm96960882010-11-05 17:23:41 +00003855 if (!Py_ISXDIGIT(c)) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003856 endinpos = (s+i+1)-starts;
3857 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003858 errors, &errorHandler,
3859 "unicodeescape", message,
3860 &starts, &end, &startinpos, &endinpos, &exc, &s,
3861 &v, &outpos, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00003862 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003863 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00003864 }
3865 chr = (chr<<4) & ~0xF;
3866 if (c >= '0' && c <= '9')
3867 chr += c - '0';
3868 else if (c >= 'a' && c <= 'f')
3869 chr += 10 + c - 'a';
3870 else
3871 chr += 10 + c - 'A';
3872 }
3873 s += i;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00003874 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003875 /* _decoding_error will have already written into the
3876 target buffer. */
3877 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003878 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00003879 /* when we get here, chr is a 32-bit unicode character */
3880 if (chr <= 0xffff)
3881 /* UCS-2 character */
3882 *p++ = (Py_UNICODE) chr;
3883 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00003884 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00003885 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00003886#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003887 *p++ = chr;
3888#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00003889 chr -= 0x10000L;
3890 *p++ = 0xD800 + (Py_UNICODE) (chr >> 10);
Fredrik Lundh45714e92001-06-26 16:39:36 +00003891 *p++ = 0xDC00 + (Py_UNICODE) (chr & 0x03FF);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003892#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00003893 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003894 endinpos = s-starts;
3895 outpos = p-PyUnicode_AS_UNICODE(v);
3896 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003897 errors, &errorHandler,
3898 "unicodeescape", "illegal Unicode character",
3899 &starts, &end, &startinpos, &endinpos, &exc, &s,
3900 &v, &outpos, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00003901 goto onError;
3902 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00003903 break;
3904
Benjamin Peterson29060642009-01-31 22:14:21 +00003905 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00003906 case 'N':
3907 message = "malformed \\N character escape";
3908 if (ucnhash_CAPI == NULL) {
3909 /* load the unicode data module */
Benjamin Petersonb173f782009-05-05 22:31:58 +00003910 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00003911 if (ucnhash_CAPI == NULL)
3912 goto ucnhashError;
3913 }
3914 if (*s == '{') {
3915 const char *start = s+1;
3916 /* look for the closing brace */
3917 while (*s != '}' && s < end)
3918 s++;
3919 if (s > start && s < end && *s == '}') {
3920 /* found a name. look it up in the unicode database */
3921 message = "unknown Unicode character name";
3922 s++;
Martin v. Löwis480f1bb2006-03-09 23:38:20 +00003923 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1), &chr))
Fredrik Lundhccc74732001-02-18 22:13:49 +00003924 goto store;
3925 }
3926 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003927 endinpos = s-starts;
3928 outpos = p-PyUnicode_AS_UNICODE(v);
3929 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003930 errors, &errorHandler,
3931 "unicodeescape", message,
3932 &starts, &end, &startinpos, &endinpos, &exc, &s,
3933 &v, &outpos, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00003934 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003935 break;
3936
3937 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00003938 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003939 message = "\\ at end of string";
3940 s--;
3941 endinpos = s-starts;
3942 outpos = p-PyUnicode_AS_UNICODE(v);
3943 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003944 errors, &errorHandler,
3945 "unicodeescape", message,
3946 &starts, &end, &startinpos, &endinpos, &exc, &s,
3947 &v, &outpos, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00003948 goto onError;
3949 }
3950 else {
3951 *p++ = '\\';
3952 *p++ = (unsigned char)s[-1];
3953 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00003954 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003955 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003956 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003957 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003958 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003959 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003960 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00003961 Py_XDECREF(errorHandler);
3962 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003963 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00003964
Benjamin Peterson29060642009-01-31 22:14:21 +00003965 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00003966 PyErr_SetString(
3967 PyExc_UnicodeError,
3968 "\\N escapes not supported (can't load unicodedata module)"
3969 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003970 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003971 Py_XDECREF(errorHandler);
3972 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00003973 return NULL;
3974
Benjamin Peterson29060642009-01-31 22:14:21 +00003975 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003976 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003977 Py_XDECREF(errorHandler);
3978 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003979 return NULL;
3980}
3981
3982/* Return a Unicode-Escape string version of the Unicode object.
3983
3984 If quotes is true, the string is enclosed in u"" or u'' quotes as
3985 appropriate.
3986
3987*/
3988
Thomas Wouters477c8d52006-05-27 19:21:47 +00003989Py_LOCAL_INLINE(const Py_UNICODE *) findchar(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003990 Py_ssize_t size,
3991 Py_UNICODE ch)
Thomas Wouters477c8d52006-05-27 19:21:47 +00003992{
3993 /* like wcschr, but doesn't stop at NULL characters */
3994
3995 while (size-- > 0) {
3996 if (*s == ch)
3997 return s;
3998 s++;
3999 }
4000
4001 return NULL;
4002}
Barry Warsaw51ac5802000-03-20 16:36:48 +00004003
Walter Dörwald79e913e2007-05-12 11:08:06 +00004004static const char *hexdigits = "0123456789abcdef";
4005
4006PyObject *PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004007 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004008{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004009 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004010 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004011
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004012#ifdef Py_UNICODE_WIDE
4013 const Py_ssize_t expandsize = 10;
4014#else
4015 const Py_ssize_t expandsize = 6;
4016#endif
4017
Thomas Wouters89f507f2006-12-13 04:49:30 +00004018 /* XXX(nnorwitz): rather than over-allocating, it would be
4019 better to choose a different scheme. Perhaps scan the
4020 first N-chars of the string and allocate based on that size.
4021 */
4022 /* Initial allocation is based on the longest-possible unichr
4023 escape.
4024
4025 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
4026 unichr, so in this case it's the longest unichr escape. In
4027 narrow (UTF-16) builds this is five chars per source unichr
4028 since there are two unichrs in the surrogate pair, so in narrow
4029 (UTF-16) builds it's not the longest unichr escape.
4030
4031 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
4032 so in the narrow (UTF-16) build case it's the longest unichr
4033 escape.
4034 */
4035
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004036 if (size == 0)
4037 return PyBytes_FromStringAndSize(NULL, 0);
4038
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004039 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00004040 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004041
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004042 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00004043 2
4044 + expandsize*size
4045 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004046 if (repr == NULL)
4047 return NULL;
4048
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004049 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004050
Guido van Rossumd57fd912000-03-10 22:53:23 +00004051 while (size-- > 0) {
4052 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004053
Walter Dörwald79e913e2007-05-12 11:08:06 +00004054 /* Escape backslashes */
4055 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004056 *p++ = '\\';
4057 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00004058 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004059 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004060
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00004061#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004062 /* Map 21-bit characters to '\U00xxxxxx' */
4063 else if (ch >= 0x10000) {
4064 *p++ = '\\';
4065 *p++ = 'U';
Walter Dörwald79e913e2007-05-12 11:08:06 +00004066 *p++ = hexdigits[(ch >> 28) & 0x0000000F];
4067 *p++ = hexdigits[(ch >> 24) & 0x0000000F];
4068 *p++ = hexdigits[(ch >> 20) & 0x0000000F];
4069 *p++ = hexdigits[(ch >> 16) & 0x0000000F];
4070 *p++ = hexdigits[(ch >> 12) & 0x0000000F];
4071 *p++ = hexdigits[(ch >> 8) & 0x0000000F];
4072 *p++ = hexdigits[(ch >> 4) & 0x0000000F];
4073 *p++ = hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00004074 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004075 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00004076#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004077 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
4078 else if (ch >= 0xD800 && ch < 0xDC00) {
4079 Py_UNICODE ch2;
4080 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00004081
Benjamin Peterson29060642009-01-31 22:14:21 +00004082 ch2 = *s++;
4083 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00004084 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004085 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
4086 *p++ = '\\';
4087 *p++ = 'U';
4088 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
4089 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
4090 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
4091 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
4092 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
4093 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
4094 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
4095 *p++ = hexdigits[ucs & 0x0000000F];
4096 continue;
4097 }
4098 /* Fall through: isolated surrogates are copied as-is */
4099 s--;
4100 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004101 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00004102#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00004103
Guido van Rossumd57fd912000-03-10 22:53:23 +00004104 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00004105 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004106 *p++ = '\\';
4107 *p++ = 'u';
Walter Dörwald79e913e2007-05-12 11:08:06 +00004108 *p++ = hexdigits[(ch >> 12) & 0x000F];
4109 *p++ = hexdigits[(ch >> 8) & 0x000F];
4110 *p++ = hexdigits[(ch >> 4) & 0x000F];
4111 *p++ = hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00004112 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004113
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00004114 /* Map special whitespace to '\t', \n', '\r' */
4115 else if (ch == '\t') {
4116 *p++ = '\\';
4117 *p++ = 't';
4118 }
4119 else if (ch == '\n') {
4120 *p++ = '\\';
4121 *p++ = 'n';
4122 }
4123 else if (ch == '\r') {
4124 *p++ = '\\';
4125 *p++ = 'r';
4126 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004127
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00004128 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00004129 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004130 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00004131 *p++ = 'x';
Walter Dörwald79e913e2007-05-12 11:08:06 +00004132 *p++ = hexdigits[(ch >> 4) & 0x000F];
4133 *p++ = hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00004134 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004135
Guido van Rossumd57fd912000-03-10 22:53:23 +00004136 /* Copy everything else as-is */
4137 else
4138 *p++ = (char) ch;
4139 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004140
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004141 assert(p - PyBytes_AS_STRING(repr) > 0);
4142 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
4143 return NULL;
4144 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004145}
4146
Alexandre Vassalotti2056bed2008-12-27 19:46:35 +00004147PyObject *PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004148{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004149 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004150 if (!PyUnicode_Check(unicode)) {
4151 PyErr_BadArgument();
4152 return NULL;
4153 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00004154 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
4155 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004156 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004157}
4158
4159/* --- Raw Unicode Escape Codec ------------------------------------------- */
4160
4161PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004162 Py_ssize_t size,
4163 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004164{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004165 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004166 Py_ssize_t startinpos;
4167 Py_ssize_t endinpos;
4168 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004169 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004170 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004171 const char *end;
4172 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004173 PyObject *errorHandler = NULL;
4174 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00004175
Guido van Rossumd57fd912000-03-10 22:53:23 +00004176 /* Escaped strings will always be longer than the resulting
4177 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004178 length after conversion to the true value. (But decoding error
4179 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004180 v = _PyUnicode_New(size);
4181 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004182 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004183 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004184 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004185 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004186 end = s + size;
4187 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004188 unsigned char c;
4189 Py_UCS4 x;
4190 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004191 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004192
Benjamin Peterson29060642009-01-31 22:14:21 +00004193 /* Non-escape characters are interpreted as Unicode ordinals */
4194 if (*s != '\\') {
4195 *p++ = (unsigned char)*s++;
4196 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004197 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004198 startinpos = s-starts;
4199
4200 /* \u-escapes are only interpreted iff the number of leading
4201 backslashes if odd */
4202 bs = s;
4203 for (;s < end;) {
4204 if (*s != '\\')
4205 break;
4206 *p++ = (unsigned char)*s++;
4207 }
4208 if (((s - bs) & 1) == 0 ||
4209 s >= end ||
4210 (*s != 'u' && *s != 'U')) {
4211 continue;
4212 }
4213 p--;
4214 count = *s=='u' ? 4 : 8;
4215 s++;
4216
4217 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
4218 outpos = p-PyUnicode_AS_UNICODE(v);
4219 for (x = 0, i = 0; i < count; ++i, ++s) {
4220 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00004221 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004222 endinpos = s-starts;
4223 if (unicode_decode_call_errorhandler(
4224 errors, &errorHandler,
4225 "rawunicodeescape", "truncated \\uXXXX",
4226 &starts, &end, &startinpos, &endinpos, &exc, &s,
4227 &v, &outpos, &p))
4228 goto onError;
4229 goto nextByte;
4230 }
4231 x = (x<<4) & ~0xF;
4232 if (c >= '0' && c <= '9')
4233 x += c - '0';
4234 else if (c >= 'a' && c <= 'f')
4235 x += 10 + c - 'a';
4236 else
4237 x += 10 + c - 'A';
4238 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00004239 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00004240 /* UCS-2 character */
4241 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004242 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004243 /* UCS-4 character. Either store directly, or as
4244 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00004245#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004246 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004247#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004248 x -= 0x10000L;
4249 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
4250 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00004251#endif
4252 } else {
4253 endinpos = s-starts;
4254 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004255 if (unicode_decode_call_errorhandler(
4256 errors, &errorHandler,
4257 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00004258 &starts, &end, &startinpos, &endinpos, &exc, &s,
4259 &v, &outpos, &p))
4260 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004261 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004262 nextByte:
4263 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004264 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004265 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004266 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004267 Py_XDECREF(errorHandler);
4268 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004269 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004270
Benjamin Peterson29060642009-01-31 22:14:21 +00004271 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004272 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004273 Py_XDECREF(errorHandler);
4274 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004275 return NULL;
4276}
4277
4278PyObject *PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004279 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004280{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004281 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004282 char *p;
4283 char *q;
4284
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004285#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004286 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004287#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004288 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004289#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00004290
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004291 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00004292 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00004293
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004294 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004295 if (repr == NULL)
4296 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00004297 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004298 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004299
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004300 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004301 while (size-- > 0) {
4302 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004303#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004304 /* Map 32-bit characters to '\Uxxxxxxxx' */
4305 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004306 *p++ = '\\';
4307 *p++ = 'U';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00004308 *p++ = hexdigits[(ch >> 28) & 0xf];
4309 *p++ = hexdigits[(ch >> 24) & 0xf];
4310 *p++ = hexdigits[(ch >> 20) & 0xf];
4311 *p++ = hexdigits[(ch >> 16) & 0xf];
4312 *p++ = hexdigits[(ch >> 12) & 0xf];
4313 *p++ = hexdigits[(ch >> 8) & 0xf];
4314 *p++ = hexdigits[(ch >> 4) & 0xf];
4315 *p++ = hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00004316 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004317 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00004318#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004319 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
4320 if (ch >= 0xD800 && ch < 0xDC00) {
4321 Py_UNICODE ch2;
4322 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004323
Benjamin Peterson29060642009-01-31 22:14:21 +00004324 ch2 = *s++;
4325 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00004326 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004327 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
4328 *p++ = '\\';
4329 *p++ = 'U';
4330 *p++ = hexdigits[(ucs >> 28) & 0xf];
4331 *p++ = hexdigits[(ucs >> 24) & 0xf];
4332 *p++ = hexdigits[(ucs >> 20) & 0xf];
4333 *p++ = hexdigits[(ucs >> 16) & 0xf];
4334 *p++ = hexdigits[(ucs >> 12) & 0xf];
4335 *p++ = hexdigits[(ucs >> 8) & 0xf];
4336 *p++ = hexdigits[(ucs >> 4) & 0xf];
4337 *p++ = hexdigits[ucs & 0xf];
4338 continue;
4339 }
4340 /* Fall through: isolated surrogates are copied as-is */
4341 s--;
4342 size++;
4343 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004344#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004345 /* Map 16-bit characters to '\uxxxx' */
4346 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004347 *p++ = '\\';
4348 *p++ = 'u';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00004349 *p++ = hexdigits[(ch >> 12) & 0xf];
4350 *p++ = hexdigits[(ch >> 8) & 0xf];
4351 *p++ = hexdigits[(ch >> 4) & 0xf];
4352 *p++ = hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00004353 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004354 /* Copy everything else as-is */
4355 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00004356 *p++ = (char) ch;
4357 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00004358 size = p - q;
4359
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004360 assert(size > 0);
4361 if (_PyBytes_Resize(&repr, size) < 0)
4362 return NULL;
4363 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004364}
4365
4366PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
4367{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004368 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004369 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00004370 PyErr_BadArgument();
4371 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004372 }
Walter Dörwald711005d2007-05-12 12:03:26 +00004373 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
4374 PyUnicode_GET_SIZE(unicode));
4375
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004376 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004377}
4378
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004379/* --- Unicode Internal Codec ------------------------------------------- */
4380
4381PyObject *_PyUnicode_DecodeUnicodeInternal(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004382 Py_ssize_t size,
4383 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004384{
4385 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004386 Py_ssize_t startinpos;
4387 Py_ssize_t endinpos;
4388 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004389 PyUnicodeObject *v;
4390 Py_UNICODE *p;
4391 const char *end;
4392 const char *reason;
4393 PyObject *errorHandler = NULL;
4394 PyObject *exc = NULL;
4395
Neal Norwitzd43069c2006-01-08 01:12:10 +00004396#ifdef Py_UNICODE_WIDE
4397 Py_UNICODE unimax = PyUnicode_GetMax();
4398#endif
4399
Thomas Wouters89f507f2006-12-13 04:49:30 +00004400 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004401 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
4402 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004403 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004404 if (PyUnicode_GetSize((PyObject *)v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004405 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004406 p = PyUnicode_AS_UNICODE(v);
4407 end = s + size;
4408
4409 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00004410 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004411 /* We have to sanity check the raw data, otherwise doom looms for
4412 some malformed UCS-4 data. */
4413 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00004414#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004415 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00004416#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004417 end-s < Py_UNICODE_SIZE
4418 )
Benjamin Peterson29060642009-01-31 22:14:21 +00004419 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004420 startinpos = s - starts;
4421 if (end-s < Py_UNICODE_SIZE) {
4422 endinpos = end-starts;
4423 reason = "truncated input";
4424 }
4425 else {
4426 endinpos = s - starts + Py_UNICODE_SIZE;
4427 reason = "illegal code point (> 0x10FFFF)";
4428 }
4429 outpos = p - PyUnicode_AS_UNICODE(v);
4430 if (unicode_decode_call_errorhandler(
4431 errors, &errorHandler,
4432 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00004433 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00004434 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004435 goto onError;
4436 }
4437 }
4438 else {
4439 p++;
4440 s += Py_UNICODE_SIZE;
4441 }
4442 }
4443
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004444 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004445 goto onError;
4446 Py_XDECREF(errorHandler);
4447 Py_XDECREF(exc);
4448 return (PyObject *)v;
4449
Benjamin Peterson29060642009-01-31 22:14:21 +00004450 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004451 Py_XDECREF(v);
4452 Py_XDECREF(errorHandler);
4453 Py_XDECREF(exc);
4454 return NULL;
4455}
4456
Guido van Rossumd57fd912000-03-10 22:53:23 +00004457/* --- Latin-1 Codec ------------------------------------------------------ */
4458
4459PyObject *PyUnicode_DecodeLatin1(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004460 Py_ssize_t size,
4461 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004462{
4463 PyUnicodeObject *v;
4464 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00004465 const char *e, *unrolled_end;
Tim Petersced69f82003-09-16 20:30:58 +00004466
Guido van Rossumd57fd912000-03-10 22:53:23 +00004467 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004468 if (size == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004469 Py_UNICODE r = *(unsigned char*)s;
4470 return PyUnicode_FromUnicode(&r, 1);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004471 }
4472
Guido van Rossumd57fd912000-03-10 22:53:23 +00004473 v = _PyUnicode_New(size);
4474 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004475 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004476 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004477 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004478 p = PyUnicode_AS_UNICODE(v);
Antoine Pitrouab868312009-01-10 15:40:25 +00004479 e = s + size;
4480 /* Unrolling the copy makes it much faster by reducing the looping
4481 overhead. This is similar to what many memcpy() implementations do. */
4482 unrolled_end = e - 4;
4483 while (s < unrolled_end) {
4484 p[0] = (unsigned char) s[0];
4485 p[1] = (unsigned char) s[1];
4486 p[2] = (unsigned char) s[2];
4487 p[3] = (unsigned char) s[3];
4488 s += 4;
4489 p += 4;
4490 }
4491 while (s < e)
4492 *p++ = (unsigned char) *s++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004493 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004494
Benjamin Peterson29060642009-01-31 22:14:21 +00004495 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004496 Py_XDECREF(v);
4497 return NULL;
4498}
4499
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004500/* create or adjust a UnicodeEncodeError */
4501static void make_encode_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004502 const char *encoding,
4503 const Py_UNICODE *unicode, Py_ssize_t size,
4504 Py_ssize_t startpos, Py_ssize_t endpos,
4505 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004506{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004507 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004508 *exceptionObject = PyUnicodeEncodeError_Create(
4509 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004510 }
4511 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004512 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
4513 goto onError;
4514 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
4515 goto onError;
4516 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
4517 goto onError;
4518 return;
4519 onError:
4520 Py_DECREF(*exceptionObject);
4521 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004522 }
4523}
4524
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004525/* raises a UnicodeEncodeError */
4526static void raise_encode_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004527 const char *encoding,
4528 const Py_UNICODE *unicode, Py_ssize_t size,
4529 Py_ssize_t startpos, Py_ssize_t endpos,
4530 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004531{
4532 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004533 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004534 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004535 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004536}
4537
4538/* error handling callback helper:
4539 build arguments, call the callback and check the arguments,
4540 put the result into newpos and return the replacement string, which
4541 has to be freed by the caller */
4542static PyObject *unicode_encode_call_errorhandler(const char *errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00004543 PyObject **errorHandler,
4544 const char *encoding, const char *reason,
4545 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
4546 Py_ssize_t startpos, Py_ssize_t endpos,
4547 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004548{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004549 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004550
4551 PyObject *restuple;
4552 PyObject *resunicode;
4553
4554 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004555 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004556 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004557 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004558 }
4559
4560 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004561 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004562 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004563 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004564
4565 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00004566 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004567 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004568 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004569 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004570 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004571 Py_DECREF(restuple);
4572 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004573 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004574 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00004575 &resunicode, newpos)) {
4576 Py_DECREF(restuple);
4577 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004578 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004579 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
4580 PyErr_SetString(PyExc_TypeError, &argparse[3]);
4581 Py_DECREF(restuple);
4582 return NULL;
4583 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004584 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004585 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004586 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004587 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
4588 Py_DECREF(restuple);
4589 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004590 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004591 Py_INCREF(resunicode);
4592 Py_DECREF(restuple);
4593 return resunicode;
4594}
4595
4596static PyObject *unicode_encode_ucs1(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004597 Py_ssize_t size,
4598 const char *errors,
4599 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004600{
4601 /* output object */
4602 PyObject *res;
4603 /* pointers to the beginning and end+1 of input */
4604 const Py_UNICODE *startp = p;
4605 const Py_UNICODE *endp = p + size;
4606 /* pointer to the beginning of the unencodable characters */
4607 /* const Py_UNICODE *badp = NULL; */
4608 /* pointer into the output */
4609 char *str;
4610 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00004611 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004612 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
4613 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004614 PyObject *errorHandler = NULL;
4615 PyObject *exc = NULL;
4616 /* the following variable is used for caching string comparisons
4617 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
4618 int known_errorHandler = -1;
4619
4620 /* allocate enough for a simple encoding without
4621 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00004622 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00004623 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004624 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004625 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00004626 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004627 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004628 ressize = size;
4629
4630 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004631 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004632
Benjamin Peterson29060642009-01-31 22:14:21 +00004633 /* can we encode this? */
4634 if (c<limit) {
4635 /* no overflow check, because we know that the space is enough */
4636 *str++ = (char)c;
4637 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004638 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004639 else {
4640 Py_ssize_t unicodepos = p-startp;
4641 Py_ssize_t requiredsize;
4642 PyObject *repunicode;
4643 Py_ssize_t repsize;
4644 Py_ssize_t newpos;
4645 Py_ssize_t respos;
4646 Py_UNICODE *uni2;
4647 /* startpos for collecting unencodable chars */
4648 const Py_UNICODE *collstart = p;
4649 const Py_UNICODE *collend = p;
4650 /* find all unecodable characters */
4651 while ((collend < endp) && ((*collend)>=limit))
4652 ++collend;
4653 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
4654 if (known_errorHandler==-1) {
4655 if ((errors==NULL) || (!strcmp(errors, "strict")))
4656 known_errorHandler = 1;
4657 else if (!strcmp(errors, "replace"))
4658 known_errorHandler = 2;
4659 else if (!strcmp(errors, "ignore"))
4660 known_errorHandler = 3;
4661 else if (!strcmp(errors, "xmlcharrefreplace"))
4662 known_errorHandler = 4;
4663 else
4664 known_errorHandler = 0;
4665 }
4666 switch (known_errorHandler) {
4667 case 1: /* strict */
4668 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
4669 goto onError;
4670 case 2: /* replace */
4671 while (collstart++<collend)
4672 *str++ = '?'; /* fall through */
4673 case 3: /* ignore */
4674 p = collend;
4675 break;
4676 case 4: /* xmlcharrefreplace */
4677 respos = str - PyBytes_AS_STRING(res);
4678 /* determine replacement size (temporarily (mis)uses p) */
4679 for (p = collstart, repsize = 0; p < collend; ++p) {
4680 if (*p<10)
4681 repsize += 2+1+1;
4682 else if (*p<100)
4683 repsize += 2+2+1;
4684 else if (*p<1000)
4685 repsize += 2+3+1;
4686 else if (*p<10000)
4687 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00004688#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004689 else
4690 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00004691#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004692 else if (*p<100000)
4693 repsize += 2+5+1;
4694 else if (*p<1000000)
4695 repsize += 2+6+1;
4696 else
4697 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004698#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004699 }
4700 requiredsize = respos+repsize+(endp-collend);
4701 if (requiredsize > ressize) {
4702 if (requiredsize<2*ressize)
4703 requiredsize = 2*ressize;
4704 if (_PyBytes_Resize(&res, requiredsize))
4705 goto onError;
4706 str = PyBytes_AS_STRING(res) + respos;
4707 ressize = requiredsize;
4708 }
4709 /* generate replacement (temporarily (mis)uses p) */
4710 for (p = collstart; p < collend; ++p) {
4711 str += sprintf(str, "&#%d;", (int)*p);
4712 }
4713 p = collend;
4714 break;
4715 default:
4716 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
4717 encoding, reason, startp, size, &exc,
4718 collstart-startp, collend-startp, &newpos);
4719 if (repunicode == NULL)
4720 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004721 if (PyBytes_Check(repunicode)) {
4722 /* Directly copy bytes result to output. */
4723 repsize = PyBytes_Size(repunicode);
4724 if (repsize > 1) {
4725 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00004726 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00004727 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
4728 Py_DECREF(repunicode);
4729 goto onError;
4730 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00004731 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004732 ressize += repsize-1;
4733 }
4734 memcpy(str, PyBytes_AsString(repunicode), repsize);
4735 str += repsize;
4736 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004737 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00004738 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004739 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004740 /* need more space? (at least enough for what we
4741 have+the replacement+the rest of the string, so
4742 we won't have to check space for encodable characters) */
4743 respos = str - PyBytes_AS_STRING(res);
4744 repsize = PyUnicode_GET_SIZE(repunicode);
4745 requiredsize = respos+repsize+(endp-collend);
4746 if (requiredsize > ressize) {
4747 if (requiredsize<2*ressize)
4748 requiredsize = 2*ressize;
4749 if (_PyBytes_Resize(&res, requiredsize)) {
4750 Py_DECREF(repunicode);
4751 goto onError;
4752 }
4753 str = PyBytes_AS_STRING(res) + respos;
4754 ressize = requiredsize;
4755 }
4756 /* check if there is anything unencodable in the replacement
4757 and copy it to the output */
4758 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
4759 c = *uni2;
4760 if (c >= limit) {
4761 raise_encode_exception(&exc, encoding, startp, size,
4762 unicodepos, unicodepos+1, reason);
4763 Py_DECREF(repunicode);
4764 goto onError;
4765 }
4766 *str = (char)c;
4767 }
4768 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004769 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00004770 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004771 }
4772 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004773 /* Resize if we allocated to much */
4774 size = str - PyBytes_AS_STRING(res);
4775 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00004776 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004777 if (_PyBytes_Resize(&res, size) < 0)
4778 goto onError;
4779 }
4780
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004781 Py_XDECREF(errorHandler);
4782 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004783 return res;
4784
4785 onError:
4786 Py_XDECREF(res);
4787 Py_XDECREF(errorHandler);
4788 Py_XDECREF(exc);
4789 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004790}
4791
Guido van Rossumd57fd912000-03-10 22:53:23 +00004792PyObject *PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004793 Py_ssize_t size,
4794 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004795{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004796 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004797}
4798
4799PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
4800{
4801 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004802 PyErr_BadArgument();
4803 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004804 }
4805 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004806 PyUnicode_GET_SIZE(unicode),
4807 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004808}
4809
4810/* --- 7-bit ASCII Codec -------------------------------------------------- */
4811
Guido van Rossumd57fd912000-03-10 22:53:23 +00004812PyObject *PyUnicode_DecodeASCII(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004813 Py_ssize_t size,
4814 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004815{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004816 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004817 PyUnicodeObject *v;
4818 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004819 Py_ssize_t startinpos;
4820 Py_ssize_t endinpos;
4821 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004822 const char *e;
4823 PyObject *errorHandler = NULL;
4824 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00004825
Guido van Rossumd57fd912000-03-10 22:53:23 +00004826 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004827 if (size == 1 && *(unsigned char*)s < 128) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004828 Py_UNICODE r = *(unsigned char*)s;
4829 return PyUnicode_FromUnicode(&r, 1);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004830 }
Tim Petersced69f82003-09-16 20:30:58 +00004831
Guido van Rossumd57fd912000-03-10 22:53:23 +00004832 v = _PyUnicode_New(size);
4833 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004834 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004835 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004836 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004837 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004838 e = s + size;
4839 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004840 register unsigned char c = (unsigned char)*s;
4841 if (c < 128) {
4842 *p++ = c;
4843 ++s;
4844 }
4845 else {
4846 startinpos = s-starts;
4847 endinpos = startinpos + 1;
4848 outpos = p - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
4849 if (unicode_decode_call_errorhandler(
4850 errors, &errorHandler,
4851 "ascii", "ordinal not in range(128)",
4852 &starts, &e, &startinpos, &endinpos, &exc, &s,
4853 &v, &outpos, &p))
4854 goto onError;
4855 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004856 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00004857 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00004858 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
4859 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004860 Py_XDECREF(errorHandler);
4861 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004862 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004863
Benjamin Peterson29060642009-01-31 22:14:21 +00004864 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004865 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004866 Py_XDECREF(errorHandler);
4867 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004868 return NULL;
4869}
4870
Guido van Rossumd57fd912000-03-10 22:53:23 +00004871PyObject *PyUnicode_EncodeASCII(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004872 Py_ssize_t size,
4873 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004874{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004875 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004876}
4877
4878PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
4879{
4880 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004881 PyErr_BadArgument();
4882 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004883 }
4884 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004885 PyUnicode_GET_SIZE(unicode),
4886 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004887}
4888
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004889#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004890
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004891/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004892
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00004893#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004894#define NEED_RETRY
4895#endif
4896
4897/* XXX This code is limited to "true" double-byte encodings, as
4898 a) it assumes an incomplete character consists of a single byte, and
4899 b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
Benjamin Peterson29060642009-01-31 22:14:21 +00004900 encodings, see IsDBCSLeadByteEx documentation. */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004901
4902static int is_dbcs_lead_byte(const char *s, int offset)
4903{
4904 const char *curr = s + offset;
4905
4906 if (IsDBCSLeadByte(*curr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004907 const char *prev = CharPrev(s, curr);
4908 return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004909 }
4910 return 0;
4911}
4912
4913/*
4914 * Decode MBCS string into unicode object. If 'final' is set, converts
4915 * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
4916 */
4917static int decode_mbcs(PyUnicodeObject **v,
Benjamin Peterson29060642009-01-31 22:14:21 +00004918 const char *s, /* MBCS string */
4919 int size, /* sizeof MBCS string */
Victor Stinner554f3f02010-06-16 23:33:54 +00004920 int final,
4921 const char *errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004922{
4923 Py_UNICODE *p;
Victor Stinner554f3f02010-06-16 23:33:54 +00004924 Py_ssize_t n;
4925 DWORD usize;
4926 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004927
4928 assert(size >= 0);
4929
Victor Stinner554f3f02010-06-16 23:33:54 +00004930 /* check and handle 'errors' arg */
4931 if (errors==NULL || strcmp(errors, "strict")==0)
4932 flags = MB_ERR_INVALID_CHARS;
4933 else if (strcmp(errors, "ignore")==0)
4934 flags = 0;
4935 else {
4936 PyErr_Format(PyExc_ValueError,
4937 "mbcs encoding does not support errors='%s'",
4938 errors);
4939 return -1;
4940 }
4941
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004942 /* Skip trailing lead-byte unless 'final' is set */
4943 if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
Benjamin Peterson29060642009-01-31 22:14:21 +00004944 --size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004945
4946 /* First get the size of the result */
4947 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00004948 usize = MultiByteToWideChar(CP_ACP, flags, s, size, NULL, 0);
4949 if (usize==0)
4950 goto mbcs_decode_error;
4951 } else
4952 usize = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004953
4954 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004955 /* Create unicode object */
4956 *v = _PyUnicode_New(usize);
4957 if (*v == NULL)
4958 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00004959 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004960 }
4961 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004962 /* Extend unicode object */
4963 n = PyUnicode_GET_SIZE(*v);
4964 if (_PyUnicode_Resize(v, n + usize) < 0)
4965 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004966 }
4967
4968 /* Do the conversion */
Victor Stinner554f3f02010-06-16 23:33:54 +00004969 if (usize > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004970 p = PyUnicode_AS_UNICODE(*v) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00004971 if (0 == MultiByteToWideChar(CP_ACP, flags, s, size, p, usize)) {
4972 goto mbcs_decode_error;
Benjamin Peterson29060642009-01-31 22:14:21 +00004973 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004974 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004975 return size;
Victor Stinner554f3f02010-06-16 23:33:54 +00004976
4977mbcs_decode_error:
4978 /* If the last error was ERROR_NO_UNICODE_TRANSLATION, then
4979 we raise a UnicodeDecodeError - else it is a 'generic'
4980 windows error
4981 */
4982 if (GetLastError()==ERROR_NO_UNICODE_TRANSLATION) {
4983 /* Ideally, we should get reason from FormatMessage - this
4984 is the Windows 2000 English version of the message
4985 */
4986 PyObject *exc = NULL;
4987 const char *reason = "No mapping for the Unicode character exists "
4988 "in the target multi-byte code page.";
4989 make_decode_exception(&exc, "mbcs", s, size, 0, 0, reason);
4990 if (exc != NULL) {
4991 PyCodec_StrictErrors(exc);
4992 Py_DECREF(exc);
4993 }
4994 } else {
4995 PyErr_SetFromWindowsErrWithFilename(0, NULL);
4996 }
4997 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004998}
4999
5000PyObject *PyUnicode_DecodeMBCSStateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005001 Py_ssize_t size,
5002 const char *errors,
5003 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005004{
5005 PyUnicodeObject *v = NULL;
5006 int done;
5007
5008 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005009 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005010
5011#ifdef NEED_RETRY
5012 retry:
5013 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00005014 done = decode_mbcs(&v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005015 else
5016#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00005017 done = decode_mbcs(&v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005018
5019 if (done < 0) {
5020 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00005021 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005022 }
5023
5024 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005025 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005026
5027#ifdef NEED_RETRY
5028 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005029 s += done;
5030 size -= done;
5031 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005032 }
5033#endif
5034
5035 return (PyObject *)v;
5036}
5037
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005038PyObject *PyUnicode_DecodeMBCS(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005039 Py_ssize_t size,
5040 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005041{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005042 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
5043}
5044
5045/*
5046 * Convert unicode into string object (MBCS).
5047 * Returns 0 if succeed, -1 otherwise.
5048 */
5049static int encode_mbcs(PyObject **repr,
Benjamin Peterson29060642009-01-31 22:14:21 +00005050 const Py_UNICODE *p, /* unicode */
Victor Stinner554f3f02010-06-16 23:33:54 +00005051 int size, /* size of unicode */
5052 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005053{
Victor Stinner554f3f02010-06-16 23:33:54 +00005054 BOOL usedDefaultChar = FALSE;
5055 BOOL *pusedDefaultChar;
5056 int mbcssize;
5057 Py_ssize_t n;
5058 PyObject *exc = NULL;
5059 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005060
5061 assert(size >= 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005062
Victor Stinner554f3f02010-06-16 23:33:54 +00005063 /* check and handle 'errors' arg */
5064 if (errors==NULL || strcmp(errors, "strict")==0) {
5065 flags = WC_NO_BEST_FIT_CHARS;
5066 pusedDefaultChar = &usedDefaultChar;
5067 } else if (strcmp(errors, "replace")==0) {
5068 flags = 0;
5069 pusedDefaultChar = NULL;
5070 } else {
5071 PyErr_Format(PyExc_ValueError,
5072 "mbcs encoding does not support errors='%s'",
5073 errors);
5074 return -1;
5075 }
5076
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005077 /* First get the size of the result */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005078 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00005079 mbcssize = WideCharToMultiByte(CP_ACP, flags, p, size, NULL, 0,
5080 NULL, pusedDefaultChar);
Benjamin Peterson29060642009-01-31 22:14:21 +00005081 if (mbcssize == 0) {
5082 PyErr_SetFromWindowsErrWithFilename(0, NULL);
5083 return -1;
5084 }
Victor Stinner554f3f02010-06-16 23:33:54 +00005085 /* If we used a default char, then we failed! */
5086 if (pusedDefaultChar && *pusedDefaultChar)
5087 goto mbcs_encode_error;
5088 } else {
5089 mbcssize = 0;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005090 }
5091
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005092 if (*repr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005093 /* Create string object */
5094 *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
5095 if (*repr == NULL)
5096 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00005097 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005098 }
5099 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005100 /* Extend string object */
5101 n = PyBytes_Size(*repr);
5102 if (_PyBytes_Resize(repr, n + mbcssize) < 0)
5103 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005104 }
5105
5106 /* Do the conversion */
5107 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005108 char *s = PyBytes_AS_STRING(*repr) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00005109 if (0 == WideCharToMultiByte(CP_ACP, flags, p, size, s, mbcssize,
5110 NULL, pusedDefaultChar)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005111 PyErr_SetFromWindowsErrWithFilename(0, NULL);
5112 return -1;
5113 }
Victor Stinner554f3f02010-06-16 23:33:54 +00005114 if (pusedDefaultChar && *pusedDefaultChar)
5115 goto mbcs_encode_error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005116 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005117 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00005118
5119mbcs_encode_error:
5120 raise_encode_exception(&exc, "mbcs", p, size, 0, 0, "invalid character");
5121 Py_XDECREF(exc);
5122 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005123}
5124
5125PyObject *PyUnicode_EncodeMBCS(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00005126 Py_ssize_t size,
5127 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005128{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005129 PyObject *repr = NULL;
5130 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00005131
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005132#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00005133 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005134 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00005135 ret = encode_mbcs(&repr, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005136 else
5137#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00005138 ret = encode_mbcs(&repr, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005139
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005140 if (ret < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005141 Py_XDECREF(repr);
5142 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005143 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005144
5145#ifdef NEED_RETRY
5146 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005147 p += INT_MAX;
5148 size -= INT_MAX;
5149 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005150 }
5151#endif
5152
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005153 return repr;
5154}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00005155
Mark Hammond0ccda1e2003-07-01 00:13:27 +00005156PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
5157{
5158 if (!PyUnicode_Check(unicode)) {
5159 PyErr_BadArgument();
5160 return NULL;
5161 }
5162 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005163 PyUnicode_GET_SIZE(unicode),
5164 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00005165}
5166
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005167#undef NEED_RETRY
5168
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00005169#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005170
Guido van Rossumd57fd912000-03-10 22:53:23 +00005171/* --- Character Mapping Codec -------------------------------------------- */
5172
Guido van Rossumd57fd912000-03-10 22:53:23 +00005173PyObject *PyUnicode_DecodeCharmap(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005174 Py_ssize_t size,
5175 PyObject *mapping,
5176 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005177{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005178 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005179 Py_ssize_t startinpos;
5180 Py_ssize_t endinpos;
5181 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005182 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005183 PyUnicodeObject *v;
5184 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005185 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005186 PyObject *errorHandler = NULL;
5187 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005188 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005189 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00005190
Guido van Rossumd57fd912000-03-10 22:53:23 +00005191 /* Default to Latin-1 */
5192 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005193 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005194
5195 v = _PyUnicode_New(size);
5196 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005197 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005198 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005199 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005200 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005201 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005202 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005203 mapstring = PyUnicode_AS_UNICODE(mapping);
5204 maplen = PyUnicode_GET_SIZE(mapping);
5205 while (s < e) {
5206 unsigned char ch = *s;
5207 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005208
Benjamin Peterson29060642009-01-31 22:14:21 +00005209 if (ch < maplen)
5210 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005211
Benjamin Peterson29060642009-01-31 22:14:21 +00005212 if (x == 0xfffe) {
5213 /* undefined mapping */
5214 outpos = p-PyUnicode_AS_UNICODE(v);
5215 startinpos = s-starts;
5216 endinpos = startinpos+1;
5217 if (unicode_decode_call_errorhandler(
5218 errors, &errorHandler,
5219 "charmap", "character maps to <undefined>",
5220 &starts, &e, &startinpos, &endinpos, &exc, &s,
5221 &v, &outpos, &p)) {
5222 goto onError;
5223 }
5224 continue;
5225 }
5226 *p++ = x;
5227 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005228 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005229 }
5230 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005231 while (s < e) {
5232 unsigned char ch = *s;
5233 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005234
Benjamin Peterson29060642009-01-31 22:14:21 +00005235 /* Get mapping (char ordinal -> integer, Unicode char or None) */
5236 w = PyLong_FromLong((long)ch);
5237 if (w == NULL)
5238 goto onError;
5239 x = PyObject_GetItem(mapping, w);
5240 Py_DECREF(w);
5241 if (x == NULL) {
5242 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5243 /* No mapping found means: mapping is undefined. */
5244 PyErr_Clear();
5245 x = Py_None;
5246 Py_INCREF(x);
5247 } else
5248 goto onError;
5249 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005250
Benjamin Peterson29060642009-01-31 22:14:21 +00005251 /* Apply mapping */
5252 if (PyLong_Check(x)) {
5253 long value = PyLong_AS_LONG(x);
Antoine Pitrou6f80f5d2012-09-23 19:55:21 +02005254 if (value < 0 || value > 0x10FFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005255 PyErr_SetString(PyExc_TypeError,
Antoine Pitrou6f80f5d2012-09-23 19:55:21 +02005256 "character mapping must be in range(0x110000)");
Benjamin Peterson29060642009-01-31 22:14:21 +00005257 Py_DECREF(x);
5258 goto onError;
5259 }
Antoine Pitrou6f80f5d2012-09-23 19:55:21 +02005260
5261#ifndef Py_UNICODE_WIDE
5262 if (value > 0xFFFF) {
5263 /* see the code for 1-n mapping below */
5264 if (extrachars < 2) {
5265 /* resize first */
5266 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
5267 Py_ssize_t needed = 10 - extrachars;
5268 extrachars += needed;
5269 /* XXX overflow detection missing */
5270 if (_PyUnicode_Resize(&v,
5271 PyUnicode_GET_SIZE(v) + needed) < 0) {
5272 Py_DECREF(x);
5273 goto onError;
5274 }
5275 p = PyUnicode_AS_UNICODE(v) + oldpos;
5276 }
5277 value -= 0x10000;
5278 *p++ = 0xD800 | (value >> 10);
5279 *p++ = 0xDC00 | (value & 0x3FF);
5280 extrachars -= 2;
5281 }
5282 else
5283#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005284 *p++ = (Py_UNICODE)value;
5285 }
5286 else if (x == Py_None) {
5287 /* undefined mapping */
5288 outpos = p-PyUnicode_AS_UNICODE(v);
5289 startinpos = s-starts;
5290 endinpos = startinpos+1;
5291 if (unicode_decode_call_errorhandler(
5292 errors, &errorHandler,
5293 "charmap", "character maps to <undefined>",
5294 &starts, &e, &startinpos, &endinpos, &exc, &s,
5295 &v, &outpos, &p)) {
5296 Py_DECREF(x);
5297 goto onError;
5298 }
5299 Py_DECREF(x);
5300 continue;
5301 }
5302 else if (PyUnicode_Check(x)) {
5303 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005304
Benjamin Peterson29060642009-01-31 22:14:21 +00005305 if (targetsize == 1)
5306 /* 1-1 mapping */
5307 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005308
Benjamin Peterson29060642009-01-31 22:14:21 +00005309 else if (targetsize > 1) {
5310 /* 1-n mapping */
5311 if (targetsize > extrachars) {
5312 /* resize first */
5313 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
5314 Py_ssize_t needed = (targetsize - extrachars) + \
5315 (targetsize << 2);
5316 extrachars += needed;
5317 /* XXX overflow detection missing */
5318 if (_PyUnicode_Resize(&v,
5319 PyUnicode_GET_SIZE(v) + needed) < 0) {
5320 Py_DECREF(x);
5321 goto onError;
5322 }
5323 p = PyUnicode_AS_UNICODE(v) + oldpos;
5324 }
5325 Py_UNICODE_COPY(p,
5326 PyUnicode_AS_UNICODE(x),
5327 targetsize);
5328 p += targetsize;
5329 extrachars -= targetsize;
5330 }
5331 /* 1-0 mapping: skip the character */
5332 }
5333 else {
5334 /* wrong return value */
5335 PyErr_SetString(PyExc_TypeError,
5336 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00005337 Py_DECREF(x);
5338 goto onError;
5339 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005340 Py_DECREF(x);
5341 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005342 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005343 }
5344 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00005345 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
5346 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005347 Py_XDECREF(errorHandler);
5348 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005349 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00005350
Benjamin Peterson29060642009-01-31 22:14:21 +00005351 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005352 Py_XDECREF(errorHandler);
5353 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005354 Py_XDECREF(v);
5355 return NULL;
5356}
5357
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005358/* Charmap encoding: the lookup table */
5359
5360struct encoding_map{
Benjamin Peterson29060642009-01-31 22:14:21 +00005361 PyObject_HEAD
5362 unsigned char level1[32];
5363 int count2, count3;
5364 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005365};
5366
5367static PyObject*
5368encoding_map_size(PyObject *obj, PyObject* args)
5369{
5370 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005371 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00005372 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005373}
5374
5375static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005376 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00005377 PyDoc_STR("Return the size (in bytes) of this object") },
5378 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005379};
5380
5381static void
5382encoding_map_dealloc(PyObject* o)
5383{
Benjamin Peterson14339b62009-01-31 16:36:08 +00005384 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005385}
5386
5387static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005388 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005389 "EncodingMap", /*tp_name*/
5390 sizeof(struct encoding_map), /*tp_basicsize*/
5391 0, /*tp_itemsize*/
5392 /* methods */
5393 encoding_map_dealloc, /*tp_dealloc*/
5394 0, /*tp_print*/
5395 0, /*tp_getattr*/
5396 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00005397 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00005398 0, /*tp_repr*/
5399 0, /*tp_as_number*/
5400 0, /*tp_as_sequence*/
5401 0, /*tp_as_mapping*/
5402 0, /*tp_hash*/
5403 0, /*tp_call*/
5404 0, /*tp_str*/
5405 0, /*tp_getattro*/
5406 0, /*tp_setattro*/
5407 0, /*tp_as_buffer*/
5408 Py_TPFLAGS_DEFAULT, /*tp_flags*/
5409 0, /*tp_doc*/
5410 0, /*tp_traverse*/
5411 0, /*tp_clear*/
5412 0, /*tp_richcompare*/
5413 0, /*tp_weaklistoffset*/
5414 0, /*tp_iter*/
5415 0, /*tp_iternext*/
5416 encoding_map_methods, /*tp_methods*/
5417 0, /*tp_members*/
5418 0, /*tp_getset*/
5419 0, /*tp_base*/
5420 0, /*tp_dict*/
5421 0, /*tp_descr_get*/
5422 0, /*tp_descr_set*/
5423 0, /*tp_dictoffset*/
5424 0, /*tp_init*/
5425 0, /*tp_alloc*/
5426 0, /*tp_new*/
5427 0, /*tp_free*/
5428 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005429};
5430
5431PyObject*
5432PyUnicode_BuildEncodingMap(PyObject* string)
5433{
5434 Py_UNICODE *decode;
5435 PyObject *result;
5436 struct encoding_map *mresult;
5437 int i;
5438 int need_dict = 0;
5439 unsigned char level1[32];
5440 unsigned char level2[512];
5441 unsigned char *mlevel1, *mlevel2, *mlevel3;
5442 int count2 = 0, count3 = 0;
5443
5444 if (!PyUnicode_Check(string) || PyUnicode_GetSize(string) != 256) {
5445 PyErr_BadArgument();
5446 return NULL;
5447 }
5448 decode = PyUnicode_AS_UNICODE(string);
5449 memset(level1, 0xFF, sizeof level1);
5450 memset(level2, 0xFF, sizeof level2);
5451
5452 /* If there isn't a one-to-one mapping of NULL to \0,
5453 or if there are non-BMP characters, we need to use
5454 a mapping dictionary. */
5455 if (decode[0] != 0)
5456 need_dict = 1;
5457 for (i = 1; i < 256; i++) {
5458 int l1, l2;
5459 if (decode[i] == 0
Benjamin Peterson29060642009-01-31 22:14:21 +00005460#ifdef Py_UNICODE_WIDE
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005461 || decode[i] > 0xFFFF
Benjamin Peterson29060642009-01-31 22:14:21 +00005462#endif
5463 ) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005464 need_dict = 1;
5465 break;
5466 }
5467 if (decode[i] == 0xFFFE)
5468 /* unmapped character */
5469 continue;
5470 l1 = decode[i] >> 11;
5471 l2 = decode[i] >> 7;
5472 if (level1[l1] == 0xFF)
5473 level1[l1] = count2++;
5474 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00005475 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005476 }
5477
5478 if (count2 >= 0xFF || count3 >= 0xFF)
5479 need_dict = 1;
5480
5481 if (need_dict) {
5482 PyObject *result = PyDict_New();
5483 PyObject *key, *value;
5484 if (!result)
5485 return NULL;
5486 for (i = 0; i < 256; i++) {
5487 key = value = NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00005488 key = PyLong_FromLong(decode[i]);
5489 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005490 if (!key || !value)
5491 goto failed1;
5492 if (PyDict_SetItem(result, key, value) == -1)
5493 goto failed1;
5494 Py_DECREF(key);
5495 Py_DECREF(value);
5496 }
5497 return result;
5498 failed1:
5499 Py_XDECREF(key);
5500 Py_XDECREF(value);
5501 Py_DECREF(result);
5502 return NULL;
5503 }
5504
5505 /* Create a three-level trie */
5506 result = PyObject_MALLOC(sizeof(struct encoding_map) +
5507 16*count2 + 128*count3 - 1);
5508 if (!result)
5509 return PyErr_NoMemory();
5510 PyObject_Init(result, &EncodingMapType);
5511 mresult = (struct encoding_map*)result;
5512 mresult->count2 = count2;
5513 mresult->count3 = count3;
5514 mlevel1 = mresult->level1;
5515 mlevel2 = mresult->level23;
5516 mlevel3 = mresult->level23 + 16*count2;
5517 memcpy(mlevel1, level1, 32);
5518 memset(mlevel2, 0xFF, 16*count2);
5519 memset(mlevel3, 0, 128*count3);
5520 count3 = 0;
5521 for (i = 1; i < 256; i++) {
5522 int o1, o2, o3, i2, i3;
5523 if (decode[i] == 0xFFFE)
5524 /* unmapped character */
5525 continue;
5526 o1 = decode[i]>>11;
5527 o2 = (decode[i]>>7) & 0xF;
5528 i2 = 16*mlevel1[o1] + o2;
5529 if (mlevel2[i2] == 0xFF)
5530 mlevel2[i2] = count3++;
5531 o3 = decode[i] & 0x7F;
5532 i3 = 128*mlevel2[i2] + o3;
5533 mlevel3[i3] = i;
5534 }
5535 return result;
5536}
5537
5538static int
5539encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
5540{
5541 struct encoding_map *map = (struct encoding_map*)mapping;
5542 int l1 = c>>11;
5543 int l2 = (c>>7) & 0xF;
5544 int l3 = c & 0x7F;
5545 int i;
5546
5547#ifdef Py_UNICODE_WIDE
5548 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005549 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005550 }
5551#endif
5552 if (c == 0)
5553 return 0;
5554 /* level 1*/
5555 i = map->level1[l1];
5556 if (i == 0xFF) {
5557 return -1;
5558 }
5559 /* level 2*/
5560 i = map->level23[16*i+l2];
5561 if (i == 0xFF) {
5562 return -1;
5563 }
5564 /* level 3 */
5565 i = map->level23[16*map->count2 + 128*i + l3];
5566 if (i == 0) {
5567 return -1;
5568 }
5569 return i;
5570}
5571
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005572/* Lookup the character ch in the mapping. If the character
5573 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00005574 error occurred). */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005575static PyObject *charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005576{
Christian Heimes217cfd12007-12-02 14:31:20 +00005577 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005578 PyObject *x;
5579
5580 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005581 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005582 x = PyObject_GetItem(mapping, w);
5583 Py_DECREF(w);
5584 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005585 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5586 /* No mapping found means: mapping is undefined. */
5587 PyErr_Clear();
5588 x = Py_None;
5589 Py_INCREF(x);
5590 return x;
5591 } else
5592 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005593 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00005594 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00005595 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00005596 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005597 long value = PyLong_AS_LONG(x);
5598 if (value < 0 || value > 255) {
5599 PyErr_SetString(PyExc_TypeError,
5600 "character mapping must be in range(256)");
5601 Py_DECREF(x);
5602 return NULL;
5603 }
5604 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005605 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005606 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00005607 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005608 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005609 /* wrong return value */
5610 PyErr_Format(PyExc_TypeError,
5611 "character mapping must return integer, bytes or None, not %.400s",
5612 x->ob_type->tp_name);
5613 Py_DECREF(x);
5614 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005615 }
5616}
5617
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005618static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00005619charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005620{
Benjamin Peterson14339b62009-01-31 16:36:08 +00005621 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
5622 /* exponentially overallocate to minimize reallocations */
5623 if (requiredsize < 2*outsize)
5624 requiredsize = 2*outsize;
5625 if (_PyBytes_Resize(outobj, requiredsize))
5626 return -1;
5627 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005628}
5629
Benjamin Peterson14339b62009-01-31 16:36:08 +00005630typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00005631 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005632}charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005633/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00005634 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005635 space is available. Return a new reference to the object that
5636 was put in the output buffer, or Py_None, if the mapping was undefined
5637 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00005638 reallocation error occurred. The caller must decref the result */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005639static
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005640charmapencode_result charmapencode_output(Py_UNICODE c, PyObject *mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00005641 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005642{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005643 PyObject *rep;
5644 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00005645 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005646
Christian Heimes90aa7642007-12-19 02:45:37 +00005647 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005648 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00005649 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005650 if (res == -1)
5651 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00005652 if (outsize<requiredsize)
5653 if (charmapencode_resize(outobj, outpos, requiredsize))
5654 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00005655 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005656 outstart[(*outpos)++] = (char)res;
5657 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005658 }
5659
5660 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005661 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005662 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005663 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005664 Py_DECREF(rep);
5665 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005666 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005667 if (PyLong_Check(rep)) {
5668 Py_ssize_t requiredsize = *outpos+1;
5669 if (outsize<requiredsize)
5670 if (charmapencode_resize(outobj, outpos, requiredsize)) {
5671 Py_DECREF(rep);
5672 return enc_EXCEPTION;
5673 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005674 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005675 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005676 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005677 else {
5678 const char *repchars = PyBytes_AS_STRING(rep);
5679 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
5680 Py_ssize_t requiredsize = *outpos+repsize;
5681 if (outsize<requiredsize)
5682 if (charmapencode_resize(outobj, outpos, requiredsize)) {
5683 Py_DECREF(rep);
5684 return enc_EXCEPTION;
5685 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005686 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005687 memcpy(outstart + *outpos, repchars, repsize);
5688 *outpos += repsize;
5689 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005690 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005691 Py_DECREF(rep);
5692 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005693}
5694
5695/* handle an error in PyUnicode_EncodeCharmap
5696 Return 0 on success, -1 on error */
5697static
5698int charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00005699 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005700 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00005701 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00005702 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005703{
5704 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005705 Py_ssize_t repsize;
5706 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005707 Py_UNICODE *uni2;
5708 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005709 Py_ssize_t collstartpos = *inpos;
5710 Py_ssize_t collendpos = *inpos+1;
5711 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005712 char *encoding = "charmap";
5713 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005714 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005715
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005716 /* find all unencodable characters */
5717 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005718 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00005719 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005720 int res = encoding_map_lookup(p[collendpos], mapping);
5721 if (res != -1)
5722 break;
5723 ++collendpos;
5724 continue;
5725 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005726
Benjamin Peterson29060642009-01-31 22:14:21 +00005727 rep = charmapencode_lookup(p[collendpos], mapping);
5728 if (rep==NULL)
5729 return -1;
5730 else if (rep!=Py_None) {
5731 Py_DECREF(rep);
5732 break;
5733 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005734 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00005735 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005736 }
5737 /* cache callback name lookup
5738 * (if not done yet, i.e. it's the first error) */
5739 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005740 if ((errors==NULL) || (!strcmp(errors, "strict")))
5741 *known_errorHandler = 1;
5742 else if (!strcmp(errors, "replace"))
5743 *known_errorHandler = 2;
5744 else if (!strcmp(errors, "ignore"))
5745 *known_errorHandler = 3;
5746 else if (!strcmp(errors, "xmlcharrefreplace"))
5747 *known_errorHandler = 4;
5748 else
5749 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005750 }
5751 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005752 case 1: /* strict */
5753 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5754 return -1;
5755 case 2: /* replace */
5756 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005757 x = charmapencode_output('?', mapping, res, respos);
5758 if (x==enc_EXCEPTION) {
5759 return -1;
5760 }
5761 else if (x==enc_FAILED) {
5762 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5763 return -1;
5764 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005765 }
5766 /* fall through */
5767 case 3: /* ignore */
5768 *inpos = collendpos;
5769 break;
5770 case 4: /* xmlcharrefreplace */
5771 /* generate replacement (temporarily (mis)uses p) */
5772 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005773 char buffer[2+29+1+1];
5774 char *cp;
5775 sprintf(buffer, "&#%d;", (int)p[collpos]);
5776 for (cp = buffer; *cp; ++cp) {
5777 x = charmapencode_output(*cp, mapping, res, respos);
5778 if (x==enc_EXCEPTION)
5779 return -1;
5780 else if (x==enc_FAILED) {
5781 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5782 return -1;
5783 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005784 }
5785 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005786 *inpos = collendpos;
5787 break;
5788 default:
5789 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00005790 encoding, reason, p, size, exceptionObject,
5791 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005792 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005793 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005794 if (PyBytes_Check(repunicode)) {
5795 /* Directly copy bytes result to output. */
5796 Py_ssize_t outsize = PyBytes_Size(*res);
5797 Py_ssize_t requiredsize;
5798 repsize = PyBytes_Size(repunicode);
5799 requiredsize = *respos + repsize;
5800 if (requiredsize > outsize)
5801 /* Make room for all additional bytes. */
5802 if (charmapencode_resize(res, respos, requiredsize)) {
5803 Py_DECREF(repunicode);
5804 return -1;
5805 }
5806 memcpy(PyBytes_AsString(*res) + *respos,
5807 PyBytes_AsString(repunicode), repsize);
5808 *respos += repsize;
5809 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005810 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00005811 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005812 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005813 /* generate replacement */
5814 repsize = PyUnicode_GET_SIZE(repunicode);
5815 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005816 x = charmapencode_output(*uni2, mapping, res, respos);
5817 if (x==enc_EXCEPTION) {
5818 return -1;
5819 }
5820 else if (x==enc_FAILED) {
5821 Py_DECREF(repunicode);
5822 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5823 return -1;
5824 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005825 }
5826 *inpos = newpos;
5827 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005828 }
5829 return 0;
5830}
5831
Guido van Rossumd57fd912000-03-10 22:53:23 +00005832PyObject *PyUnicode_EncodeCharmap(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00005833 Py_ssize_t size,
5834 PyObject *mapping,
5835 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005836{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005837 /* output object */
5838 PyObject *res = NULL;
5839 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005840 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005841 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005842 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005843 PyObject *errorHandler = NULL;
5844 PyObject *exc = NULL;
5845 /* the following variable is used for caching string comparisons
5846 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
5847 * 3=ignore, 4=xmlcharrefreplace */
5848 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005849
5850 /* Default to Latin-1 */
5851 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005852 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005853
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005854 /* allocate enough for a simple encoding without
5855 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00005856 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005857 if (res == NULL)
5858 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00005859 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005860 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005861
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005862 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005863 /* try to encode it */
5864 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
5865 if (x==enc_EXCEPTION) /* error */
5866 goto onError;
5867 if (x==enc_FAILED) { /* unencodable character */
5868 if (charmap_encoding_error(p, size, &inpos, mapping,
5869 &exc,
5870 &known_errorHandler, &errorHandler, errors,
5871 &res, &respos)) {
5872 goto onError;
5873 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005874 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005875 else
5876 /* done with this character => adjust input position */
5877 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005878 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005879
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005880 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00005881 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005882 if (_PyBytes_Resize(&res, respos) < 0)
5883 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005884
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005885 Py_XDECREF(exc);
5886 Py_XDECREF(errorHandler);
5887 return res;
5888
Benjamin Peterson29060642009-01-31 22:14:21 +00005889 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005890 Py_XDECREF(res);
5891 Py_XDECREF(exc);
5892 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005893 return NULL;
5894}
5895
5896PyObject *PyUnicode_AsCharmapString(PyObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00005897 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005898{
5899 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005900 PyErr_BadArgument();
5901 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005902 }
5903 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005904 PyUnicode_GET_SIZE(unicode),
5905 mapping,
5906 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005907}
5908
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005909/* create or adjust a UnicodeTranslateError */
5910static void make_translate_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005911 const Py_UNICODE *unicode, Py_ssize_t size,
5912 Py_ssize_t startpos, Py_ssize_t endpos,
5913 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005914{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005915 if (*exceptionObject == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005916 *exceptionObject = PyUnicodeTranslateError_Create(
Benjamin Peterson29060642009-01-31 22:14:21 +00005917 unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005918 }
5919 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005920 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
5921 goto onError;
5922 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
5923 goto onError;
5924 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
5925 goto onError;
5926 return;
5927 onError:
5928 Py_DECREF(*exceptionObject);
5929 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005930 }
5931}
5932
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005933/* raises a UnicodeTranslateError */
5934static void raise_translate_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005935 const Py_UNICODE *unicode, Py_ssize_t size,
5936 Py_ssize_t startpos, Py_ssize_t endpos,
5937 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005938{
5939 make_translate_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005940 unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005941 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005942 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005943}
5944
5945/* error handling callback helper:
5946 build arguments, call the callback and check the arguments,
5947 put the result into newpos and return the replacement string, which
5948 has to be freed by the caller */
5949static PyObject *unicode_translate_call_errorhandler(const char *errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00005950 PyObject **errorHandler,
5951 const char *reason,
5952 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
5953 Py_ssize_t startpos, Py_ssize_t endpos,
5954 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005955{
Benjamin Peterson142957c2008-07-04 19:55:29 +00005956 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005957
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005958 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005959 PyObject *restuple;
5960 PyObject *resunicode;
5961
5962 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005963 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005964 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005965 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005966 }
5967
5968 make_translate_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005969 unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005970 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005971 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005972
5973 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00005974 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005975 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005976 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005977 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00005978 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00005979 Py_DECREF(restuple);
5980 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005981 }
5982 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00005983 &resunicode, &i_newpos)) {
5984 Py_DECREF(restuple);
5985 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005986 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00005987 if (i_newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005988 *newpos = size+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005989 else
5990 *newpos = i_newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005991 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005992 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
5993 Py_DECREF(restuple);
5994 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005995 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005996 Py_INCREF(resunicode);
5997 Py_DECREF(restuple);
5998 return resunicode;
5999}
6000
6001/* Lookup the character ch in the mapping and put the result in result,
6002 which must be decrefed by the caller.
6003 Return 0 on success, -1 on error */
6004static
6005int charmaptranslate_lookup(Py_UNICODE c, PyObject *mapping, PyObject **result)
6006{
Christian Heimes217cfd12007-12-02 14:31:20 +00006007 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006008 PyObject *x;
6009
6010 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006011 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006012 x = PyObject_GetItem(mapping, w);
6013 Py_DECREF(w);
6014 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006015 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
6016 /* No mapping found means: use 1:1 mapping. */
6017 PyErr_Clear();
6018 *result = NULL;
6019 return 0;
6020 } else
6021 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006022 }
6023 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006024 *result = x;
6025 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006026 }
Christian Heimes217cfd12007-12-02 14:31:20 +00006027 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006028 long value = PyLong_AS_LONG(x);
6029 long max = PyUnicode_GetMax();
6030 if (value < 0 || value > max) {
6031 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00006032 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00006033 Py_DECREF(x);
6034 return -1;
6035 }
6036 *result = x;
6037 return 0;
6038 }
6039 else if (PyUnicode_Check(x)) {
6040 *result = x;
6041 return 0;
6042 }
6043 else {
6044 /* wrong return value */
6045 PyErr_SetString(PyExc_TypeError,
6046 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00006047 Py_DECREF(x);
6048 return -1;
6049 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006050}
6051/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00006052 if not reallocate and adjust various state variables.
6053 Return 0 on success, -1 on error */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006054static
Walter Dörwald4894c302003-10-24 14:25:28 +00006055int charmaptranslate_makespace(PyObject **outobj, Py_UNICODE **outp,
Benjamin Peterson29060642009-01-31 22:14:21 +00006056 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006057{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006058 Py_ssize_t oldsize = PyUnicode_GET_SIZE(*outobj);
Walter Dörwald4894c302003-10-24 14:25:28 +00006059 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006060 /* remember old output position */
6061 Py_ssize_t outpos = *outp-PyUnicode_AS_UNICODE(*outobj);
6062 /* exponentially overallocate to minimize reallocations */
6063 if (requiredsize < 2 * oldsize)
6064 requiredsize = 2 * oldsize;
6065 if (PyUnicode_Resize(outobj, requiredsize) < 0)
6066 return -1;
6067 *outp = PyUnicode_AS_UNICODE(*outobj) + outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006068 }
6069 return 0;
6070}
6071/* lookup the character, put the result in the output string and adjust
6072 various state variables. Return a new reference to the object that
6073 was put in the output buffer in *result, or Py_None, if the mapping was
6074 undefined (in which case no character was written).
6075 The called must decref result.
6076 Return 0 on success, -1 on error. */
6077static
Walter Dörwald4894c302003-10-24 14:25:28 +00006078int charmaptranslate_output(const Py_UNICODE *startinp, const Py_UNICODE *curinp,
Benjamin Peterson29060642009-01-31 22:14:21 +00006079 Py_ssize_t insize, PyObject *mapping, PyObject **outobj, Py_UNICODE **outp,
6080 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006081{
Walter Dörwald4894c302003-10-24 14:25:28 +00006082 if (charmaptranslate_lookup(*curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00006083 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006084 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006085 /* not found => default to 1:1 mapping */
6086 *(*outp)++ = *curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006087 }
6088 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00006089 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00006090 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006091 /* no overflow check, because we know that the space is enough */
6092 *(*outp)++ = (Py_UNICODE)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006093 }
6094 else if (PyUnicode_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006095 Py_ssize_t repsize = PyUnicode_GET_SIZE(*res);
6096 if (repsize==1) {
6097 /* no overflow check, because we know that the space is enough */
6098 *(*outp)++ = *PyUnicode_AS_UNICODE(*res);
6099 }
6100 else if (repsize!=0) {
6101 /* more than one character */
6102 Py_ssize_t requiredsize = (*outp-PyUnicode_AS_UNICODE(*outobj)) +
6103 (insize - (curinp-startinp)) +
6104 repsize - 1;
6105 if (charmaptranslate_makespace(outobj, outp, requiredsize))
6106 return -1;
6107 memcpy(*outp, PyUnicode_AS_UNICODE(*res), sizeof(Py_UNICODE)*repsize);
6108 *outp += repsize;
6109 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006110 }
6111 else
Benjamin Peterson29060642009-01-31 22:14:21 +00006112 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006113 return 0;
6114}
6115
6116PyObject *PyUnicode_TranslateCharmap(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00006117 Py_ssize_t size,
6118 PyObject *mapping,
6119 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006120{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006121 /* output object */
6122 PyObject *res = NULL;
6123 /* pointers to the beginning and end+1 of input */
6124 const Py_UNICODE *startp = p;
6125 const Py_UNICODE *endp = p + size;
6126 /* pointer into the output */
6127 Py_UNICODE *str;
6128 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006129 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006130 char *reason = "character maps to <undefined>";
6131 PyObject *errorHandler = NULL;
6132 PyObject *exc = NULL;
6133 /* the following variable is used for caching string comparisons
6134 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
6135 * 3=ignore, 4=xmlcharrefreplace */
6136 int known_errorHandler = -1;
6137
Guido van Rossumd57fd912000-03-10 22:53:23 +00006138 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006139 PyErr_BadArgument();
6140 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006141 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006142
6143 /* allocate enough for a simple 1:1 translation without
6144 replacements, if we need more, we'll resize */
6145 res = PyUnicode_FromUnicode(NULL, size);
6146 if (res == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006147 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006148 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006149 return res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006150 str = PyUnicode_AS_UNICODE(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006151
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006152 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006153 /* try to encode it */
6154 PyObject *x = NULL;
6155 if (charmaptranslate_output(startp, p, size, mapping, &res, &str, &x)) {
6156 Py_XDECREF(x);
6157 goto onError;
6158 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006159 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00006160 if (x!=Py_None) /* it worked => adjust input pointer */
6161 ++p;
6162 else { /* untranslatable character */
6163 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
6164 Py_ssize_t repsize;
6165 Py_ssize_t newpos;
6166 Py_UNICODE *uni2;
6167 /* startpos for collecting untranslatable chars */
6168 const Py_UNICODE *collstart = p;
6169 const Py_UNICODE *collend = p+1;
6170 const Py_UNICODE *coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006171
Benjamin Peterson29060642009-01-31 22:14:21 +00006172 /* find all untranslatable characters */
6173 while (collend < endp) {
6174 if (charmaptranslate_lookup(*collend, mapping, &x))
6175 goto onError;
6176 Py_XDECREF(x);
6177 if (x!=Py_None)
6178 break;
6179 ++collend;
6180 }
6181 /* cache callback name lookup
6182 * (if not done yet, i.e. it's the first error) */
6183 if (known_errorHandler==-1) {
6184 if ((errors==NULL) || (!strcmp(errors, "strict")))
6185 known_errorHandler = 1;
6186 else if (!strcmp(errors, "replace"))
6187 known_errorHandler = 2;
6188 else if (!strcmp(errors, "ignore"))
6189 known_errorHandler = 3;
6190 else if (!strcmp(errors, "xmlcharrefreplace"))
6191 known_errorHandler = 4;
6192 else
6193 known_errorHandler = 0;
6194 }
6195 switch (known_errorHandler) {
6196 case 1: /* strict */
6197 raise_translate_exception(&exc, startp, size, collstart-startp, collend-startp, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006198 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006199 case 2: /* replace */
6200 /* No need to check for space, this is a 1:1 replacement */
6201 for (coll = collstart; coll<collend; ++coll)
6202 *str++ = '?';
6203 /* fall through */
6204 case 3: /* ignore */
6205 p = collend;
6206 break;
6207 case 4: /* xmlcharrefreplace */
6208 /* generate replacement (temporarily (mis)uses p) */
6209 for (p = collstart; p < collend; ++p) {
6210 char buffer[2+29+1+1];
6211 char *cp;
6212 sprintf(buffer, "&#%d;", (int)*p);
6213 if (charmaptranslate_makespace(&res, &str,
6214 (str-PyUnicode_AS_UNICODE(res))+strlen(buffer)+(endp-collend)))
6215 goto onError;
6216 for (cp = buffer; *cp; ++cp)
6217 *str++ = *cp;
6218 }
6219 p = collend;
6220 break;
6221 default:
6222 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
6223 reason, startp, size, &exc,
6224 collstart-startp, collend-startp, &newpos);
6225 if (repunicode == NULL)
6226 goto onError;
6227 /* generate replacement */
6228 repsize = PyUnicode_GET_SIZE(repunicode);
6229 if (charmaptranslate_makespace(&res, &str,
6230 (str-PyUnicode_AS_UNICODE(res))+repsize+(endp-collend))) {
6231 Py_DECREF(repunicode);
6232 goto onError;
6233 }
6234 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2)
6235 *str++ = *uni2;
6236 p = startp + newpos;
6237 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006238 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006239 }
6240 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006241 /* Resize if we allocated to much */
6242 respos = str-PyUnicode_AS_UNICODE(res);
Walter Dörwald4894c302003-10-24 14:25:28 +00006243 if (respos<PyUnicode_GET_SIZE(res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006244 if (PyUnicode_Resize(&res, respos) < 0)
6245 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006246 }
6247 Py_XDECREF(exc);
6248 Py_XDECREF(errorHandler);
6249 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006250
Benjamin Peterson29060642009-01-31 22:14:21 +00006251 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006252 Py_XDECREF(res);
6253 Py_XDECREF(exc);
6254 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006255 return NULL;
6256}
6257
6258PyObject *PyUnicode_Translate(PyObject *str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006259 PyObject *mapping,
6260 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006261{
6262 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00006263
Guido van Rossumd57fd912000-03-10 22:53:23 +00006264 str = PyUnicode_FromObject(str);
6265 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006266 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006267 result = PyUnicode_TranslateCharmap(PyUnicode_AS_UNICODE(str),
Benjamin Peterson29060642009-01-31 22:14:21 +00006268 PyUnicode_GET_SIZE(str),
6269 mapping,
6270 errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006271 Py_DECREF(str);
6272 return result;
Tim Petersced69f82003-09-16 20:30:58 +00006273
Benjamin Peterson29060642009-01-31 22:14:21 +00006274 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006275 Py_XDECREF(str);
6276 return NULL;
6277}
Tim Petersced69f82003-09-16 20:30:58 +00006278
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00006279PyObject *
6280PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
6281 Py_ssize_t length)
6282{
6283 PyObject *result;
6284 Py_UNICODE *p; /* write pointer into result */
6285 Py_ssize_t i;
6286 /* Copy to a new string */
6287 result = (PyObject *)_PyUnicode_New(length);
6288 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
6289 if (result == NULL)
6290 return result;
6291 p = PyUnicode_AS_UNICODE(result);
6292 /* Iterate over code points */
6293 for (i = 0; i < length; i++) {
6294 Py_UNICODE ch =s[i];
6295 if (ch > 127) {
6296 int decimal = Py_UNICODE_TODECIMAL(ch);
6297 if (decimal >= 0)
6298 p[i] = '0' + decimal;
6299 }
6300 }
6301 return result;
6302}
Guido van Rossum9e896b32000-04-05 20:11:21 +00006303/* --- Decimal Encoder ---------------------------------------------------- */
6304
6305int PyUnicode_EncodeDecimal(Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00006306 Py_ssize_t length,
6307 char *output,
6308 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00006309{
6310 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006311 PyObject *errorHandler = NULL;
6312 PyObject *exc = NULL;
6313 const char *encoding = "decimal";
6314 const char *reason = "invalid decimal Unicode string";
6315 /* the following variable is used for caching string comparisons
6316 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6317 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00006318
6319 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006320 PyErr_BadArgument();
6321 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00006322 }
6323
6324 p = s;
6325 end = s + length;
6326 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006327 register Py_UNICODE ch = *p;
6328 int decimal;
6329 PyObject *repunicode;
6330 Py_ssize_t repsize;
6331 Py_ssize_t newpos;
6332 Py_UNICODE *uni2;
6333 Py_UNICODE *collstart;
6334 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00006335
Benjamin Peterson29060642009-01-31 22:14:21 +00006336 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006337 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00006338 ++p;
6339 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006340 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006341 decimal = Py_UNICODE_TODECIMAL(ch);
6342 if (decimal >= 0) {
6343 *output++ = '0' + decimal;
6344 ++p;
6345 continue;
6346 }
6347 if (0 < ch && ch < 256) {
6348 *output++ = (char)ch;
6349 ++p;
6350 continue;
6351 }
6352 /* All other characters are considered unencodable */
6353 collstart = p;
Victor Stinnerab1d16b2011-11-22 01:45:37 +01006354 for (collend = p+1; collend < end; collend++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006355 if ((0 < *collend && *collend < 256) ||
Victor Stinnerab1d16b2011-11-22 01:45:37 +01006356 Py_UNICODE_ISSPACE(*collend) ||
6357 0 <= Py_UNICODE_TODECIMAL(*collend))
Benjamin Peterson29060642009-01-31 22:14:21 +00006358 break;
6359 }
6360 /* cache callback name lookup
6361 * (if not done yet, i.e. it's the first error) */
6362 if (known_errorHandler==-1) {
6363 if ((errors==NULL) || (!strcmp(errors, "strict")))
6364 known_errorHandler = 1;
6365 else if (!strcmp(errors, "replace"))
6366 known_errorHandler = 2;
6367 else if (!strcmp(errors, "ignore"))
6368 known_errorHandler = 3;
6369 else if (!strcmp(errors, "xmlcharrefreplace"))
6370 known_errorHandler = 4;
6371 else
6372 known_errorHandler = 0;
6373 }
6374 switch (known_errorHandler) {
6375 case 1: /* strict */
6376 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
6377 goto onError;
6378 case 2: /* replace */
6379 for (p = collstart; p < collend; ++p)
6380 *output++ = '?';
6381 /* fall through */
6382 case 3: /* ignore */
6383 p = collend;
6384 break;
6385 case 4: /* xmlcharrefreplace */
6386 /* generate replacement (temporarily (mis)uses p) */
6387 for (p = collstart; p < collend; ++p)
6388 output += sprintf(output, "&#%d;", (int)*p);
6389 p = collend;
6390 break;
6391 default:
6392 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
6393 encoding, reason, s, length, &exc,
6394 collstart-s, collend-s, &newpos);
6395 if (repunicode == NULL)
6396 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006397 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006398 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006399 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
6400 Py_DECREF(repunicode);
6401 goto onError;
6402 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006403 /* generate replacement */
6404 repsize = PyUnicode_GET_SIZE(repunicode);
6405 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
6406 Py_UNICODE ch = *uni2;
6407 if (Py_UNICODE_ISSPACE(ch))
6408 *output++ = ' ';
6409 else {
6410 decimal = Py_UNICODE_TODECIMAL(ch);
6411 if (decimal >= 0)
6412 *output++ = '0' + decimal;
6413 else if (0 < ch && ch < 256)
6414 *output++ = (char)ch;
6415 else {
6416 Py_DECREF(repunicode);
6417 raise_encode_exception(&exc, encoding,
6418 s, length, collstart-s, collend-s, reason);
6419 goto onError;
6420 }
6421 }
6422 }
6423 p = s + newpos;
6424 Py_DECREF(repunicode);
6425 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00006426 }
6427 /* 0-terminate the output string */
6428 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006429 Py_XDECREF(exc);
6430 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00006431 return 0;
6432
Benjamin Peterson29060642009-01-31 22:14:21 +00006433 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006434 Py_XDECREF(exc);
6435 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00006436 return -1;
6437}
6438
Guido van Rossumd57fd912000-03-10 22:53:23 +00006439/* --- Helpers ------------------------------------------------------------ */
6440
Eric Smith8c663262007-08-25 02:26:07 +00006441#include "stringlib/unicodedefs.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00006442#include "stringlib/fastsearch.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006443
Thomas Wouters477c8d52006-05-27 19:21:47 +00006444#include "stringlib/count.h"
6445#include "stringlib/find.h"
6446#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006447#include "stringlib/split.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00006448
Eric Smith5807c412008-05-11 21:00:57 +00006449#define _Py_InsertThousandsGrouping _PyUnicode_InsertThousandsGrouping
Eric Smitha3b1ac82009-04-03 14:45:06 +00006450#define _Py_InsertThousandsGroupingLocale _PyUnicode_InsertThousandsGroupingLocale
Eric Smith5807c412008-05-11 21:00:57 +00006451#include "stringlib/localeutil.h"
6452
Thomas Wouters477c8d52006-05-27 19:21:47 +00006453/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006454#define ADJUST_INDICES(start, end, len) \
6455 if (end > len) \
6456 end = len; \
6457 else if (end < 0) { \
6458 end += len; \
6459 if (end < 0) \
6460 end = 0; \
6461 } \
6462 if (start < 0) { \
6463 start += len; \
6464 if (start < 0) \
6465 start = 0; \
6466 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00006467
Ezio Melotti93e7afc2011-08-22 14:08:38 +03006468/* _Py_UNICODE_NEXT is a private macro used to retrieve the character pointed
6469 * by 'ptr', possibly combining surrogate pairs on narrow builds.
6470 * 'ptr' and 'end' must be Py_UNICODE*, with 'ptr' pointing at the character
6471 * that should be returned and 'end' pointing to the end of the buffer.
6472 * ('end' is used on narrow builds to detect a lone surrogate at the
6473 * end of the buffer that should be returned unchanged.)
6474 * The ptr and end arguments should be side-effect free and ptr must an lvalue.
6475 * The type of the returned char is always Py_UCS4.
6476 *
6477 * Note: the macro advances ptr to next char, so it might have side-effects
6478 * (especially if used with other macros).
6479 */
6480
6481/* helper macros used by _Py_UNICODE_NEXT */
6482#define _Py_UNICODE_IS_HIGH_SURROGATE(ch) (0xD800 <= ch && ch <= 0xDBFF)
6483#define _Py_UNICODE_IS_LOW_SURROGATE(ch) (0xDC00 <= ch && ch <= 0xDFFF)
6484/* Join two surrogate characters and return a single Py_UCS4 value. */
6485#define _Py_UNICODE_JOIN_SURROGATES(high, low) \
6486 (((((Py_UCS4)(high) & 0x03FF) << 10) | \
6487 ((Py_UCS4)(low) & 0x03FF)) + 0x10000)
6488
6489#ifdef Py_UNICODE_WIDE
6490#define _Py_UNICODE_NEXT(ptr, end) *(ptr)++
6491#else
6492#define _Py_UNICODE_NEXT(ptr, end) \
6493 (((_Py_UNICODE_IS_HIGH_SURROGATE(*(ptr)) && (ptr) < (end)) && \
6494 _Py_UNICODE_IS_LOW_SURROGATE((ptr)[1])) ? \
6495 ((ptr) += 2,_Py_UNICODE_JOIN_SURROGATES((ptr)[-2], (ptr)[-1])) : \
6496 (Py_UCS4)*(ptr)++)
6497#endif
6498
Martin v. Löwis18e16552006-02-15 17:27:45 +00006499Py_ssize_t PyUnicode_Count(PyObject *str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00006500 PyObject *substr,
6501 Py_ssize_t start,
6502 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006503{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006504 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006505 PyUnicodeObject* str_obj;
6506 PyUnicodeObject* sub_obj;
Tim Petersced69f82003-09-16 20:30:58 +00006507
Thomas Wouters477c8d52006-05-27 19:21:47 +00006508 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
6509 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00006510 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006511 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
6512 if (!sub_obj) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006513 Py_DECREF(str_obj);
6514 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006515 }
Tim Petersced69f82003-09-16 20:30:58 +00006516
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006517 ADJUST_INDICES(start, end, str_obj->length);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006518 result = stringlib_count(
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006519 str_obj->str + start, end - start, sub_obj->str, sub_obj->length,
6520 PY_SSIZE_T_MAX
Thomas Wouters477c8d52006-05-27 19:21:47 +00006521 );
6522
6523 Py_DECREF(sub_obj);
6524 Py_DECREF(str_obj);
6525
Guido van Rossumd57fd912000-03-10 22:53:23 +00006526 return result;
6527}
6528
Martin v. Löwis18e16552006-02-15 17:27:45 +00006529Py_ssize_t PyUnicode_Find(PyObject *str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00006530 PyObject *sub,
6531 Py_ssize_t start,
6532 Py_ssize_t end,
6533 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006534{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006535 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00006536
Guido van Rossumd57fd912000-03-10 22:53:23 +00006537 str = PyUnicode_FromObject(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006538 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00006539 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006540 sub = PyUnicode_FromObject(sub);
6541 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006542 Py_DECREF(str);
6543 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006544 }
Tim Petersced69f82003-09-16 20:30:58 +00006545
Thomas Wouters477c8d52006-05-27 19:21:47 +00006546 if (direction > 0)
6547 result = stringlib_find_slice(
6548 PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
6549 PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
6550 start, end
6551 );
6552 else
6553 result = stringlib_rfind_slice(
6554 PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
6555 PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
6556 start, end
6557 );
6558
Guido van Rossumd57fd912000-03-10 22:53:23 +00006559 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006560 Py_DECREF(sub);
6561
Guido van Rossumd57fd912000-03-10 22:53:23 +00006562 return result;
6563}
6564
Tim Petersced69f82003-09-16 20:30:58 +00006565static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006566int tailmatch(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006567 PyUnicodeObject *substring,
6568 Py_ssize_t start,
6569 Py_ssize_t end,
6570 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006571{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006572 if (substring->length == 0)
6573 return 1;
6574
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006575 ADJUST_INDICES(start, end, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006576 end -= substring->length;
6577 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00006578 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006579
6580 if (direction > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006581 if (Py_UNICODE_MATCH(self, end, substring))
6582 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006583 } else {
6584 if (Py_UNICODE_MATCH(self, start, substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00006585 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006586 }
6587
6588 return 0;
6589}
6590
Martin v. Löwis18e16552006-02-15 17:27:45 +00006591Py_ssize_t PyUnicode_Tailmatch(PyObject *str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006592 PyObject *substr,
6593 Py_ssize_t start,
6594 Py_ssize_t end,
6595 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006596{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006597 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00006598
Guido van Rossumd57fd912000-03-10 22:53:23 +00006599 str = PyUnicode_FromObject(str);
6600 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006601 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006602 substr = PyUnicode_FromObject(substr);
6603 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006604 Py_DECREF(str);
6605 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006606 }
Tim Petersced69f82003-09-16 20:30:58 +00006607
Guido van Rossumd57fd912000-03-10 22:53:23 +00006608 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006609 (PyUnicodeObject *)substr,
6610 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006611 Py_DECREF(str);
6612 Py_DECREF(substr);
6613 return result;
6614}
6615
Guido van Rossumd57fd912000-03-10 22:53:23 +00006616/* Apply fixfct filter to the Unicode object self and return a
6617 reference to the modified object */
6618
Tim Petersced69f82003-09-16 20:30:58 +00006619static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006620PyObject *fixup(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006621 int (*fixfct)(PyUnicodeObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00006622{
6623
6624 PyUnicodeObject *u;
6625
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006626 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006627 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006628 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006629
6630 Py_UNICODE_COPY(u->str, self->str, self->length);
6631
Tim Peters7a29bd52001-09-12 03:03:31 +00006632 if (!fixfct(u) && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006633 /* fixfct should return TRUE if it modified the buffer. If
6634 FALSE, return a reference to the original buffer instead
6635 (to save space, not time) */
6636 Py_INCREF(self);
6637 Py_DECREF(u);
6638 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006639 }
6640 return (PyObject*) u;
6641}
6642
Tim Petersced69f82003-09-16 20:30:58 +00006643static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006644int fixupper(PyUnicodeObject *self)
6645{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006646 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006647 Py_UNICODE *s = self->str;
6648 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006649
Guido van Rossumd57fd912000-03-10 22:53:23 +00006650 while (len-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006651 register Py_UNICODE ch;
Tim Petersced69f82003-09-16 20:30:58 +00006652
Benjamin Peterson29060642009-01-31 22:14:21 +00006653 ch = Py_UNICODE_TOUPPER(*s);
6654 if (ch != *s) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006655 status = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006656 *s = ch;
6657 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006658 s++;
6659 }
6660
6661 return status;
6662}
6663
Tim Petersced69f82003-09-16 20:30:58 +00006664static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006665int fixlower(PyUnicodeObject *self)
6666{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006667 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006668 Py_UNICODE *s = self->str;
6669 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006670
Guido van Rossumd57fd912000-03-10 22:53:23 +00006671 while (len-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006672 register Py_UNICODE ch;
Tim Petersced69f82003-09-16 20:30:58 +00006673
Benjamin Peterson29060642009-01-31 22:14:21 +00006674 ch = Py_UNICODE_TOLOWER(*s);
6675 if (ch != *s) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006676 status = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006677 *s = ch;
6678 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006679 s++;
6680 }
6681
6682 return status;
6683}
6684
Tim Petersced69f82003-09-16 20:30:58 +00006685static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006686int fixswapcase(PyUnicodeObject *self)
6687{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006688 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006689 Py_UNICODE *s = self->str;
6690 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006691
Guido van Rossumd57fd912000-03-10 22:53:23 +00006692 while (len-- > 0) {
6693 if (Py_UNICODE_ISUPPER(*s)) {
6694 *s = Py_UNICODE_TOLOWER(*s);
6695 status = 1;
6696 } else if (Py_UNICODE_ISLOWER(*s)) {
6697 *s = Py_UNICODE_TOUPPER(*s);
6698 status = 1;
6699 }
6700 s++;
6701 }
6702
6703 return status;
6704}
6705
Tim Petersced69f82003-09-16 20:30:58 +00006706static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006707int fixcapitalize(PyUnicodeObject *self)
6708{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006709 Py_ssize_t len = self->length;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006710 Py_UNICODE *s = self->str;
6711 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006712
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006713 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006714 return 0;
Ezio Melottiee8d9982011-08-15 09:09:57 +03006715 if (!Py_UNICODE_ISUPPER(*s)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006716 *s = Py_UNICODE_TOUPPER(*s);
6717 status = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006718 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006719 s++;
6720 while (--len > 0) {
Ezio Melottiee8d9982011-08-15 09:09:57 +03006721 if (!Py_UNICODE_ISLOWER(*s)) {
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006722 *s = Py_UNICODE_TOLOWER(*s);
6723 status = 1;
6724 }
6725 s++;
6726 }
6727 return status;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006728}
6729
6730static
6731int fixtitle(PyUnicodeObject *self)
6732{
6733 register Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
6734 register Py_UNICODE *e;
6735 int previous_is_cased;
6736
6737 /* Shortcut for single character strings */
6738 if (PyUnicode_GET_SIZE(self) == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006739 Py_UNICODE ch = Py_UNICODE_TOTITLE(*p);
6740 if (*p != ch) {
6741 *p = ch;
6742 return 1;
6743 }
6744 else
6745 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006746 }
Tim Petersced69f82003-09-16 20:30:58 +00006747
Guido van Rossumd57fd912000-03-10 22:53:23 +00006748 e = p + PyUnicode_GET_SIZE(self);
6749 previous_is_cased = 0;
6750 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006751 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00006752
Benjamin Peterson29060642009-01-31 22:14:21 +00006753 if (previous_is_cased)
6754 *p = Py_UNICODE_TOLOWER(ch);
6755 else
6756 *p = Py_UNICODE_TOTITLE(ch);
Tim Petersced69f82003-09-16 20:30:58 +00006757
Benjamin Peterson29060642009-01-31 22:14:21 +00006758 if (Py_UNICODE_ISLOWER(ch) ||
6759 Py_UNICODE_ISUPPER(ch) ||
6760 Py_UNICODE_ISTITLE(ch))
6761 previous_is_cased = 1;
6762 else
6763 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006764 }
6765 return 1;
6766}
6767
Tim Peters8ce9f162004-08-27 01:49:32 +00006768PyObject *
6769PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006770{
Skip Montanaro6543b452004-09-16 03:28:13 +00006771 const Py_UNICODE blank = ' ';
6772 const Py_UNICODE *sep = &blank;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006773 Py_ssize_t seplen = 1;
Tim Peters05eba1f2004-08-27 21:32:02 +00006774 PyUnicodeObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00006775 Py_UNICODE *res_p; /* pointer to free byte in res's string area */
6776 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006777 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
6778 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00006779 PyObject *item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006780 Py_ssize_t sz, i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006781
Tim Peters05eba1f2004-08-27 21:32:02 +00006782 fseq = PySequence_Fast(seq, "");
6783 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006784 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00006785 }
6786
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006787 /* NOTE: the following code can't call back into Python code,
6788 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00006789 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006790
Tim Peters05eba1f2004-08-27 21:32:02 +00006791 seqlen = PySequence_Fast_GET_SIZE(fseq);
6792 /* If empty sequence, return u"". */
6793 if (seqlen == 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006794 res = _PyUnicode_New(0); /* empty sequence; return u"" */
6795 goto Done;
Tim Peters05eba1f2004-08-27 21:32:02 +00006796 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006797 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00006798 /* If singleton sequence with an exact Unicode, return that. */
6799 if (seqlen == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006800 item = items[0];
6801 if (PyUnicode_CheckExact(item)) {
6802 Py_INCREF(item);
6803 res = (PyUnicodeObject *)item;
6804 goto Done;
6805 }
Tim Peters8ce9f162004-08-27 01:49:32 +00006806 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006807 else {
6808 /* Set up sep and seplen */
6809 if (separator == NULL) {
6810 sep = &blank;
6811 seplen = 1;
Tim Peters05eba1f2004-08-27 21:32:02 +00006812 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006813 else {
6814 if (!PyUnicode_Check(separator)) {
6815 PyErr_Format(PyExc_TypeError,
6816 "separator: expected str instance,"
6817 " %.80s found",
6818 Py_TYPE(separator)->tp_name);
6819 goto onError;
6820 }
6821 sep = PyUnicode_AS_UNICODE(separator);
6822 seplen = PyUnicode_GET_SIZE(separator);
Tim Peters05eba1f2004-08-27 21:32:02 +00006823 }
6824 }
6825
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006826 /* There are at least two things to join, or else we have a subclass
6827 * of str in the sequence.
6828 * Do a pre-pass to figure out the total amount of space we'll
6829 * need (sz), and see whether all argument are strings.
6830 */
6831 sz = 0;
6832 for (i = 0; i < seqlen; i++) {
6833 const Py_ssize_t old_sz = sz;
6834 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00006835 if (!PyUnicode_Check(item)) {
6836 PyErr_Format(PyExc_TypeError,
6837 "sequence item %zd: expected str instance,"
6838 " %.80s found",
6839 i, Py_TYPE(item)->tp_name);
6840 goto onError;
6841 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006842 sz += PyUnicode_GET_SIZE(item);
6843 if (i != 0)
6844 sz += seplen;
6845 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
6846 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00006847 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006848 goto onError;
6849 }
6850 }
Tim Petersced69f82003-09-16 20:30:58 +00006851
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006852 res = _PyUnicode_New(sz);
6853 if (res == NULL)
6854 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00006855
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006856 /* Catenate everything. */
6857 res_p = PyUnicode_AS_UNICODE(res);
6858 for (i = 0; i < seqlen; ++i) {
6859 Py_ssize_t itemlen;
6860 item = items[i];
6861 itemlen = PyUnicode_GET_SIZE(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00006862 /* Copy item, and maybe the separator. */
6863 if (i) {
6864 Py_UNICODE_COPY(res_p, sep, seplen);
6865 res_p += seplen;
6866 }
6867 Py_UNICODE_COPY(res_p, PyUnicode_AS_UNICODE(item), itemlen);
6868 res_p += itemlen;
Tim Peters05eba1f2004-08-27 21:32:02 +00006869 }
Tim Peters8ce9f162004-08-27 01:49:32 +00006870
Benjamin Peterson29060642009-01-31 22:14:21 +00006871 Done:
Tim Peters05eba1f2004-08-27 21:32:02 +00006872 Py_DECREF(fseq);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006873 return (PyObject *)res;
6874
Benjamin Peterson29060642009-01-31 22:14:21 +00006875 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00006876 Py_DECREF(fseq);
Tim Peters8ce9f162004-08-27 01:49:32 +00006877 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006878 return NULL;
6879}
6880
Tim Petersced69f82003-09-16 20:30:58 +00006881static
6882PyUnicodeObject *pad(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006883 Py_ssize_t left,
6884 Py_ssize_t right,
6885 Py_UNICODE fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006886{
6887 PyUnicodeObject *u;
6888
6889 if (left < 0)
6890 left = 0;
6891 if (right < 0)
6892 right = 0;
6893
Tim Peters7a29bd52001-09-12 03:03:31 +00006894 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006895 Py_INCREF(self);
6896 return self;
6897 }
6898
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006899 if (left > PY_SSIZE_T_MAX - self->length ||
6900 right > PY_SSIZE_T_MAX - (left + self->length)) {
6901 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
6902 return NULL;
6903 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006904 u = _PyUnicode_New(left + self->length + right);
6905 if (u) {
6906 if (left)
6907 Py_UNICODE_FILL(u->str, fill, left);
6908 Py_UNICODE_COPY(u->str + left, self->str, self->length);
6909 if (right)
6910 Py_UNICODE_FILL(u->str + left + self->length, fill, right);
6911 }
6912
6913 return u;
6914}
6915
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006916PyObject *PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006917{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006918 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006919
6920 string = PyUnicode_FromObject(string);
6921 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006922 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006923
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006924 list = stringlib_splitlines(
6925 (PyObject*) string, PyUnicode_AS_UNICODE(string),
6926 PyUnicode_GET_SIZE(string), keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006927
6928 Py_DECREF(string);
6929 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006930}
6931
Tim Petersced69f82003-09-16 20:30:58 +00006932static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006933PyObject *split(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006934 PyUnicodeObject *substring,
6935 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006936{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006937 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006938 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006939
Guido van Rossumd57fd912000-03-10 22:53:23 +00006940 if (substring == NULL)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006941 return stringlib_split_whitespace(
6942 (PyObject*) self, self->str, self->length, maxcount
6943 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00006944
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006945 return stringlib_split(
6946 (PyObject*) self, self->str, self->length,
6947 substring->str, substring->length,
6948 maxcount
6949 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00006950}
6951
Tim Petersced69f82003-09-16 20:30:58 +00006952static
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006953PyObject *rsplit(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006954 PyUnicodeObject *substring,
6955 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006956{
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006957 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006958 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006959
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006960 if (substring == NULL)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006961 return stringlib_rsplit_whitespace(
6962 (PyObject*) self, self->str, self->length, maxcount
6963 );
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006964
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006965 return stringlib_rsplit(
6966 (PyObject*) self, self->str, self->length,
6967 substring->str, substring->length,
6968 maxcount
6969 );
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006970}
6971
6972static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006973PyObject *replace(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006974 PyUnicodeObject *str1,
6975 PyUnicodeObject *str2,
6976 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006977{
6978 PyUnicodeObject *u;
6979
6980 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006981 maxcount = PY_SSIZE_T_MAX;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006982 else if (maxcount == 0 || self->length == 0)
6983 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006984
Thomas Wouters477c8d52006-05-27 19:21:47 +00006985 if (str1->length == str2->length) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +00006986 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006987 /* same length */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006988 if (str1->length == 0)
6989 goto nothing;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006990 if (str1->length == 1) {
6991 /* replace characters */
6992 Py_UNICODE u1, u2;
6993 if (!findchar(self->str, self->length, str1->str[0]))
6994 goto nothing;
6995 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
6996 if (!u)
6997 return NULL;
6998 Py_UNICODE_COPY(u->str, self->str, self->length);
6999 u1 = str1->str[0];
7000 u2 = str2->str[0];
7001 for (i = 0; i < u->length; i++)
7002 if (u->str[i] == u1) {
7003 if (--maxcount < 0)
7004 break;
7005 u->str[i] = u2;
7006 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007007 } else {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007008 i = stringlib_find(
7009 self->str, self->length, str1->str, str1->length, 0
Guido van Rossumd57fd912000-03-10 22:53:23 +00007010 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00007011 if (i < 0)
7012 goto nothing;
7013 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
7014 if (!u)
7015 return NULL;
7016 Py_UNICODE_COPY(u->str, self->str, self->length);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007017
7018 /* change everything in-place, starting with this one */
7019 Py_UNICODE_COPY(u->str+i, str2->str, str2->length);
7020 i += str1->length;
7021
7022 while ( --maxcount > 0) {
7023 i = stringlib_find(self->str+i, self->length-i,
7024 str1->str, str1->length,
7025 i);
7026 if (i == -1)
7027 break;
7028 Py_UNICODE_COPY(u->str+i, str2->str, str2->length);
7029 i += str1->length;
7030 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007031 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007032 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00007033
Victor Stinnerab1d16b2011-11-22 01:45:37 +01007034 Py_ssize_t n, i, j;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007035 Py_ssize_t product, new_size, delta;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007036 Py_UNICODE *p;
7037
7038 /* replace strings */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007039 n = stringlib_count(self->str, self->length, str1->str, str1->length,
7040 maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007041 if (n == 0)
7042 goto nothing;
7043 /* new_size = self->length + n * (str2->length - str1->length)); */
7044 delta = (str2->length - str1->length);
7045 if (delta == 0) {
7046 new_size = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007047 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00007048 product = n * (str2->length - str1->length);
7049 if ((product / (str2->length - str1->length)) != n) {
7050 PyErr_SetString(PyExc_OverflowError,
7051 "replace string is too long");
7052 return NULL;
7053 }
7054 new_size = self->length + product;
7055 if (new_size < 0) {
7056 PyErr_SetString(PyExc_OverflowError,
7057 "replace string is too long");
7058 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007059 }
7060 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00007061 u = _PyUnicode_New(new_size);
7062 if (!u)
7063 return NULL;
7064 i = 0;
7065 p = u->str;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007066 if (str1->length > 0) {
7067 while (n-- > 0) {
7068 /* look for next match */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007069 j = stringlib_find(self->str+i, self->length-i,
7070 str1->str, str1->length,
7071 i);
7072 if (j == -1)
7073 break;
7074 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00007075 /* copy unchanged part [i:j] */
7076 Py_UNICODE_COPY(p, self->str+i, j-i);
7077 p += j - i;
7078 }
7079 /* copy substitution string */
7080 if (str2->length > 0) {
7081 Py_UNICODE_COPY(p, str2->str, str2->length);
7082 p += str2->length;
7083 }
7084 i = j + str1->length;
7085 }
7086 if (i < self->length)
7087 /* copy tail [i:] */
7088 Py_UNICODE_COPY(p, self->str+i, self->length-i);
7089 } else {
7090 /* interleave */
7091 while (n > 0) {
7092 Py_UNICODE_COPY(p, str2->str, str2->length);
7093 p += str2->length;
7094 if (--n <= 0)
7095 break;
7096 *p++ = self->str[i++];
7097 }
7098 Py_UNICODE_COPY(p, self->str+i, self->length-i);
7099 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007100 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007101 return (PyObject *) u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007102
Benjamin Peterson29060642009-01-31 22:14:21 +00007103 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00007104 /* nothing to replace; return original string (when possible) */
7105 if (PyUnicode_CheckExact(self)) {
7106 Py_INCREF(self);
7107 return (PyObject *) self;
7108 }
7109 return PyUnicode_FromUnicode(self->str, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007110}
7111
7112/* --- Unicode Object Methods --------------------------------------------- */
7113
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007114PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007115 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007116\n\
7117Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007118characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007119
7120static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007121unicode_title(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007122{
Guido van Rossumd57fd912000-03-10 22:53:23 +00007123 return fixup(self, fixtitle);
7124}
7125
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007126PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007127 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007128\n\
7129Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +00007130have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007131
7132static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007133unicode_capitalize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007134{
Guido van Rossumd57fd912000-03-10 22:53:23 +00007135 return fixup(self, fixcapitalize);
7136}
7137
7138#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007139PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007140 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007141\n\
7142Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007143normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007144
7145static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007146unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007147{
7148 PyObject *list;
7149 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007150 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007151
Guido van Rossumd57fd912000-03-10 22:53:23 +00007152 /* Split into words */
7153 list = split(self, NULL, -1);
7154 if (!list)
7155 return NULL;
7156
7157 /* Capitalize each word */
7158 for (i = 0; i < PyList_GET_SIZE(list); i++) {
7159 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00007160 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007161 if (item == NULL)
7162 goto onError;
7163 Py_DECREF(PyList_GET_ITEM(list, i));
7164 PyList_SET_ITEM(list, i, item);
7165 }
7166
7167 /* Join the words to form a new string */
7168 item = PyUnicode_Join(NULL, list);
7169
Benjamin Peterson29060642009-01-31 22:14:21 +00007170 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007171 Py_DECREF(list);
7172 return (PyObject *)item;
7173}
7174#endif
7175
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007176/* Argument converter. Coerces to a single unicode character */
7177
7178static int
7179convert_uc(PyObject *obj, void *addr)
7180{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007181 Py_UNICODE *fillcharloc = (Py_UNICODE *)addr;
7182 PyObject *uniobj;
7183 Py_UNICODE *unistr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007184
Benjamin Peterson14339b62009-01-31 16:36:08 +00007185 uniobj = PyUnicode_FromObject(obj);
7186 if (uniobj == NULL) {
7187 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00007188 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007189 return 0;
7190 }
7191 if (PyUnicode_GET_SIZE(uniobj) != 1) {
7192 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00007193 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007194 Py_DECREF(uniobj);
7195 return 0;
7196 }
7197 unistr = PyUnicode_AS_UNICODE(uniobj);
7198 *fillcharloc = unistr[0];
7199 Py_DECREF(uniobj);
7200 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007201}
7202
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007203PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007204 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007205\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007206Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007207done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007208
7209static PyObject *
7210unicode_center(PyUnicodeObject *self, PyObject *args)
7211{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007212 Py_ssize_t marg, left;
7213 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007214 Py_UNICODE fillchar = ' ';
Guido van Rossumd57fd912000-03-10 22:53:23 +00007215
Thomas Woutersde017742006-02-16 19:34:37 +00007216 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007217 return NULL;
7218
Tim Peters7a29bd52001-09-12 03:03:31 +00007219 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00007220 Py_INCREF(self);
7221 return (PyObject*) self;
7222 }
7223
7224 marg = width - self->length;
7225 left = marg / 2 + (marg & width & 1);
7226
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007227 return (PyObject*) pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007228}
7229
Marc-André Lemburge5034372000-08-08 08:04:29 +00007230#if 0
7231
7232/* This code should go into some future Unicode collation support
7233 module. The basic comparison should compare ordinals on a naive
Georg Brandlc6c31782009-06-08 13:41:29 +00007234 basis (this is what Java does and thus Jython too). */
Marc-André Lemburge5034372000-08-08 08:04:29 +00007235
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007236/* speedy UTF-16 code point order comparison */
7237/* gleaned from: */
7238/* http://www-4.ibm.com/software/developer/library/utf16.html?dwzone=unicode */
7239
Marc-André Lemburge12896e2000-07-07 17:51:08 +00007240static short utf16Fixup[32] =
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007241{
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007242 0, 0, 0, 0, 0, 0, 0, 0,
Tim Petersced69f82003-09-16 20:30:58 +00007243 0, 0, 0, 0, 0, 0, 0, 0,
7244 0, 0, 0, 0, 0, 0, 0, 0,
Marc-André Lemburge12896e2000-07-07 17:51:08 +00007245 0, 0, 0, 0x2000, -0x800, -0x800, -0x800, -0x800
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007246};
7247
Guido van Rossumd57fd912000-03-10 22:53:23 +00007248static int
7249unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
7250{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007251 Py_ssize_t len1, len2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007252
Guido van Rossumd57fd912000-03-10 22:53:23 +00007253 Py_UNICODE *s1 = str1->str;
7254 Py_UNICODE *s2 = str2->str;
7255
7256 len1 = str1->length;
7257 len2 = str2->length;
Tim Petersced69f82003-09-16 20:30:58 +00007258
Guido van Rossumd57fd912000-03-10 22:53:23 +00007259 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00007260 Py_UNICODE c1, c2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007261
7262 c1 = *s1++;
7263 c2 = *s2++;
Fredrik Lundh45714e92001-06-26 16:39:36 +00007264
Benjamin Peterson29060642009-01-31 22:14:21 +00007265 if (c1 > (1<<11) * 26)
7266 c1 += utf16Fixup[c1>>11];
7267 if (c2 > (1<<11) * 26)
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007268 c2 += utf16Fixup[c2>>11];
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007269 /* now c1 and c2 are in UTF-32-compatible order */
Fredrik Lundh45714e92001-06-26 16:39:36 +00007270
7271 if (c1 != c2)
7272 return (c1 < c2) ? -1 : 1;
Tim Petersced69f82003-09-16 20:30:58 +00007273
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007274 len1--; len2--;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007275 }
7276
7277 return (len1 < len2) ? -1 : (len1 != len2);
7278}
7279
Marc-André Lemburge5034372000-08-08 08:04:29 +00007280#else
7281
7282static int
7283unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
7284{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007285 register Py_ssize_t len1, len2;
Marc-André Lemburge5034372000-08-08 08:04:29 +00007286
7287 Py_UNICODE *s1 = str1->str;
7288 Py_UNICODE *s2 = str2->str;
7289
7290 len1 = str1->length;
7291 len2 = str2->length;
Tim Petersced69f82003-09-16 20:30:58 +00007292
Marc-André Lemburge5034372000-08-08 08:04:29 +00007293 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00007294 Py_UNICODE c1, c2;
Marc-André Lemburge5034372000-08-08 08:04:29 +00007295
Fredrik Lundh45714e92001-06-26 16:39:36 +00007296 c1 = *s1++;
7297 c2 = *s2++;
7298
7299 if (c1 != c2)
7300 return (c1 < c2) ? -1 : 1;
7301
Marc-André Lemburge5034372000-08-08 08:04:29 +00007302 len1--; len2--;
7303 }
7304
7305 return (len1 < len2) ? -1 : (len1 != len2);
7306}
7307
7308#endif
7309
Guido van Rossumd57fd912000-03-10 22:53:23 +00007310int PyUnicode_Compare(PyObject *left,
Benjamin Peterson29060642009-01-31 22:14:21 +00007311 PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007312{
Guido van Rossum09dc34f2007-05-04 04:17:33 +00007313 if (PyUnicode_Check(left) && PyUnicode_Check(right))
7314 return unicode_compare((PyUnicodeObject *)left,
7315 (PyUnicodeObject *)right);
Guido van Rossum09dc34f2007-05-04 04:17:33 +00007316 PyErr_Format(PyExc_TypeError,
7317 "Can't compare %.100s and %.100s",
7318 left->ob_type->tp_name,
7319 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007320 return -1;
7321}
7322
Martin v. Löwis5b222132007-06-10 09:51:05 +00007323int
7324PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
7325{
7326 int i;
7327 Py_UNICODE *id;
7328 assert(PyUnicode_Check(uni));
7329 id = PyUnicode_AS_UNICODE(uni);
7330 /* Compare Unicode string and source character set string */
7331 for (i = 0; id[i] && str[i]; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00007332 if (id[i] != str[i])
7333 return ((int)id[i] < (int)str[i]) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +00007334 /* This check keeps Python strings that end in '\0' from comparing equal
7335 to C strings identical up to that point. */
Benjamin Petersona23831f2010-04-25 21:54:00 +00007336 if (PyUnicode_GET_SIZE(uni) != i || id[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00007337 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00007338 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00007339 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00007340 return 0;
7341}
7342
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007343
Benjamin Peterson29060642009-01-31 22:14:21 +00007344#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +00007345 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007346
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007347PyObject *PyUnicode_RichCompare(PyObject *left,
7348 PyObject *right,
7349 int op)
7350{
7351 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007352
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007353 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
7354 PyObject *v;
7355 if (((PyUnicodeObject *) left)->length !=
7356 ((PyUnicodeObject *) right)->length) {
7357 if (op == Py_EQ) {
7358 Py_INCREF(Py_False);
7359 return Py_False;
7360 }
7361 if (op == Py_NE) {
7362 Py_INCREF(Py_True);
7363 return Py_True;
7364 }
7365 }
7366 if (left == right)
7367 result = 0;
7368 else
7369 result = unicode_compare((PyUnicodeObject *)left,
7370 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007371
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007372 /* Convert the return value to a Boolean */
7373 switch (op) {
7374 case Py_EQ:
7375 v = TEST_COND(result == 0);
7376 break;
7377 case Py_NE:
7378 v = TEST_COND(result != 0);
7379 break;
7380 case Py_LE:
7381 v = TEST_COND(result <= 0);
7382 break;
7383 case Py_GE:
7384 v = TEST_COND(result >= 0);
7385 break;
7386 case Py_LT:
7387 v = TEST_COND(result == -1);
7388 break;
7389 case Py_GT:
7390 v = TEST_COND(result == 1);
7391 break;
7392 default:
7393 PyErr_BadArgument();
7394 return NULL;
7395 }
7396 Py_INCREF(v);
7397 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007398 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007399
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007400 Py_INCREF(Py_NotImplemented);
7401 return Py_NotImplemented;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007402}
7403
Guido van Rossum403d68b2000-03-13 15:55:09 +00007404int PyUnicode_Contains(PyObject *container,
Benjamin Peterson29060642009-01-31 22:14:21 +00007405 PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +00007406{
Thomas Wouters477c8d52006-05-27 19:21:47 +00007407 PyObject *str, *sub;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007408 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007409
7410 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +00007411 sub = PyUnicode_FromObject(element);
7412 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007413 PyErr_Format(PyExc_TypeError,
7414 "'in <string>' requires string as left operand, not %s",
7415 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007416 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007417 }
7418
Thomas Wouters477c8d52006-05-27 19:21:47 +00007419 str = PyUnicode_FromObject(container);
7420 if (!str) {
7421 Py_DECREF(sub);
7422 return -1;
7423 }
7424
7425 result = stringlib_contains_obj(str, sub);
7426
7427 Py_DECREF(str);
7428 Py_DECREF(sub);
7429
Guido van Rossum403d68b2000-03-13 15:55:09 +00007430 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007431}
7432
Guido van Rossumd57fd912000-03-10 22:53:23 +00007433/* Concat to string or Unicode object giving a new Unicode object. */
7434
7435PyObject *PyUnicode_Concat(PyObject *left,
Benjamin Peterson29060642009-01-31 22:14:21 +00007436 PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007437{
7438 PyUnicodeObject *u = NULL, *v = NULL, *w;
7439
7440 /* Coerce the two arguments */
7441 u = (PyUnicodeObject *)PyUnicode_FromObject(left);
7442 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007443 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007444 v = (PyUnicodeObject *)PyUnicode_FromObject(right);
7445 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007446 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007447
7448 /* Shortcuts */
7449 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007450 Py_DECREF(v);
7451 return (PyObject *)u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007452 }
7453 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007454 Py_DECREF(u);
7455 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007456 }
7457
7458 /* Concat the two Unicode strings */
7459 w = _PyUnicode_New(u->length + v->length);
7460 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007461 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007462 Py_UNICODE_COPY(w->str, u->str, u->length);
7463 Py_UNICODE_COPY(w->str + u->length, v->str, v->length);
7464
7465 Py_DECREF(u);
7466 Py_DECREF(v);
7467 return (PyObject *)w;
7468
Benjamin Peterson29060642009-01-31 22:14:21 +00007469 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007470 Py_XDECREF(u);
7471 Py_XDECREF(v);
7472 return NULL;
7473}
7474
Walter Dörwald1ab83302007-05-18 17:15:44 +00007475void
7476PyUnicode_Append(PyObject **pleft, PyObject *right)
7477{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007478 PyObject *new;
7479 if (*pleft == NULL)
7480 return;
7481 if (right == NULL || !PyUnicode_Check(*pleft)) {
7482 Py_DECREF(*pleft);
7483 *pleft = NULL;
7484 return;
7485 }
7486 new = PyUnicode_Concat(*pleft, right);
7487 Py_DECREF(*pleft);
7488 *pleft = new;
Walter Dörwald1ab83302007-05-18 17:15:44 +00007489}
7490
7491void
7492PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
7493{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007494 PyUnicode_Append(pleft, right);
7495 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +00007496}
7497
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007498PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007499 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007500\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00007501Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007502string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007503interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007504
7505static PyObject *
7506unicode_count(PyUnicodeObject *self, PyObject *args)
7507{
7508 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007509 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007510 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007511 PyObject *result;
7512
Jesus Ceaac451502011-04-20 17:09:23 +02007513 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
7514 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +00007515 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007516
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007517 ADJUST_INDICES(start, end, self->length);
Christian Heimes217cfd12007-12-02 14:31:20 +00007518 result = PyLong_FromSsize_t(
Thomas Wouters477c8d52006-05-27 19:21:47 +00007519 stringlib_count(self->str + start, end - start,
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007520 substring->str, substring->length,
7521 PY_SSIZE_T_MAX)
Thomas Wouters477c8d52006-05-27 19:21:47 +00007522 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007523
7524 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007525
Guido van Rossumd57fd912000-03-10 22:53:23 +00007526 return result;
7527}
7528
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007529PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +00007530 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007531\n\
Victor Stinnere14e2122010-11-07 18:41:46 +00007532Encode S using the codec registered for encoding. Default encoding\n\
7533is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +00007534handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007535a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
7536'xmlcharrefreplace' as well as any other name registered with\n\
7537codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007538
7539static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +00007540unicode_encode(PyUnicodeObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007541{
Benjamin Peterson308d6372009-09-18 21:42:35 +00007542 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +00007543 char *encoding = NULL;
7544 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +00007545
Benjamin Peterson308d6372009-09-18 21:42:35 +00007546 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
7547 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007548 return NULL;
Georg Brandl3b9406b2010-12-03 07:54:09 +00007549 return PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007550}
7551
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007552PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007553 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007554\n\
7555Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007556If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007557
7558static PyObject*
7559unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
7560{
7561 Py_UNICODE *e;
7562 Py_UNICODE *p;
7563 Py_UNICODE *q;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007564 Py_UNICODE *qe;
7565 Py_ssize_t i, j, incr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007566 PyUnicodeObject *u;
7567 int tabsize = 8;
7568
7569 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00007570 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007571
Thomas Wouters7e474022000-07-16 12:04:32 +00007572 /* First pass: determine size of output string */
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007573 i = 0; /* chars up to and including most recent \n or \r */
7574 j = 0; /* chars since most recent \n or \r (use in tab calculations) */
7575 e = self->str + self->length; /* end of input */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007576 for (p = self->str; p < e; p++)
7577 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007578 if (tabsize > 0) {
7579 incr = tabsize - (j % tabsize); /* cannot overflow */
7580 if (j > PY_SSIZE_T_MAX - incr)
7581 goto overflow1;
7582 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007583 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007584 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007585 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007586 if (j > PY_SSIZE_T_MAX - 1)
7587 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007588 j++;
7589 if (*p == '\n' || *p == '\r') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007590 if (i > PY_SSIZE_T_MAX - j)
7591 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007592 i += j;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007593 j = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007594 }
7595 }
7596
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007597 if (i > PY_SSIZE_T_MAX - j)
Benjamin Peterson29060642009-01-31 22:14:21 +00007598 goto overflow1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007599
Guido van Rossumd57fd912000-03-10 22:53:23 +00007600 /* Second pass: create output string and fill it */
7601 u = _PyUnicode_New(i + j);
7602 if (!u)
7603 return NULL;
7604
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007605 j = 0; /* same as in first pass */
7606 q = u->str; /* next output char */
7607 qe = u->str + u->length; /* end of output */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007608
7609 for (p = self->str; p < e; p++)
7610 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007611 if (tabsize > 0) {
7612 i = tabsize - (j % tabsize);
7613 j += i;
7614 while (i--) {
7615 if (q >= qe)
7616 goto overflow2;
7617 *q++ = ' ';
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007618 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007619 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007620 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007621 else {
7622 if (q >= qe)
7623 goto overflow2;
7624 *q++ = *p;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007625 j++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007626 if (*p == '\n' || *p == '\r')
7627 j = 0;
7628 }
7629
7630 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007631
7632 overflow2:
7633 Py_DECREF(u);
7634 overflow1:
7635 PyErr_SetString(PyExc_OverflowError, "new string is too long");
7636 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007637}
7638
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007639PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007640 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007641\n\
7642Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08007643such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007644arguments start and end are interpreted as in slice notation.\n\
7645\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007646Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007647
7648static PyObject *
7649unicode_find(PyUnicodeObject *self, PyObject *args)
7650{
Jesus Ceaac451502011-04-20 17:09:23 +02007651 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00007652 Py_ssize_t start;
7653 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007654 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007655
Jesus Ceaac451502011-04-20 17:09:23 +02007656 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
7657 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007658 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007659
Thomas Wouters477c8d52006-05-27 19:21:47 +00007660 result = stringlib_find_slice(
7661 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
7662 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
7663 start, end
7664 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007665
7666 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007667
Christian Heimes217cfd12007-12-02 14:31:20 +00007668 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007669}
7670
7671static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00007672unicode_getitem(PyUnicodeObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007673{
7674 if (index < 0 || index >= self->length) {
7675 PyErr_SetString(PyExc_IndexError, "string index out of range");
7676 return NULL;
7677 }
7678
7679 return (PyObject*) PyUnicode_FromUnicode(&self->str[index], 1);
7680}
7681
Guido van Rossumc2504932007-09-18 19:42:40 +00007682/* Believe it or not, this produces the same value for ASCII strings
7683 as string_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00007684static Py_hash_t
Neil Schemenauerf8c37d12007-09-07 20:49:04 +00007685unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007686{
Guido van Rossumc2504932007-09-18 19:42:40 +00007687 Py_ssize_t len;
7688 Py_UNICODE *p;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -08007689 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +00007690
Benjamin Petersonf6622c82012-04-09 14:53:07 -04007691#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -05007692 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -04007693#endif
Guido van Rossumc2504932007-09-18 19:42:40 +00007694 if (self->hash != -1)
7695 return self->hash;
Christian Heimes90aa7642007-12-19 02:45:37 +00007696 len = Py_SIZE(self);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01007697 /*
7698 We make the hash of the empty string be 0, rather than using
7699 (prefix ^ suffix), since this slightly obfuscates the hash secret
7700 */
7701 if (len == 0) {
7702 self->hash = 0;
7703 return 0;
7704 }
Guido van Rossumc2504932007-09-18 19:42:40 +00007705 p = self->str;
Georg Brandl2daf6ae2012-02-20 19:54:16 +01007706 x = _Py_HashSecret.prefix;
7707 x ^= *p << 7;
Guido van Rossumc2504932007-09-18 19:42:40 +00007708 while (--len >= 0)
Gregory P. Smith63e6c322012-01-14 15:31:34 -08007709 x = (_PyHASH_MULTIPLIER*x) ^ *p++;
Christian Heimes90aa7642007-12-19 02:45:37 +00007710 x ^= Py_SIZE(self);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01007711 x ^= _Py_HashSecret.suffix;
Guido van Rossumc2504932007-09-18 19:42:40 +00007712 if (x == -1)
7713 x = -2;
7714 self->hash = x;
7715 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007716}
7717
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007718PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007719 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007720\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007721Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007722
7723static PyObject *
7724unicode_index(PyUnicodeObject *self, PyObject *args)
7725{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007726 Py_ssize_t result;
Jesus Ceaac451502011-04-20 17:09:23 +02007727 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00007728 Py_ssize_t start;
7729 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007730
Jesus Ceaac451502011-04-20 17:09:23 +02007731 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
7732 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007733 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007734
Thomas Wouters477c8d52006-05-27 19:21:47 +00007735 result = stringlib_find_slice(
7736 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
7737 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
7738 start, end
7739 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007740
7741 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007742
Guido van Rossumd57fd912000-03-10 22:53:23 +00007743 if (result < 0) {
7744 PyErr_SetString(PyExc_ValueError, "substring not found");
7745 return NULL;
7746 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00007747
Christian Heimes217cfd12007-12-02 14:31:20 +00007748 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007749}
7750
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007751PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007752 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007753\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007754Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007755at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007756
7757static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007758unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007759{
7760 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7761 register const Py_UNICODE *e;
7762 int cased;
7763
Guido van Rossumd57fd912000-03-10 22:53:23 +00007764 /* Shortcut for single character strings */
7765 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007766 return PyBool_FromLong(Py_UNICODE_ISLOWER(*p));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007767
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007768 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007769 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007770 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007771
Guido van Rossumd57fd912000-03-10 22:53:23 +00007772 e = p + PyUnicode_GET_SIZE(self);
7773 cased = 0;
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007774 while (p < e) {
7775 const Py_UCS4 ch = _Py_UNICODE_NEXT(p, e);
Tim Petersced69f82003-09-16 20:30:58 +00007776
Benjamin Peterson29060642009-01-31 22:14:21 +00007777 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
7778 return PyBool_FromLong(0);
7779 else if (!cased && Py_UNICODE_ISLOWER(ch))
7780 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007781 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007782 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007783}
7784
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007785PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007786 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007787\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007788Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007789at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007790
7791static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007792unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007793{
7794 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7795 register const Py_UNICODE *e;
7796 int cased;
7797
Guido van Rossumd57fd912000-03-10 22:53:23 +00007798 /* Shortcut for single character strings */
7799 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007800 return PyBool_FromLong(Py_UNICODE_ISUPPER(*p) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007801
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007802 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007803 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007804 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007805
Guido van Rossumd57fd912000-03-10 22:53:23 +00007806 e = p + PyUnicode_GET_SIZE(self);
7807 cased = 0;
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007808 while (p < e) {
7809 const Py_UCS4 ch = _Py_UNICODE_NEXT(p, e);
Tim Petersced69f82003-09-16 20:30:58 +00007810
Benjamin Peterson29060642009-01-31 22:14:21 +00007811 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
7812 return PyBool_FromLong(0);
7813 else if (!cased && Py_UNICODE_ISUPPER(ch))
7814 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007815 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007816 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007817}
7818
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007819PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007820 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007821\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007822Return True if S is a titlecased string and there is at least one\n\
7823character in S, i.e. upper- and titlecase characters may only\n\
7824follow uncased characters and lowercase characters only cased ones.\n\
7825Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007826
7827static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007828unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007829{
7830 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7831 register const Py_UNICODE *e;
7832 int cased, previous_is_cased;
7833
Guido van Rossumd57fd912000-03-10 22:53:23 +00007834 /* Shortcut for single character strings */
7835 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007836 return PyBool_FromLong((Py_UNICODE_ISTITLE(*p) != 0) ||
7837 (Py_UNICODE_ISUPPER(*p) != 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007838
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007839 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007840 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007841 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007842
Guido van Rossumd57fd912000-03-10 22:53:23 +00007843 e = p + PyUnicode_GET_SIZE(self);
7844 cased = 0;
7845 previous_is_cased = 0;
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007846 while (p < e) {
7847 const Py_UCS4 ch = _Py_UNICODE_NEXT(p, e);
Tim Petersced69f82003-09-16 20:30:58 +00007848
Benjamin Peterson29060642009-01-31 22:14:21 +00007849 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
7850 if (previous_is_cased)
7851 return PyBool_FromLong(0);
7852 previous_is_cased = 1;
7853 cased = 1;
7854 }
7855 else if (Py_UNICODE_ISLOWER(ch)) {
7856 if (!previous_is_cased)
7857 return PyBool_FromLong(0);
7858 previous_is_cased = 1;
7859 cased = 1;
7860 }
7861 else
7862 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007863 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007864 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007865}
7866
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007867PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007868 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007869\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007870Return True if all characters in S are whitespace\n\
7871and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007872
7873static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007874unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007875{
7876 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7877 register const Py_UNICODE *e;
7878
Guido van Rossumd57fd912000-03-10 22:53:23 +00007879 /* Shortcut for single character strings */
7880 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007881 Py_UNICODE_ISSPACE(*p))
7882 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007883
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007884 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007885 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007886 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007887
Guido van Rossumd57fd912000-03-10 22:53:23 +00007888 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007889 while (p < e) {
7890 const Py_UCS4 ch = _Py_UNICODE_NEXT(p, e);
7891 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +00007892 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007893 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007894 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007895}
7896
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007897PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007898 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007899\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007900Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007901and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007902
7903static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007904unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007905{
7906 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7907 register const Py_UNICODE *e;
7908
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007909 /* Shortcut for single character strings */
7910 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007911 Py_UNICODE_ISALPHA(*p))
7912 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007913
7914 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007915 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007916 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007917
7918 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007919 while (p < e) {
7920 if (!Py_UNICODE_ISALPHA(_Py_UNICODE_NEXT(p, e)))
Benjamin Peterson29060642009-01-31 22:14:21 +00007921 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007922 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007923 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007924}
7925
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007926PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007927 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007928\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007929Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007930and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007931
7932static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007933unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007934{
7935 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7936 register const Py_UNICODE *e;
7937
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007938 /* Shortcut for single character strings */
7939 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007940 Py_UNICODE_ISALNUM(*p))
7941 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007942
7943 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007944 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007945 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007946
7947 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007948 while (p < e) {
7949 const Py_UCS4 ch = _Py_UNICODE_NEXT(p, e);
7950 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +00007951 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007952 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007953 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007954}
7955
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007956PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007957 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007958\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007959Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007960False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007961
7962static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007963unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007964{
7965 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7966 register const Py_UNICODE *e;
7967
Guido van Rossumd57fd912000-03-10 22:53:23 +00007968 /* Shortcut for single character strings */
7969 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007970 Py_UNICODE_ISDECIMAL(*p))
7971 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007972
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007973 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007974 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007975 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007976
Guido van Rossumd57fd912000-03-10 22:53:23 +00007977 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03007978 while (p < e) {
7979 if (!Py_UNICODE_ISDECIMAL(_Py_UNICODE_NEXT(p, e)))
Benjamin Peterson29060642009-01-31 22:14:21 +00007980 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007981 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007982 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007983}
7984
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007985PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007986 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007987\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007988Return True if all characters in S are digits\n\
7989and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007990
7991static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007992unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007993{
7994 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7995 register const Py_UNICODE *e;
7996
Guido van Rossumd57fd912000-03-10 22:53:23 +00007997 /* Shortcut for single character strings */
7998 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007999 Py_UNICODE_ISDIGIT(*p))
8000 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008001
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00008002 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00008003 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008004 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00008005
Guido van Rossumd57fd912000-03-10 22:53:23 +00008006 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03008007 while (p < e) {
8008 if (!Py_UNICODE_ISDIGIT(_Py_UNICODE_NEXT(p, e)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008009 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008010 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00008011 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008012}
8013
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008014PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008015 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008016\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00008017Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008018False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008019
8020static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008021unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008022{
8023 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
8024 register const Py_UNICODE *e;
8025
Guido van Rossumd57fd912000-03-10 22:53:23 +00008026 /* Shortcut for single character strings */
8027 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00008028 Py_UNICODE_ISNUMERIC(*p))
8029 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008030
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00008031 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00008032 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008033 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00008034
Guido van Rossumd57fd912000-03-10 22:53:23 +00008035 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03008036 while (p < e) {
8037 if (!Py_UNICODE_ISNUMERIC(_Py_UNICODE_NEXT(p, e)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008038 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008039 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00008040 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008041}
8042
Martin v. Löwis47383402007-08-15 07:32:56 +00008043int
8044PyUnicode_IsIdentifier(PyObject *self)
8045{
Benjamin Petersonf413b802011-08-12 22:17:18 -05008046 const Py_UNICODE *p = PyUnicode_AS_UNICODE((PyUnicodeObject*)self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03008047 const Py_UNICODE *e;
8048 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +00008049
8050 /* Special case for empty strings */
Ezio Melotti93e7afc2011-08-22 14:08:38 +03008051 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008052 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +00008053
8054 /* PEP 3131 says that the first character must be in
8055 XID_Start and subsequent characters in XID_Continue,
8056 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +00008057 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +00008058 letters, digits, underscore). However, given the current
8059 definition of XID_Start and XID_Continue, it is sufficient
8060 to check just for these, except that _ must be allowed
8061 as starting an identifier. */
Ezio Melotti93e7afc2011-08-22 14:08:38 +03008062 e = p + PyUnicode_GET_SIZE(self);
8063 first = _Py_UNICODE_NEXT(p, e);
Benjamin Petersonf413b802011-08-12 22:17:18 -05008064 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +00008065 return 0;
8066
Ezio Melotti93e7afc2011-08-22 14:08:38 +03008067 while (p < e)
8068 if (!_PyUnicode_IsXidContinue(_Py_UNICODE_NEXT(p, e)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008069 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +00008070 return 1;
8071}
8072
8073PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008074 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +00008075\n\
8076Return True if S is a valid identifier according\n\
8077to the language definition.");
8078
8079static PyObject*
8080unicode_isidentifier(PyObject *self)
8081{
8082 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
8083}
8084
Georg Brandl559e5d72008-06-11 18:37:52 +00008085PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008086 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +00008087\n\
8088Return True if all characters in S are considered\n\
8089printable in repr() or S is empty, False otherwise.");
8090
8091static PyObject*
8092unicode_isprintable(PyObject *self)
8093{
8094 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
8095 register const Py_UNICODE *e;
8096
8097 /* Shortcut for single character strings */
8098 if (PyUnicode_GET_SIZE(self) == 1 && Py_UNICODE_ISPRINTABLE(*p)) {
8099 Py_RETURN_TRUE;
8100 }
8101
8102 e = p + PyUnicode_GET_SIZE(self);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03008103 while (p < e) {
8104 if (!Py_UNICODE_ISPRINTABLE(_Py_UNICODE_NEXT(p, e))) {
Georg Brandl559e5d72008-06-11 18:37:52 +00008105 Py_RETURN_FALSE;
8106 }
8107 }
8108 Py_RETURN_TRUE;
8109}
8110
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008111PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +00008112 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008113\n\
8114Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +00008115iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008116
8117static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008118unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008119{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008120 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008121}
8122
Martin v. Löwis18e16552006-02-15 17:27:45 +00008123static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +00008124unicode_length(PyUnicodeObject *self)
8125{
8126 return self->length;
8127}
8128
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008129PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008130 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008131\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008132Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008133done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008134
8135static PyObject *
8136unicode_ljust(PyUnicodeObject *self, PyObject *args)
8137{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008138 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008139 Py_UNICODE fillchar = ' ';
8140
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008141 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008142 return NULL;
8143
Tim Peters7a29bd52001-09-12 03:03:31 +00008144 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008145 Py_INCREF(self);
8146 return (PyObject*) self;
8147 }
8148
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008149 return (PyObject*) pad(self, 0, width - self->length, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008150}
8151
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008152PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008153 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008154\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008155Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008156
8157static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008158unicode_lower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008159{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008160 return fixup(self, fixlower);
8161}
8162
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008163#define LEFTSTRIP 0
8164#define RIGHTSTRIP 1
8165#define BOTHSTRIP 2
8166
8167/* Arrays indexed by above */
8168static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
8169
8170#define STRIPNAME(i) (stripformat[i]+3)
8171
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008172/* externally visible for str.strip(unicode) */
8173PyObject *
8174_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
8175{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008176 Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
8177 Py_ssize_t len = PyUnicode_GET_SIZE(self);
8178 Py_UNICODE *sep = PyUnicode_AS_UNICODE(sepobj);
8179 Py_ssize_t seplen = PyUnicode_GET_SIZE(sepobj);
8180 Py_ssize_t i, j;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008181
Benjamin Peterson29060642009-01-31 22:14:21 +00008182 BLOOM_MASK sepmask = make_bloom_mask(sep, seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008183
Benjamin Peterson14339b62009-01-31 16:36:08 +00008184 i = 0;
8185 if (striptype != RIGHTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008186 while (i < len && BLOOM_MEMBER(sepmask, s[i], sep, seplen)) {
8187 i++;
8188 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008189 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008190
Benjamin Peterson14339b62009-01-31 16:36:08 +00008191 j = len;
8192 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008193 do {
8194 j--;
8195 } while (j >= i && BLOOM_MEMBER(sepmask, s[j], sep, seplen));
8196 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008197 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008198
Benjamin Peterson14339b62009-01-31 16:36:08 +00008199 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008200 Py_INCREF(self);
8201 return (PyObject*)self;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008202 }
8203 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008204 return PyUnicode_FromUnicode(s+i, j-i);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008205}
8206
Guido van Rossumd57fd912000-03-10 22:53:23 +00008207
8208static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008209do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008210{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008211 Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
8212 Py_ssize_t len = PyUnicode_GET_SIZE(self), i, j;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008213
Benjamin Peterson14339b62009-01-31 16:36:08 +00008214 i = 0;
8215 if (striptype != RIGHTSTRIP) {
8216 while (i < len && Py_UNICODE_ISSPACE(s[i])) {
8217 i++;
8218 }
8219 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008220
Benjamin Peterson14339b62009-01-31 16:36:08 +00008221 j = len;
8222 if (striptype != LEFTSTRIP) {
8223 do {
8224 j--;
8225 } while (j >= i && Py_UNICODE_ISSPACE(s[j]));
8226 j++;
8227 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008228
Benjamin Peterson14339b62009-01-31 16:36:08 +00008229 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
8230 Py_INCREF(self);
8231 return (PyObject*)self;
8232 }
8233 else
8234 return PyUnicode_FromUnicode(s+i, j-i);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008235}
8236
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008237
8238static PyObject *
8239do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
8240{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008241 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008242
Benjamin Peterson14339b62009-01-31 16:36:08 +00008243 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
8244 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008245
Benjamin Peterson14339b62009-01-31 16:36:08 +00008246 if (sep != NULL && sep != Py_None) {
8247 if (PyUnicode_Check(sep))
8248 return _PyUnicode_XStrip(self, striptype, sep);
8249 else {
8250 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00008251 "%s arg must be None or str",
8252 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +00008253 return NULL;
8254 }
8255 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008256
Benjamin Peterson14339b62009-01-31 16:36:08 +00008257 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008258}
8259
8260
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008261PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008262 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008263\n\
8264Return a copy of the string S with leading and trailing\n\
8265whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008266If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008267
8268static PyObject *
8269unicode_strip(PyUnicodeObject *self, PyObject *args)
8270{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008271 if (PyTuple_GET_SIZE(args) == 0)
8272 return do_strip(self, BOTHSTRIP); /* Common case */
8273 else
8274 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008275}
8276
8277
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008278PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008279 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008280\n\
8281Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008282If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008283
8284static PyObject *
8285unicode_lstrip(PyUnicodeObject *self, PyObject *args)
8286{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008287 if (PyTuple_GET_SIZE(args) == 0)
8288 return do_strip(self, LEFTSTRIP); /* Common case */
8289 else
8290 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008291}
8292
8293
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008294PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008295 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008296\n\
8297Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008298If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008299
8300static PyObject *
8301unicode_rstrip(PyUnicodeObject *self, PyObject *args)
8302{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008303 if (PyTuple_GET_SIZE(args) == 0)
8304 return do_strip(self, RIGHTSTRIP); /* Common case */
8305 else
8306 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008307}
8308
8309
Guido van Rossumd57fd912000-03-10 22:53:23 +00008310static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +00008311unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008312{
8313 PyUnicodeObject *u;
8314 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008315 Py_ssize_t nchars;
Tim Peters8f422462000-09-09 06:13:41 +00008316 size_t nbytes;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008317
Georg Brandl222de0f2009-04-12 12:01:50 +00008318 if (len < 1) {
8319 Py_INCREF(unicode_empty);
8320 return (PyObject *)unicode_empty;
8321 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008322
Tim Peters7a29bd52001-09-12 03:03:31 +00008323 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008324 /* no repeat, return original string */
8325 Py_INCREF(str);
8326 return (PyObject*) str;
8327 }
Tim Peters8f422462000-09-09 06:13:41 +00008328
8329 /* ensure # of chars needed doesn't overflow int and # of bytes
8330 * needed doesn't overflow size_t
8331 */
8332 nchars = len * str->length;
Georg Brandl222de0f2009-04-12 12:01:50 +00008333 if (nchars / len != str->length) {
Tim Peters8f422462000-09-09 06:13:41 +00008334 PyErr_SetString(PyExc_OverflowError,
8335 "repeated string is too long");
8336 return NULL;
8337 }
8338 nbytes = (nchars + 1) * sizeof(Py_UNICODE);
8339 if (nbytes / sizeof(Py_UNICODE) != (size_t)(nchars + 1)) {
8340 PyErr_SetString(PyExc_OverflowError,
8341 "repeated string is too long");
8342 return NULL;
8343 }
8344 u = _PyUnicode_New(nchars);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008345 if (!u)
8346 return NULL;
8347
8348 p = u->str;
8349
Georg Brandl222de0f2009-04-12 12:01:50 +00008350 if (str->length == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00008351 Py_UNICODE_FILL(p, str->str[0], len);
8352 } else {
Georg Brandl222de0f2009-04-12 12:01:50 +00008353 Py_ssize_t done = str->length; /* number of characters copied this far */
8354 Py_UNICODE_COPY(p, str->str, str->length);
Benjamin Peterson29060642009-01-31 22:14:21 +00008355 while (done < nchars) {
Christian Heimescc47b052008-03-25 14:56:36 +00008356 Py_ssize_t n = (done <= nchars-done) ? done : nchars-done;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008357 Py_UNICODE_COPY(p+done, p, n);
8358 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00008359 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008360 }
8361
8362 return (PyObject*) u;
8363}
8364
8365PyObject *PyUnicode_Replace(PyObject *obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00008366 PyObject *subobj,
8367 PyObject *replobj,
8368 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008369{
8370 PyObject *self;
8371 PyObject *str1;
8372 PyObject *str2;
8373 PyObject *result;
8374
8375 self = PyUnicode_FromObject(obj);
8376 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008377 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008378 str1 = PyUnicode_FromObject(subobj);
8379 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008380 Py_DECREF(self);
8381 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008382 }
8383 str2 = PyUnicode_FromObject(replobj);
8384 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008385 Py_DECREF(self);
8386 Py_DECREF(str1);
8387 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008388 }
Tim Petersced69f82003-09-16 20:30:58 +00008389 result = replace((PyUnicodeObject *)self,
Benjamin Peterson29060642009-01-31 22:14:21 +00008390 (PyUnicodeObject *)str1,
8391 (PyUnicodeObject *)str2,
8392 maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008393 Py_DECREF(self);
8394 Py_DECREF(str1);
8395 Py_DECREF(str2);
8396 return result;
8397}
8398
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008399PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +00008400 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008401\n\
8402Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +00008403old replaced by new. If the optional argument count is\n\
8404given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008405
8406static PyObject*
8407unicode_replace(PyUnicodeObject *self, PyObject *args)
8408{
8409 PyUnicodeObject *str1;
8410 PyUnicodeObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008411 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008412 PyObject *result;
8413
Martin v. Löwis18e16552006-02-15 17:27:45 +00008414 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008415 return NULL;
8416 str1 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str1);
8417 if (str1 == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008418 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008419 str2 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str2);
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +00008420 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008421 Py_DECREF(str1);
8422 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +00008423 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008424
8425 result = replace(self, str1, str2, maxcount);
8426
8427 Py_DECREF(str1);
8428 Py_DECREF(str2);
8429 return result;
8430}
8431
8432static
8433PyObject *unicode_repr(PyObject *unicode)
8434{
Walter Dörwald79e913e2007-05-12 11:08:06 +00008435 PyObject *repr;
Walter Dörwald1ab83302007-05-18 17:15:44 +00008436 Py_UNICODE *p;
Walter Dörwald79e913e2007-05-12 11:08:06 +00008437 Py_UNICODE *s = PyUnicode_AS_UNICODE(unicode);
8438 Py_ssize_t size = PyUnicode_GET_SIZE(unicode);
8439
8440 /* XXX(nnorwitz): rather than over-allocating, it would be
8441 better to choose a different scheme. Perhaps scan the
8442 first N-chars of the string and allocate based on that size.
8443 */
8444 /* Initial allocation is based on the longest-possible unichr
8445 escape.
8446
8447 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
8448 unichr, so in this case it's the longest unichr escape. In
8449 narrow (UTF-16) builds this is five chars per source unichr
8450 since there are two unichrs in the surrogate pair, so in narrow
8451 (UTF-16) builds it's not the longest unichr escape.
8452
8453 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
8454 so in the narrow (UTF-16) build case it's the longest unichr
8455 escape.
8456 */
8457
Walter Dörwald1ab83302007-05-18 17:15:44 +00008458 repr = PyUnicode_FromUnicode(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00008459 2 /* quotes */
Walter Dörwald79e913e2007-05-12 11:08:06 +00008460#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00008461 + 10*size
Walter Dörwald79e913e2007-05-12 11:08:06 +00008462#else
Benjamin Peterson29060642009-01-31 22:14:21 +00008463 + 6*size
Walter Dörwald79e913e2007-05-12 11:08:06 +00008464#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00008465 + 1);
Walter Dörwald79e913e2007-05-12 11:08:06 +00008466 if (repr == NULL)
8467 return NULL;
8468
Walter Dörwald1ab83302007-05-18 17:15:44 +00008469 p = PyUnicode_AS_UNICODE(repr);
Walter Dörwald79e913e2007-05-12 11:08:06 +00008470
8471 /* Add quote */
8472 *p++ = (findchar(s, size, '\'') &&
8473 !findchar(s, size, '"')) ? '"' : '\'';
8474 while (size-- > 0) {
8475 Py_UNICODE ch = *s++;
8476
8477 /* Escape quotes and backslashes */
Walter Dörwald1ab83302007-05-18 17:15:44 +00008478 if ((ch == PyUnicode_AS_UNICODE(repr)[0]) || (ch == '\\')) {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008479 *p++ = '\\';
Walter Dörwald1ab83302007-05-18 17:15:44 +00008480 *p++ = ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00008481 continue;
8482 }
8483
Benjamin Peterson29060642009-01-31 22:14:21 +00008484 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +00008485 if (ch == '\t') {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008486 *p++ = '\\';
8487 *p++ = 't';
8488 }
8489 else if (ch == '\n') {
8490 *p++ = '\\';
8491 *p++ = 'n';
8492 }
8493 else if (ch == '\r') {
8494 *p++ = '\\';
8495 *p++ = 'r';
8496 }
8497
8498 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +00008499 else if (ch < ' ' || ch == 0x7F) {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008500 *p++ = '\\';
8501 *p++ = 'x';
8502 *p++ = hexdigits[(ch >> 4) & 0x000F];
8503 *p++ = hexdigits[ch & 0x000F];
8504 }
8505
Georg Brandl559e5d72008-06-11 18:37:52 +00008506 /* Copy ASCII characters as-is */
8507 else if (ch < 0x7F) {
8508 *p++ = ch;
8509 }
8510
Benjamin Peterson29060642009-01-31 22:14:21 +00008511 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +00008512 else {
8513 Py_UCS4 ucs = ch;
8514
8515#ifndef Py_UNICODE_WIDE
8516 Py_UNICODE ch2 = 0;
8517 /* Get code point from surrogate pair */
8518 if (size > 0) {
8519 ch2 = *s;
8520 if (ch >= 0xD800 && ch < 0xDC00 && ch2 >= 0xDC00
Benjamin Peterson29060642009-01-31 22:14:21 +00008521 && ch2 <= 0xDFFF) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008522 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF))
Benjamin Peterson29060642009-01-31 22:14:21 +00008523 + 0x00010000;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008524 s++;
Georg Brandl559e5d72008-06-11 18:37:52 +00008525 size--;
8526 }
8527 }
8528#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00008529 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +00008530 (categories Z* and C* except ASCII space)
8531 */
8532 if (!Py_UNICODE_ISPRINTABLE(ucs)) {
8533 /* Map 8-bit characters to '\xhh' */
8534 if (ucs <= 0xff) {
8535 *p++ = '\\';
8536 *p++ = 'x';
8537 *p++ = hexdigits[(ch >> 4) & 0x000F];
8538 *p++ = hexdigits[ch & 0x000F];
8539 }
8540 /* Map 21-bit characters to '\U00xxxxxx' */
8541 else if (ucs >= 0x10000) {
8542 *p++ = '\\';
8543 *p++ = 'U';
8544 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
8545 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
8546 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
8547 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
8548 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
8549 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
8550 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
8551 *p++ = hexdigits[ucs & 0x0000000F];
8552 }
8553 /* Map 16-bit characters to '\uxxxx' */
8554 else {
8555 *p++ = '\\';
8556 *p++ = 'u';
8557 *p++ = hexdigits[(ucs >> 12) & 0x000F];
8558 *p++ = hexdigits[(ucs >> 8) & 0x000F];
8559 *p++ = hexdigits[(ucs >> 4) & 0x000F];
8560 *p++ = hexdigits[ucs & 0x000F];
8561 }
8562 }
8563 /* Copy characters as-is */
8564 else {
8565 *p++ = ch;
8566#ifndef Py_UNICODE_WIDE
8567 if (ucs >= 0x10000)
8568 *p++ = ch2;
8569#endif
8570 }
8571 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00008572 }
8573 /* Add quote */
Walter Dörwald1ab83302007-05-18 17:15:44 +00008574 *p++ = PyUnicode_AS_UNICODE(repr)[0];
Walter Dörwald79e913e2007-05-12 11:08:06 +00008575
8576 *p = '\0';
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00008577 PyUnicode_Resize(&repr, p - PyUnicode_AS_UNICODE(repr));
Walter Dörwald79e913e2007-05-12 11:08:06 +00008578 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008579}
8580
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008581PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008582 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008583\n\
8584Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08008585such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008586arguments start and end are interpreted as in slice notation.\n\
8587\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008588Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008589
8590static PyObject *
8591unicode_rfind(PyUnicodeObject *self, PyObject *args)
8592{
Jesus Ceaac451502011-04-20 17:09:23 +02008593 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00008594 Py_ssize_t start;
8595 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008596 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008597
Jesus Ceaac451502011-04-20 17:09:23 +02008598 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
8599 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008600 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008601
Thomas Wouters477c8d52006-05-27 19:21:47 +00008602 result = stringlib_rfind_slice(
8603 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
8604 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
8605 start, end
8606 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008607
8608 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008609
Christian Heimes217cfd12007-12-02 14:31:20 +00008610 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008611}
8612
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008613PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008614 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008615\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008616Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008617
8618static PyObject *
8619unicode_rindex(PyUnicodeObject *self, PyObject *args)
8620{
Jesus Ceaac451502011-04-20 17:09:23 +02008621 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00008622 Py_ssize_t start;
8623 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008624 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008625
Jesus Ceaac451502011-04-20 17:09:23 +02008626 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
8627 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008628 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008629
Thomas Wouters477c8d52006-05-27 19:21:47 +00008630 result = stringlib_rfind_slice(
8631 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
8632 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
8633 start, end
8634 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008635
8636 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008637
Guido van Rossumd57fd912000-03-10 22:53:23 +00008638 if (result < 0) {
8639 PyErr_SetString(PyExc_ValueError, "substring not found");
8640 return NULL;
8641 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008642 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008643}
8644
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008645PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008646 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008647\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008648Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008649done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008650
8651static PyObject *
8652unicode_rjust(PyUnicodeObject *self, PyObject *args)
8653{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008654 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008655 Py_UNICODE fillchar = ' ';
8656
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008657 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008658 return NULL;
8659
Tim Peters7a29bd52001-09-12 03:03:31 +00008660 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008661 Py_INCREF(self);
8662 return (PyObject*) self;
8663 }
8664
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008665 return (PyObject*) pad(self, width - self->length, 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008666}
8667
Guido van Rossumd57fd912000-03-10 22:53:23 +00008668PyObject *PyUnicode_Split(PyObject *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00008669 PyObject *sep,
8670 Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008671{
8672 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008673
Guido van Rossumd57fd912000-03-10 22:53:23 +00008674 s = PyUnicode_FromObject(s);
8675 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008676 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00008677 if (sep != NULL) {
8678 sep = PyUnicode_FromObject(sep);
8679 if (sep == NULL) {
8680 Py_DECREF(s);
8681 return NULL;
8682 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008683 }
8684
8685 result = split((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
8686
8687 Py_DECREF(s);
8688 Py_XDECREF(sep);
8689 return result;
8690}
8691
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008692PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008693 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008694\n\
8695Return a list of the words in S, using sep as the\n\
8696delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00008697splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00008698whitespace string is a separator and empty strings are\n\
8699removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008700
8701static PyObject*
8702unicode_split(PyUnicodeObject *self, PyObject *args)
8703{
8704 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008705 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008706
Martin v. Löwis18e16552006-02-15 17:27:45 +00008707 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008708 return NULL;
8709
8710 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008711 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008712 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00008713 return split(self, (PyUnicodeObject *)substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008714 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008715 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008716}
8717
Thomas Wouters477c8d52006-05-27 19:21:47 +00008718PyObject *
8719PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
8720{
8721 PyObject* str_obj;
8722 PyObject* sep_obj;
8723 PyObject* out;
8724
8725 str_obj = PyUnicode_FromObject(str_in);
8726 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008727 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008728 sep_obj = PyUnicode_FromObject(sep_in);
8729 if (!sep_obj) {
8730 Py_DECREF(str_obj);
8731 return NULL;
8732 }
8733
8734 out = stringlib_partition(
8735 str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
8736 sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
8737 );
8738
8739 Py_DECREF(sep_obj);
8740 Py_DECREF(str_obj);
8741
8742 return out;
8743}
8744
8745
8746PyObject *
8747PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
8748{
8749 PyObject* str_obj;
8750 PyObject* sep_obj;
8751 PyObject* out;
8752
8753 str_obj = PyUnicode_FromObject(str_in);
8754 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008755 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008756 sep_obj = PyUnicode_FromObject(sep_in);
8757 if (!sep_obj) {
8758 Py_DECREF(str_obj);
8759 return NULL;
8760 }
8761
8762 out = stringlib_rpartition(
8763 str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
8764 sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
8765 );
8766
8767 Py_DECREF(sep_obj);
8768 Py_DECREF(str_obj);
8769
8770 return out;
8771}
8772
8773PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008774 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008775\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00008776Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008777the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008778found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00008779
8780static PyObject*
8781unicode_partition(PyUnicodeObject *self, PyObject *separator)
8782{
8783 return PyUnicode_Partition((PyObject *)self, separator);
8784}
8785
8786PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +00008787 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008788\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00008789Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008790the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008791separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00008792
8793static PyObject*
8794unicode_rpartition(PyUnicodeObject *self, PyObject *separator)
8795{
8796 return PyUnicode_RPartition((PyObject *)self, separator);
8797}
8798
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008799PyObject *PyUnicode_RSplit(PyObject *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00008800 PyObject *sep,
8801 Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008802{
8803 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008804
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008805 s = PyUnicode_FromObject(s);
8806 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008807 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00008808 if (sep != NULL) {
8809 sep = PyUnicode_FromObject(sep);
8810 if (sep == NULL) {
8811 Py_DECREF(s);
8812 return NULL;
8813 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008814 }
8815
8816 result = rsplit((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
8817
8818 Py_DECREF(s);
8819 Py_XDECREF(sep);
8820 return result;
8821}
8822
8823PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008824 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008825\n\
8826Return a list of the words in S, using sep as the\n\
8827delimiter string, starting at the end of the string and\n\
8828working to the front. If maxsplit is given, at most maxsplit\n\
8829splits are done. If sep is not specified, any whitespace string\n\
8830is a separator.");
8831
8832static PyObject*
8833unicode_rsplit(PyUnicodeObject *self, PyObject *args)
8834{
8835 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008836 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008837
Martin v. Löwis18e16552006-02-15 17:27:45 +00008838 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008839 return NULL;
8840
8841 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008842 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008843 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00008844 return rsplit(self, (PyUnicodeObject *)substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008845 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008846 return PyUnicode_RSplit((PyObject *)self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008847}
8848
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008849PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008850 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008851\n\
8852Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +00008853Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008854is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008855
8856static PyObject*
8857unicode_splitlines(PyUnicodeObject *self, PyObject *args)
8858{
Guido van Rossum86662912000-04-11 15:38:46 +00008859 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008860
Guido van Rossum86662912000-04-11 15:38:46 +00008861 if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008862 return NULL;
8863
Guido van Rossum86662912000-04-11 15:38:46 +00008864 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008865}
8866
8867static
Guido van Rossumf15a29f2007-05-04 00:41:39 +00008868PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008869{
Walter Dörwald346737f2007-05-31 10:44:43 +00008870 if (PyUnicode_CheckExact(self)) {
8871 Py_INCREF(self);
8872 return self;
8873 } else
8874 /* Subtype -- return genuine unicode string with the same value. */
8875 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(self),
8876 PyUnicode_GET_SIZE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +00008877}
8878
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008879PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008880 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008881\n\
8882Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008883and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008884
8885static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008886unicode_swapcase(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008887{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008888 return fixup(self, fixswapcase);
8889}
8890
Georg Brandlceee0772007-11-27 23:48:05 +00008891PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008892 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +00008893\n\
8894Return a translation table usable for str.translate().\n\
8895If there is only one argument, it must be a dictionary mapping Unicode\n\
8896ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008897Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +00008898If there are two arguments, they must be strings of equal length, and\n\
8899in the resulting dictionary, each character in x will be mapped to the\n\
8900character at the same position in y. If there is a third argument, it\n\
8901must be a string, whose characters will be mapped to None in the result.");
8902
8903static PyObject*
8904unicode_maketrans(PyUnicodeObject *null, PyObject *args)
8905{
8906 PyObject *x, *y = NULL, *z = NULL;
8907 PyObject *new = NULL, *key, *value;
8908 Py_ssize_t i = 0;
8909 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008910
Georg Brandlceee0772007-11-27 23:48:05 +00008911 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
8912 return NULL;
8913 new = PyDict_New();
8914 if (!new)
8915 return NULL;
8916 if (y != NULL) {
8917 /* x must be a string too, of equal length */
8918 Py_ssize_t ylen = PyUnicode_GET_SIZE(y);
8919 if (!PyUnicode_Check(x)) {
8920 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
8921 "be a string if there is a second argument");
8922 goto err;
8923 }
8924 if (PyUnicode_GET_SIZE(x) != ylen) {
8925 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
8926 "arguments must have equal length");
8927 goto err;
8928 }
8929 /* create entries for translating chars in x to those in y */
8930 for (i = 0; i < PyUnicode_GET_SIZE(x); i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +00008931 key = PyLong_FromLong(PyUnicode_AS_UNICODE(x)[i]);
Benjamin Peterson53aa1d72011-12-20 13:29:45 -06008932 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +00008933 goto err;
Benjamin Peterson53aa1d72011-12-20 13:29:45 -06008934 value = PyLong_FromLong(PyUnicode_AS_UNICODE(y)[i]);
8935 if (!value) {
8936 Py_DECREF(key);
8937 goto err;
8938 }
Georg Brandlceee0772007-11-27 23:48:05 +00008939 res = PyDict_SetItem(new, key, value);
8940 Py_DECREF(key);
8941 Py_DECREF(value);
8942 if (res < 0)
8943 goto err;
8944 }
8945 /* create entries for deleting chars in z */
8946 if (z != NULL) {
8947 for (i = 0; i < PyUnicode_GET_SIZE(z); i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +00008948 key = PyLong_FromLong(PyUnicode_AS_UNICODE(z)[i]);
Georg Brandlceee0772007-11-27 23:48:05 +00008949 if (!key)
8950 goto err;
8951 res = PyDict_SetItem(new, key, Py_None);
8952 Py_DECREF(key);
8953 if (res < 0)
8954 goto err;
8955 }
8956 }
8957 } else {
8958 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +00008959 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +00008960 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
8961 "to maketrans it must be a dict");
8962 goto err;
8963 }
8964 /* copy entries into the new dict, converting string keys to int keys */
8965 while (PyDict_Next(x, &i, &key, &value)) {
8966 if (PyUnicode_Check(key)) {
8967 /* convert string keys to integer keys */
8968 PyObject *newkey;
8969 if (PyUnicode_GET_SIZE(key) != 1) {
8970 PyErr_SetString(PyExc_ValueError, "string keys in translate "
8971 "table must be of length 1");
8972 goto err;
8973 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008974 newkey = PyLong_FromLong(PyUnicode_AS_UNICODE(key)[0]);
Georg Brandlceee0772007-11-27 23:48:05 +00008975 if (!newkey)
8976 goto err;
8977 res = PyDict_SetItem(new, newkey, value);
8978 Py_DECREF(newkey);
8979 if (res < 0)
8980 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +00008981 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +00008982 /* just keep integer keys */
8983 if (PyDict_SetItem(new, key, value) < 0)
8984 goto err;
8985 } else {
8986 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
8987 "be strings or integers");
8988 goto err;
8989 }
8990 }
8991 }
8992 return new;
8993 err:
8994 Py_DECREF(new);
8995 return NULL;
8996}
8997
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008998PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008999 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009000\n\
9001Return a copy of the string S, where all characters have been mapped\n\
9002through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00009003Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +00009004Unmapped characters are left untouched. Characters mapped to None\n\
9005are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009006
9007static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009008unicode_translate(PyUnicodeObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009009{
Georg Brandlceee0772007-11-27 23:48:05 +00009010 return PyUnicode_TranslateCharmap(self->str, self->length, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009011}
9012
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009013PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009014 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009015\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009016Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009017
9018static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009019unicode_upper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009020{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009021 return fixup(self, fixupper);
9022}
9023
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009024PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009025 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009026\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +00009027Pad a numeric string S with zeros on the left, to fill a field\n\
9028of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009029
9030static PyObject *
9031unicode_zfill(PyUnicodeObject *self, PyObject *args)
9032{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009033 Py_ssize_t fill;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009034 PyUnicodeObject *u;
9035
Martin v. Löwis18e16552006-02-15 17:27:45 +00009036 Py_ssize_t width;
9037 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009038 return NULL;
9039
9040 if (self->length >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +00009041 if (PyUnicode_CheckExact(self)) {
9042 Py_INCREF(self);
9043 return (PyObject*) self;
9044 }
9045 else
9046 return PyUnicode_FromUnicode(
9047 PyUnicode_AS_UNICODE(self),
9048 PyUnicode_GET_SIZE(self)
Benjamin Peterson29060642009-01-31 22:14:21 +00009049 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00009050 }
9051
9052 fill = width - self->length;
9053
9054 u = pad(self, fill, 0, '0');
9055
Walter Dörwald068325e2002-04-15 13:36:47 +00009056 if (u == NULL)
9057 return NULL;
9058
Guido van Rossumd57fd912000-03-10 22:53:23 +00009059 if (u->str[fill] == '+' || u->str[fill] == '-') {
9060 /* move sign to beginning of string */
9061 u->str[0] = u->str[fill];
9062 u->str[fill] = '0';
9063 }
9064
9065 return (PyObject*) u;
9066}
Guido van Rossumd57fd912000-03-10 22:53:23 +00009067
9068#if 0
9069static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009070unicode_freelistsize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009071{
Christian Heimes2202f872008-02-06 14:31:34 +00009072 return PyLong_FromLong(numfree);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009073}
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009074
9075static PyObject *
9076unicode__decimal2ascii(PyObject *self)
9077{
9078 return PyUnicode_TransformDecimalToASCII(PyUnicode_AS_UNICODE(self),
9079 PyUnicode_GET_SIZE(self));
9080}
Guido van Rossumd57fd912000-03-10 22:53:23 +00009081#endif
9082
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009083PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009084 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009085\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00009086Return True if S starts with the specified prefix, False otherwise.\n\
9087With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009088With optional end, stop comparing S at that position.\n\
9089prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009090
9091static PyObject *
9092unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00009093 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009094{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009095 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009096 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009097 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009098 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009099 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009100
Jesus Ceaac451502011-04-20 17:09:23 +02009101 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +00009102 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009103 if (PyTuple_Check(subobj)) {
9104 Py_ssize_t i;
9105 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
9106 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +00009107 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009108 if (substring == NULL)
9109 return NULL;
9110 result = tailmatch(self, substring, start, end, -1);
9111 Py_DECREF(substring);
9112 if (result) {
9113 Py_RETURN_TRUE;
9114 }
9115 }
9116 /* nothing matched */
9117 Py_RETURN_FALSE;
9118 }
9119 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +03009120 if (substring == NULL) {
9121 if (PyErr_ExceptionMatches(PyExc_TypeError))
9122 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
9123 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +00009124 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03009125 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009126 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009127 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009128 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009129}
9130
9131
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009132PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009133 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009134\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00009135Return True if S ends with the specified suffix, False otherwise.\n\
9136With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009137With optional end, stop comparing S at that position.\n\
9138suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009139
9140static PyObject *
9141unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00009142 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009143{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009144 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009145 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009146 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009147 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009148 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009149
Jesus Ceaac451502011-04-20 17:09:23 +02009150 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +00009151 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009152 if (PyTuple_Check(subobj)) {
9153 Py_ssize_t i;
9154 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
9155 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +00009156 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009157 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009158 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009159 result = tailmatch(self, substring, start, end, +1);
9160 Py_DECREF(substring);
9161 if (result) {
9162 Py_RETURN_TRUE;
9163 }
9164 }
9165 Py_RETURN_FALSE;
9166 }
9167 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +03009168 if (substring == NULL) {
9169 if (PyErr_ExceptionMatches(PyExc_TypeError))
9170 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
9171 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +00009172 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03009173 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009174 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009175 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009176 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009177}
9178
Eric Smith8c663262007-08-25 02:26:07 +00009179#include "stringlib/string_format.h"
9180
9181PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009182 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +00009183\n\
Eric Smith51d2fd92010-11-06 19:27:37 +00009184Return a formatted version of S, using substitutions from args and kwargs.\n\
9185The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +00009186
Eric Smith27bbca62010-11-04 17:06:58 +00009187PyDoc_STRVAR(format_map__doc__,
9188 "S.format_map(mapping) -> str\n\
9189\n\
Eric Smith51d2fd92010-11-06 19:27:37 +00009190Return a formatted version of S, using substitutions from mapping.\n\
9191The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +00009192
Eric Smith4a7d76d2008-05-30 18:10:19 +00009193static PyObject *
9194unicode__format__(PyObject* self, PyObject* args)
9195{
9196 PyObject *format_spec;
9197
9198 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
9199 return NULL;
9200
9201 return _PyUnicode_FormatAdvanced(self,
9202 PyUnicode_AS_UNICODE(format_spec),
9203 PyUnicode_GET_SIZE(format_spec));
9204}
9205
Eric Smith8c663262007-08-25 02:26:07 +00009206PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009207 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +00009208\n\
Eric Smith51d2fd92010-11-06 19:27:37 +00009209Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +00009210
9211static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009212unicode__sizeof__(PyUnicodeObject *v)
9213{
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00009214 return PyLong_FromSsize_t(sizeof(PyUnicodeObject) +
9215 sizeof(Py_UNICODE) * (v->length + 1));
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009216}
9217
9218PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009219 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009220
9221static PyObject *
Guido van Rossum5d9113d2003-01-29 17:58:45 +00009222unicode_getnewargs(PyUnicodeObject *v)
9223{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009224 return Py_BuildValue("(u#)", v->str, v->length);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00009225}
9226
Guido van Rossumd57fd912000-03-10 22:53:23 +00009227static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +00009228 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009229 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
9230 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009231 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009232 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
9233 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
9234 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
9235 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
9236 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
9237 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
9238 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00009239 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009240 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
9241 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
9242 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00009243 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009244 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
9245 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
9246 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00009247 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00009248 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009249 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00009250 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009251 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
9252 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
9253 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
9254 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
9255 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
9256 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
9257 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
9258 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
9259 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
9260 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
9261 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
9262 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
9263 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
9264 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +00009265 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +00009266 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009267 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +00009268 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +00009269 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +00009270 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +00009271 {"maketrans", (PyCFunction) unicode_maketrans,
9272 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009273 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +00009274#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009275 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +00009276#endif
9277
9278#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009279 /* These methods are just used for debugging the implementation. */
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009280 {"freelistsize", (PyCFunction) unicode_freelistsize, METH_NOARGS},
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009281 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +00009282#endif
9283
Benjamin Peterson14339b62009-01-31 16:36:08 +00009284 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +00009285 {NULL, NULL}
9286};
9287
Neil Schemenauerce30bc92002-11-18 16:10:18 +00009288static PyObject *
9289unicode_mod(PyObject *v, PyObject *w)
9290{
Benjamin Peterson29060642009-01-31 22:14:21 +00009291 if (!PyUnicode_Check(v)) {
9292 Py_INCREF(Py_NotImplemented);
9293 return Py_NotImplemented;
9294 }
9295 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +00009296}
9297
9298static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009299 0, /*nb_add*/
9300 0, /*nb_subtract*/
9301 0, /*nb_multiply*/
9302 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +00009303};
9304
Guido van Rossumd57fd912000-03-10 22:53:23 +00009305static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009306 (lenfunc) unicode_length, /* sq_length */
9307 PyUnicode_Concat, /* sq_concat */
9308 (ssizeargfunc) unicode_repeat, /* sq_repeat */
9309 (ssizeargfunc) unicode_getitem, /* sq_item */
9310 0, /* sq_slice */
9311 0, /* sq_ass_item */
9312 0, /* sq_ass_slice */
9313 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009314};
9315
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009316static PyObject*
9317unicode_subscript(PyUnicodeObject* self, PyObject* item)
9318{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009319 if (PyIndex_Check(item)) {
9320 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009321 if (i == -1 && PyErr_Occurred())
9322 return NULL;
9323 if (i < 0)
Martin v. Löwisdea59e52006-01-05 10:00:36 +00009324 i += PyUnicode_GET_SIZE(self);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009325 return unicode_getitem(self, i);
9326 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00009327 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009328 Py_UNICODE* source_buf;
9329 Py_UNICODE* result_buf;
9330 PyObject* result;
9331
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00009332 if (PySlice_GetIndicesEx(item, PyUnicode_GET_SIZE(self),
Benjamin Peterson29060642009-01-31 22:14:21 +00009333 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009334 return NULL;
9335 }
9336
9337 if (slicelength <= 0) {
9338 return PyUnicode_FromUnicode(NULL, 0);
Thomas Woutersed03b412007-08-28 21:37:11 +00009339 } else if (start == 0 && step == 1 && slicelength == self->length &&
9340 PyUnicode_CheckExact(self)) {
9341 Py_INCREF(self);
9342 return (PyObject *)self;
9343 } else if (step == 1) {
9344 return PyUnicode_FromUnicode(self->str + start, slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009345 } else {
9346 source_buf = PyUnicode_AS_UNICODE((PyObject*)self);
Christian Heimesb186d002008-03-18 15:15:01 +00009347 result_buf = (Py_UNICODE *)PyObject_MALLOC(slicelength*
9348 sizeof(Py_UNICODE));
Benjamin Peterson14339b62009-01-31 16:36:08 +00009349
Benjamin Peterson29060642009-01-31 22:14:21 +00009350 if (result_buf == NULL)
9351 return PyErr_NoMemory();
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009352
9353 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
9354 result_buf[i] = source_buf[cur];
9355 }
Tim Petersced69f82003-09-16 20:30:58 +00009356
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009357 result = PyUnicode_FromUnicode(result_buf, slicelength);
Christian Heimesb186d002008-03-18 15:15:01 +00009358 PyObject_FREE(result_buf);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009359 return result;
9360 }
9361 } else {
9362 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
9363 return NULL;
9364 }
9365}
9366
9367static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009368 (lenfunc)unicode_length, /* mp_length */
9369 (binaryfunc)unicode_subscript, /* mp_subscript */
9370 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009371};
9372
Guido van Rossumd57fd912000-03-10 22:53:23 +00009373
Guido van Rossumd57fd912000-03-10 22:53:23 +00009374/* Helpers for PyUnicode_Format() */
9375
9376static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00009377getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009378{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009379 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009380 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009381 (*p_argidx)++;
9382 if (arglen < 0)
9383 return args;
9384 else
9385 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009386 }
9387 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009388 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009389 return NULL;
9390}
9391
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009392/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009393
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009394static PyObject *
9395formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009396{
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009397 char *p;
9398 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009399 double x;
Tim Petersced69f82003-09-16 20:30:58 +00009400
Guido van Rossumd57fd912000-03-10 22:53:23 +00009401 x = PyFloat_AsDouble(v);
9402 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009403 return NULL;
9404
Guido van Rossumd57fd912000-03-10 22:53:23 +00009405 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009406 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +00009407
Eric Smith0923d1d2009-04-16 20:16:10 +00009408 p = PyOS_double_to_string(x, type, prec,
9409 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009410 if (p == NULL)
9411 return NULL;
9412 result = PyUnicode_FromStringAndSize(p, strlen(p));
Eric Smith0923d1d2009-04-16 20:16:10 +00009413 PyMem_Free(p);
9414 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009415}
9416
Tim Peters38fd5b62000-09-21 05:43:11 +00009417static PyObject*
9418formatlong(PyObject *val, int flags, int prec, int type)
9419{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009420 char *buf;
9421 int len;
9422 PyObject *str; /* temporary string object. */
9423 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +00009424
Benjamin Peterson14339b62009-01-31 16:36:08 +00009425 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
9426 if (!str)
9427 return NULL;
9428 result = PyUnicode_FromStringAndSize(buf, len);
9429 Py_DECREF(str);
9430 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +00009431}
9432
Guido van Rossumd57fd912000-03-10 22:53:23 +00009433static int
9434formatchar(Py_UNICODE *buf,
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009435 size_t buflen,
9436 PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009437{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00009438 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009439 if (PyUnicode_Check(v)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009440 if (PyUnicode_GET_SIZE(v) == 1) {
9441 buf[0] = PyUnicode_AS_UNICODE(v)[0];
9442 buf[1] = '\0';
9443 return 1;
9444 }
9445#ifndef Py_UNICODE_WIDE
9446 if (PyUnicode_GET_SIZE(v) == 2) {
9447 /* Decode a valid surrogate pair */
9448 int c0 = PyUnicode_AS_UNICODE(v)[0];
9449 int c1 = PyUnicode_AS_UNICODE(v)[1];
9450 if (0xD800 <= c0 && c0 <= 0xDBFF &&
9451 0xDC00 <= c1 && c1 <= 0xDFFF) {
9452 buf[0] = c0;
9453 buf[1] = c1;
9454 buf[2] = '\0';
9455 return 2;
9456 }
9457 }
9458#endif
9459 goto onError;
9460 }
9461 else {
9462 /* Integer input truncated to a character */
9463 long x;
9464 x = PyLong_AsLong(v);
9465 if (x == -1 && PyErr_Occurred())
9466 goto onError;
9467
9468 if (x < 0 || x > 0x10ffff) {
9469 PyErr_SetString(PyExc_OverflowError,
9470 "%c arg not in range(0x110000)");
9471 return -1;
9472 }
9473
9474#ifndef Py_UNICODE_WIDE
9475 if (x > 0xffff) {
9476 x -= 0x10000;
9477 buf[0] = (Py_UNICODE)(0xD800 | (x >> 10));
9478 buf[1] = (Py_UNICODE)(0xDC00 | (x & 0x3FF));
9479 return 2;
9480 }
9481#endif
9482 buf[0] = (Py_UNICODE) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009483 buf[1] = '\0';
9484 return 1;
9485 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00009486
Benjamin Peterson29060642009-01-31 22:14:21 +00009487 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009488 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009489 "%c requires int or char");
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009490 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009491}
9492
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009493/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009494 FORMATBUFLEN is the length of the buffer in which chars are formatted.
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009495*/
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009496#define FORMATBUFLEN (size_t)10
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009497
Guido van Rossumd57fd912000-03-10 22:53:23 +00009498PyObject *PyUnicode_Format(PyObject *format,
Benjamin Peterson29060642009-01-31 22:14:21 +00009499 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009500{
9501 Py_UNICODE *fmt, *res;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009502 Py_ssize_t fmtcnt, rescnt, reslen, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009503 int args_owned = 0;
9504 PyUnicodeObject *result = NULL;
9505 PyObject *dict = NULL;
9506 PyObject *uformat;
Tim Petersced69f82003-09-16 20:30:58 +00009507
Guido van Rossumd57fd912000-03-10 22:53:23 +00009508 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009509 PyErr_BadInternalCall();
9510 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009511 }
9512 uformat = PyUnicode_FromObject(format);
Fred Drakee4315f52000-05-09 19:53:39 +00009513 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009514 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009515 fmt = PyUnicode_AS_UNICODE(uformat);
9516 fmtcnt = PyUnicode_GET_SIZE(uformat);
9517
9518 reslen = rescnt = fmtcnt + 100;
9519 result = _PyUnicode_New(reslen);
9520 if (result == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009521 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009522 res = PyUnicode_AS_UNICODE(result);
9523
9524 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009525 arglen = PyTuple_Size(args);
9526 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009527 }
9528 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009529 arglen = -1;
9530 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009531 }
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -04009532 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +00009533 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009534
9535 while (--fmtcnt >= 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009536 if (*fmt != '%') {
9537 if (--rescnt < 0) {
9538 rescnt = fmtcnt + 100;
9539 reslen += rescnt;
9540 if (_PyUnicode_Resize(&result, reslen) < 0)
9541 goto onError;
9542 res = PyUnicode_AS_UNICODE(result) + reslen - rescnt;
9543 --rescnt;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009544 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009545 *res++ = *fmt++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009546 }
9547 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009548 /* Got a format specifier */
9549 int flags = 0;
9550 Py_ssize_t width = -1;
9551 int prec = -1;
9552 Py_UNICODE c = '\0';
9553 Py_UNICODE fill;
9554 int isnumok;
9555 PyObject *v = NULL;
9556 PyObject *temp = NULL;
9557 Py_UNICODE *pbuf;
9558 Py_UNICODE sign;
9559 Py_ssize_t len;
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009560 Py_UNICODE formatbuf[FORMATBUFLEN]; /* For formatchar() */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009561
Benjamin Peterson29060642009-01-31 22:14:21 +00009562 fmt++;
9563 if (*fmt == '(') {
9564 Py_UNICODE *keystart;
9565 Py_ssize_t keylen;
9566 PyObject *key;
9567 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +00009568
Benjamin Peterson29060642009-01-31 22:14:21 +00009569 if (dict == NULL) {
9570 PyErr_SetString(PyExc_TypeError,
9571 "format requires a mapping");
9572 goto onError;
9573 }
9574 ++fmt;
9575 --fmtcnt;
9576 keystart = fmt;
9577 /* Skip over balanced parentheses */
9578 while (pcount > 0 && --fmtcnt >= 0) {
9579 if (*fmt == ')')
9580 --pcount;
9581 else if (*fmt == '(')
9582 ++pcount;
9583 fmt++;
9584 }
9585 keylen = fmt - keystart - 1;
9586 if (fmtcnt < 0 || pcount > 0) {
9587 PyErr_SetString(PyExc_ValueError,
9588 "incomplete format key");
9589 goto onError;
9590 }
9591#if 0
9592 /* keys are converted to strings using UTF-8 and
9593 then looked up since Python uses strings to hold
9594 variables names etc. in its namespaces and we
9595 wouldn't want to break common idioms. */
9596 key = PyUnicode_EncodeUTF8(keystart,
9597 keylen,
9598 NULL);
9599#else
9600 key = PyUnicode_FromUnicode(keystart, keylen);
9601#endif
9602 if (key == NULL)
9603 goto onError;
9604 if (args_owned) {
9605 Py_DECREF(args);
9606 args_owned = 0;
9607 }
9608 args = PyObject_GetItem(dict, key);
9609 Py_DECREF(key);
9610 if (args == NULL) {
9611 goto onError;
9612 }
9613 args_owned = 1;
9614 arglen = -1;
9615 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009616 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009617 while (--fmtcnt >= 0) {
9618 switch (c = *fmt++) {
9619 case '-': flags |= F_LJUST; continue;
9620 case '+': flags |= F_SIGN; continue;
9621 case ' ': flags |= F_BLANK; continue;
9622 case '#': flags |= F_ALT; continue;
9623 case '0': flags |= F_ZERO; continue;
9624 }
9625 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009626 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009627 if (c == '*') {
9628 v = getnextarg(args, arglen, &argidx);
9629 if (v == NULL)
9630 goto onError;
9631 if (!PyLong_Check(v)) {
9632 PyErr_SetString(PyExc_TypeError,
9633 "* wants int");
9634 goto onError;
9635 }
9636 width = PyLong_AsLong(v);
9637 if (width == -1 && PyErr_Occurred())
9638 goto onError;
9639 if (width < 0) {
9640 flags |= F_LJUST;
9641 width = -width;
9642 }
9643 if (--fmtcnt >= 0)
9644 c = *fmt++;
9645 }
9646 else if (c >= '0' && c <= '9') {
9647 width = c - '0';
9648 while (--fmtcnt >= 0) {
9649 c = *fmt++;
9650 if (c < '0' || c > '9')
9651 break;
Mark Dickinsonfb90c092012-10-28 10:18:03 +00009652 if (width > (PY_SSIZE_T_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009653 PyErr_SetString(PyExc_ValueError,
9654 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009655 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00009656 }
9657 width = width*10 + (c - '0');
9658 }
9659 }
9660 if (c == '.') {
9661 prec = 0;
9662 if (--fmtcnt >= 0)
9663 c = *fmt++;
9664 if (c == '*') {
9665 v = getnextarg(args, arglen, &argidx);
9666 if (v == NULL)
9667 goto onError;
9668 if (!PyLong_Check(v)) {
9669 PyErr_SetString(PyExc_TypeError,
9670 "* wants int");
9671 goto onError;
9672 }
9673 prec = PyLong_AsLong(v);
9674 if (prec == -1 && PyErr_Occurred())
9675 goto onError;
9676 if (prec < 0)
9677 prec = 0;
9678 if (--fmtcnt >= 0)
9679 c = *fmt++;
9680 }
9681 else if (c >= '0' && c <= '9') {
9682 prec = c - '0';
9683 while (--fmtcnt >= 0) {
Stefan Krah99212f62010-07-19 17:58:26 +00009684 c = *fmt++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009685 if (c < '0' || c > '9')
9686 break;
Mark Dickinsonfb90c092012-10-28 10:18:03 +00009687 if (prec > (INT_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009688 PyErr_SetString(PyExc_ValueError,
9689 "prec too big");
9690 goto onError;
9691 }
9692 prec = prec*10 + (c - '0');
9693 }
9694 }
9695 } /* prec */
9696 if (fmtcnt >= 0) {
9697 if (c == 'h' || c == 'l' || c == 'L') {
9698 if (--fmtcnt >= 0)
9699 c = *fmt++;
9700 }
9701 }
9702 if (fmtcnt < 0) {
9703 PyErr_SetString(PyExc_ValueError,
9704 "incomplete format");
9705 goto onError;
9706 }
9707 if (c != '%') {
9708 v = getnextarg(args, arglen, &argidx);
9709 if (v == NULL)
9710 goto onError;
9711 }
9712 sign = 0;
9713 fill = ' ';
9714 switch (c) {
9715
9716 case '%':
9717 pbuf = formatbuf;
9718 /* presume that buffer length is at least 1 */
9719 pbuf[0] = '%';
9720 len = 1;
9721 break;
9722
9723 case 's':
9724 case 'r':
9725 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +00009726 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +00009727 temp = v;
9728 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009729 }
9730 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009731 if (c == 's')
9732 temp = PyObject_Str(v);
9733 else if (c == 'r')
9734 temp = PyObject_Repr(v);
9735 else
9736 temp = PyObject_ASCII(v);
9737 if (temp == NULL)
9738 goto onError;
9739 if (PyUnicode_Check(temp))
9740 /* nothing to do */;
9741 else {
9742 Py_DECREF(temp);
9743 PyErr_SetString(PyExc_TypeError,
9744 "%s argument has non-string str()");
9745 goto onError;
9746 }
9747 }
9748 pbuf = PyUnicode_AS_UNICODE(temp);
9749 len = PyUnicode_GET_SIZE(temp);
9750 if (prec >= 0 && len > prec)
9751 len = prec;
9752 break;
9753
9754 case 'i':
9755 case 'd':
9756 case 'u':
9757 case 'o':
9758 case 'x':
9759 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +00009760 isnumok = 0;
9761 if (PyNumber_Check(v)) {
9762 PyObject *iobj=NULL;
9763
9764 if (PyLong_Check(v)) {
9765 iobj = v;
9766 Py_INCREF(iobj);
9767 }
9768 else {
9769 iobj = PyNumber_Long(v);
9770 }
9771 if (iobj!=NULL) {
9772 if (PyLong_Check(iobj)) {
9773 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -07009774 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +00009775 Py_DECREF(iobj);
9776 if (!temp)
9777 goto onError;
9778 pbuf = PyUnicode_AS_UNICODE(temp);
9779 len = PyUnicode_GET_SIZE(temp);
9780 sign = 1;
9781 }
9782 else {
9783 Py_DECREF(iobj);
9784 }
9785 }
9786 }
9787 if (!isnumok) {
9788 PyErr_Format(PyExc_TypeError,
9789 "%%%c format: a number is required, "
9790 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
9791 goto onError;
9792 }
9793 if (flags & F_ZERO)
9794 fill = '0';
9795 break;
9796
9797 case 'e':
9798 case 'E':
9799 case 'f':
9800 case 'F':
9801 case 'g':
9802 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009803 temp = formatfloat(v, flags, prec, c);
9804 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +00009805 goto onError;
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009806 pbuf = PyUnicode_AS_UNICODE(temp);
9807 len = PyUnicode_GET_SIZE(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +00009808 sign = 1;
9809 if (flags & F_ZERO)
9810 fill = '0';
9811 break;
9812
9813 case 'c':
9814 pbuf = formatbuf;
9815 len = formatchar(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), v);
9816 if (len < 0)
9817 goto onError;
9818 break;
9819
9820 default:
9821 PyErr_Format(PyExc_ValueError,
9822 "unsupported format character '%c' (0x%x) "
9823 "at index %zd",
9824 (31<=c && c<=126) ? (char)c : '?',
9825 (int)c,
9826 (Py_ssize_t)(fmt - 1 -
9827 PyUnicode_AS_UNICODE(uformat)));
9828 goto onError;
9829 }
9830 if (sign) {
9831 if (*pbuf == '-' || *pbuf == '+') {
9832 sign = *pbuf++;
9833 len--;
9834 }
9835 else if (flags & F_SIGN)
9836 sign = '+';
9837 else if (flags & F_BLANK)
9838 sign = ' ';
9839 else
9840 sign = 0;
9841 }
9842 if (width < len)
9843 width = len;
9844 if (rescnt - (sign != 0) < width) {
9845 reslen -= rescnt;
9846 rescnt = width + fmtcnt + 100;
9847 reslen += rescnt;
9848 if (reslen < 0) {
9849 Py_XDECREF(temp);
9850 PyErr_NoMemory();
9851 goto onError;
9852 }
9853 if (_PyUnicode_Resize(&result, reslen) < 0) {
9854 Py_XDECREF(temp);
9855 goto onError;
9856 }
9857 res = PyUnicode_AS_UNICODE(result)
9858 + reslen - rescnt;
9859 }
9860 if (sign) {
9861 if (fill != ' ')
9862 *res++ = sign;
9863 rescnt--;
9864 if (width > len)
9865 width--;
9866 }
9867 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
9868 assert(pbuf[0] == '0');
9869 assert(pbuf[1] == c);
9870 if (fill != ' ') {
9871 *res++ = *pbuf++;
9872 *res++ = *pbuf++;
9873 }
9874 rescnt -= 2;
9875 width -= 2;
9876 if (width < 0)
9877 width = 0;
9878 len -= 2;
9879 }
9880 if (width > len && !(flags & F_LJUST)) {
9881 do {
9882 --rescnt;
9883 *res++ = fill;
9884 } while (--width > len);
9885 }
9886 if (fill == ' ') {
9887 if (sign)
9888 *res++ = sign;
9889 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
9890 assert(pbuf[0] == '0');
9891 assert(pbuf[1] == c);
9892 *res++ = *pbuf++;
9893 *res++ = *pbuf++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009894 }
9895 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009896 Py_UNICODE_COPY(res, pbuf, len);
9897 res += len;
9898 rescnt -= len;
9899 while (--width >= len) {
9900 --rescnt;
9901 *res++ = ' ';
9902 }
9903 if (dict && (argidx < arglen) && c != '%') {
9904 PyErr_SetString(PyExc_TypeError,
9905 "not all arguments converted during string formatting");
Thomas Woutersa96affe2006-03-12 00:29:36 +00009906 Py_XDECREF(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +00009907 goto onError;
9908 }
9909 Py_XDECREF(temp);
9910 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009911 } /* until end */
9912 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009913 PyErr_SetString(PyExc_TypeError,
9914 "not all arguments converted during string formatting");
9915 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009916 }
9917
Thomas Woutersa96affe2006-03-12 00:29:36 +00009918 if (_PyUnicode_Resize(&result, reslen - rescnt) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009919 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009920 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009921 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009922 }
9923 Py_DECREF(uformat);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009924 return (PyObject *)result;
9925
Benjamin Peterson29060642009-01-31 22:14:21 +00009926 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009927 Py_XDECREF(result);
9928 Py_DECREF(uformat);
9929 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009930 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009931 }
9932 return NULL;
9933}
9934
Jeremy Hylton938ace62002-07-17 16:30:39 +00009935static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +00009936unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
9937
Tim Peters6d6c1a32001-08-02 04:15:00 +00009938static PyObject *
9939unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9940{
Benjamin Peterson29060642009-01-31 22:14:21 +00009941 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009942 static char *kwlist[] = {"object", "encoding", "errors", 0};
9943 char *encoding = NULL;
9944 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00009945
Benjamin Peterson14339b62009-01-31 16:36:08 +00009946 if (type != &PyUnicode_Type)
9947 return unicode_subtype_new(type, args, kwds);
9948 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +00009949 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009950 return NULL;
9951 if (x == NULL)
9952 return (PyObject *)_PyUnicode_New(0);
9953 if (encoding == NULL && errors == NULL)
9954 return PyObject_Str(x);
9955 else
Benjamin Peterson29060642009-01-31 22:14:21 +00009956 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +00009957}
9958
Guido van Rossume023fe02001-08-30 03:12:59 +00009959static PyObject *
9960unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9961{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009962 PyUnicodeObject *tmp, *pnew;
9963 Py_ssize_t n;
Guido van Rossume023fe02001-08-30 03:12:59 +00009964
Benjamin Peterson14339b62009-01-31 16:36:08 +00009965 assert(PyType_IsSubtype(type, &PyUnicode_Type));
9966 tmp = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
9967 if (tmp == NULL)
9968 return NULL;
9969 assert(PyUnicode_Check(tmp));
9970 pnew = (PyUnicodeObject *) type->tp_alloc(type, n = tmp->length);
9971 if (pnew == NULL) {
9972 Py_DECREF(tmp);
9973 return NULL;
9974 }
9975 pnew->str = (Py_UNICODE*) PyObject_MALLOC(sizeof(Py_UNICODE) * (n+1));
9976 if (pnew->str == NULL) {
9977 _Py_ForgetReference((PyObject *)pnew);
9978 PyObject_Del(pnew);
9979 Py_DECREF(tmp);
9980 return PyErr_NoMemory();
9981 }
9982 Py_UNICODE_COPY(pnew->str, tmp->str, n+1);
9983 pnew->length = n;
9984 pnew->hash = tmp->hash;
9985 Py_DECREF(tmp);
9986 return (PyObject *)pnew;
Guido van Rossume023fe02001-08-30 03:12:59 +00009987}
9988
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009989PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07009990"str(object='') -> str\n\
9991str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00009992\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +10009993Create a new string object from the given object. If encoding or\n\
9994errors is specified, then the object must expose a data buffer\n\
9995that will be decoded using the given encoding and error handler.\n\
9996Otherwise, returns the result of object.__str__() (if defined)\n\
9997or repr(object).\n\
9998encoding defaults to sys.getdefaultencoding().\n\
9999errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000010000
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010001static PyObject *unicode_iter(PyObject *seq);
10002
Guido van Rossumd57fd912000-03-10 22:53:23 +000010003PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000010004 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000010005 "str", /* tp_name */
10006 sizeof(PyUnicodeObject), /* tp_size */
10007 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000010008 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000010009 (destructor)unicode_dealloc, /* tp_dealloc */
10010 0, /* tp_print */
10011 0, /* tp_getattr */
10012 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000010013 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000010014 unicode_repr, /* tp_repr */
10015 &unicode_as_number, /* tp_as_number */
10016 &unicode_as_sequence, /* tp_as_sequence */
10017 &unicode_as_mapping, /* tp_as_mapping */
10018 (hashfunc) unicode_hash, /* tp_hash*/
10019 0, /* tp_call*/
10020 (reprfunc) unicode_str, /* tp_str */
10021 PyObject_GenericGetAttr, /* tp_getattro */
10022 0, /* tp_setattro */
10023 0, /* tp_as_buffer */
10024 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000010025 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000010026 unicode_doc, /* tp_doc */
10027 0, /* tp_traverse */
10028 0, /* tp_clear */
10029 PyUnicode_RichCompare, /* tp_richcompare */
10030 0, /* tp_weaklistoffset */
10031 unicode_iter, /* tp_iter */
10032 0, /* tp_iternext */
10033 unicode_methods, /* tp_methods */
10034 0, /* tp_members */
10035 0, /* tp_getset */
10036 &PyBaseObject_Type, /* tp_base */
10037 0, /* tp_dict */
10038 0, /* tp_descr_get */
10039 0, /* tp_descr_set */
10040 0, /* tp_dictoffset */
10041 0, /* tp_init */
10042 0, /* tp_alloc */
10043 unicode_new, /* tp_new */
10044 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000010045};
10046
10047/* Initialize the Unicode implementation */
10048
Thomas Wouters78890102000-07-22 19:25:51 +000010049void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010050{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000010051 int i;
10052
Thomas Wouters477c8d52006-05-27 19:21:47 +000010053 /* XXX - move this array to unicodectype.c ? */
10054 Py_UNICODE linebreak[] = {
10055 0x000A, /* LINE FEED */
10056 0x000D, /* CARRIAGE RETURN */
10057 0x001C, /* FILE SEPARATOR */
10058 0x001D, /* GROUP SEPARATOR */
10059 0x001E, /* RECORD SEPARATOR */
10060 0x0085, /* NEXT LINE */
10061 0x2028, /* LINE SEPARATOR */
10062 0x2029, /* PARAGRAPH SEPARATOR */
10063 };
10064
Fred Drakee4315f52000-05-09 19:53:39 +000010065 /* Init the implementation */
Christian Heimes2202f872008-02-06 14:31:34 +000010066 free_list = NULL;
10067 numfree = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010068 unicode_empty = _PyUnicode_New(0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000010069 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +000010070 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000010071
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000010072 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000010073 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000010074 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010075 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000010076
10077 /* initialize the linebreak bloom filter */
10078 bloom_linebreak = make_bloom_mask(
10079 linebreak, sizeof(linebreak) / sizeof(linebreak[0])
10080 );
Thomas Wouters0e3f5912006-08-11 14:57:12 +000010081
10082 PyType_Ready(&EncodingMapType);
Benjamin Petersonc4311282012-10-30 23:21:10 -040010083
10084 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
10085 Py_FatalError("Can't initialize field name iterator type");
10086
10087 if (PyType_Ready(&PyFormatterIter_Type) < 0)
10088 Py_FatalError("Can't initialize formatter iter type");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010089}
10090
10091/* Finalize the Unicode implementation */
10092
Christian Heimesa156e092008-02-16 07:38:31 +000010093int
10094PyUnicode_ClearFreeList(void)
10095{
10096 int freelist_size = numfree;
10097 PyUnicodeObject *u;
10098
10099 for (u = free_list; u != NULL;) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010100 PyUnicodeObject *v = u;
10101 u = *(PyUnicodeObject **)u;
10102 if (v->str)
10103 PyObject_DEL(v->str);
10104 Py_XDECREF(v->defenc);
10105 PyObject_Del(v);
10106 numfree--;
Christian Heimesa156e092008-02-16 07:38:31 +000010107 }
10108 free_list = NULL;
10109 assert(numfree == 0);
10110 return freelist_size;
10111}
10112
Guido van Rossumd57fd912000-03-10 22:53:23 +000010113void
Thomas Wouters78890102000-07-22 19:25:51 +000010114_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010115{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000010116 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010117
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000010118 Py_XDECREF(unicode_empty);
10119 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000010120
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000010121 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010122 if (unicode_latin1[i]) {
10123 Py_DECREF(unicode_latin1[i]);
10124 unicode_latin1[i] = NULL;
10125 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000010126 }
Christian Heimesa156e092008-02-16 07:38:31 +000010127 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000010128}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000010129
Walter Dörwald16807132007-05-25 13:52:07 +000010130void
10131PyUnicode_InternInPlace(PyObject **p)
10132{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010133 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
10134 PyObject *t;
10135 if (s == NULL || !PyUnicode_Check(s))
10136 Py_FatalError(
10137 "PyUnicode_InternInPlace: unicode strings only please!");
10138 /* If it's a subclass, we don't really know what putting
10139 it in the interned dict might do. */
10140 if (!PyUnicode_CheckExact(s))
10141 return;
10142 if (PyUnicode_CHECK_INTERNED(s))
10143 return;
10144 if (interned == NULL) {
10145 interned = PyDict_New();
10146 if (interned == NULL) {
10147 PyErr_Clear(); /* Don't leave an exception */
10148 return;
10149 }
10150 }
10151 /* It might be that the GetItem call fails even
10152 though the key is present in the dictionary,
10153 namely when this happens during a stack overflow. */
10154 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000010155 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010156 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000010157
Benjamin Peterson29060642009-01-31 22:14:21 +000010158 if (t) {
10159 Py_INCREF(t);
10160 Py_DECREF(*p);
10161 *p = t;
10162 return;
10163 }
Walter Dörwald16807132007-05-25 13:52:07 +000010164
Benjamin Peterson14339b62009-01-31 16:36:08 +000010165 PyThreadState_GET()->recursion_critical = 1;
10166 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
10167 PyErr_Clear();
10168 PyThreadState_GET()->recursion_critical = 0;
10169 return;
10170 }
10171 PyThreadState_GET()->recursion_critical = 0;
10172 /* The two references in interned are not counted by refcnt.
10173 The deallocator will take care of this */
10174 Py_REFCNT(s) -= 2;
10175 PyUnicode_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000010176}
10177
10178void
10179PyUnicode_InternImmortal(PyObject **p)
10180{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010181 PyUnicode_InternInPlace(p);
10182 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
10183 PyUnicode_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
10184 Py_INCREF(*p);
10185 }
Walter Dörwald16807132007-05-25 13:52:07 +000010186}
10187
10188PyObject *
10189PyUnicode_InternFromString(const char *cp)
10190{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010191 PyObject *s = PyUnicode_FromString(cp);
10192 if (s == NULL)
10193 return NULL;
10194 PyUnicode_InternInPlace(&s);
10195 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000010196}
10197
10198void _Py_ReleaseInternedUnicodeStrings(void)
10199{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010200 PyObject *keys;
10201 PyUnicodeObject *s;
10202 Py_ssize_t i, n;
10203 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000010204
Benjamin Peterson14339b62009-01-31 16:36:08 +000010205 if (interned == NULL || !PyDict_Check(interned))
10206 return;
10207 keys = PyDict_Keys(interned);
10208 if (keys == NULL || !PyList_Check(keys)) {
10209 PyErr_Clear();
10210 return;
10211 }
Walter Dörwald16807132007-05-25 13:52:07 +000010212
Benjamin Peterson14339b62009-01-31 16:36:08 +000010213 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
10214 detector, interned unicode strings are not forcibly deallocated;
10215 rather, we give them their stolen references back, and then clear
10216 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000010217
Benjamin Peterson14339b62009-01-31 16:36:08 +000010218 n = PyList_GET_SIZE(keys);
10219 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000010220 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010221 for (i = 0; i < n; i++) {
10222 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
10223 switch (s->state) {
10224 case SSTATE_NOT_INTERNED:
10225 /* XXX Shouldn't happen */
10226 break;
10227 case SSTATE_INTERNED_IMMORTAL:
10228 Py_REFCNT(s) += 1;
10229 immortal_size += s->length;
10230 break;
10231 case SSTATE_INTERNED_MORTAL:
10232 Py_REFCNT(s) += 2;
10233 mortal_size += s->length;
10234 break;
10235 default:
10236 Py_FatalError("Inconsistent interned string state.");
10237 }
10238 s->state = SSTATE_NOT_INTERNED;
10239 }
10240 fprintf(stderr, "total size of all interned strings: "
10241 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
10242 "mortal/immortal\n", mortal_size, immortal_size);
10243 Py_DECREF(keys);
10244 PyDict_Clear(interned);
10245 Py_DECREF(interned);
10246 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000010247}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010248
10249
10250/********************* Unicode Iterator **************************/
10251
10252typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010253 PyObject_HEAD
10254 Py_ssize_t it_index;
10255 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010256} unicodeiterobject;
10257
10258static void
10259unicodeiter_dealloc(unicodeiterobject *it)
10260{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010261 _PyObject_GC_UNTRACK(it);
10262 Py_XDECREF(it->it_seq);
10263 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010264}
10265
10266static int
10267unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
10268{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010269 Py_VISIT(it->it_seq);
10270 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010271}
10272
10273static PyObject *
10274unicodeiter_next(unicodeiterobject *it)
10275{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010276 PyUnicodeObject *seq;
10277 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010278
Benjamin Peterson14339b62009-01-31 16:36:08 +000010279 assert(it != NULL);
10280 seq = it->it_seq;
10281 if (seq == NULL)
10282 return NULL;
10283 assert(PyUnicode_Check(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010284
Benjamin Peterson14339b62009-01-31 16:36:08 +000010285 if (it->it_index < PyUnicode_GET_SIZE(seq)) {
10286 item = PyUnicode_FromUnicode(
Benjamin Peterson29060642009-01-31 22:14:21 +000010287 PyUnicode_AS_UNICODE(seq)+it->it_index, 1);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010288 if (item != NULL)
10289 ++it->it_index;
10290 return item;
10291 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010292
Benjamin Peterson14339b62009-01-31 16:36:08 +000010293 Py_DECREF(seq);
10294 it->it_seq = NULL;
10295 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010296}
10297
10298static PyObject *
10299unicodeiter_len(unicodeiterobject *it)
10300{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010301 Py_ssize_t len = 0;
10302 if (it->it_seq)
10303 len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index;
10304 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010305}
10306
10307PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
10308
10309static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010310 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000010311 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000010312 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010313};
10314
10315PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010316 PyVarObject_HEAD_INIT(&PyType_Type, 0)
10317 "str_iterator", /* tp_name */
10318 sizeof(unicodeiterobject), /* tp_basicsize */
10319 0, /* tp_itemsize */
10320 /* methods */
10321 (destructor)unicodeiter_dealloc, /* tp_dealloc */
10322 0, /* tp_print */
10323 0, /* tp_getattr */
10324 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000010325 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000010326 0, /* tp_repr */
10327 0, /* tp_as_number */
10328 0, /* tp_as_sequence */
10329 0, /* tp_as_mapping */
10330 0, /* tp_hash */
10331 0, /* tp_call */
10332 0, /* tp_str */
10333 PyObject_GenericGetAttr, /* tp_getattro */
10334 0, /* tp_setattro */
10335 0, /* tp_as_buffer */
10336 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
10337 0, /* tp_doc */
10338 (traverseproc)unicodeiter_traverse, /* tp_traverse */
10339 0, /* tp_clear */
10340 0, /* tp_richcompare */
10341 0, /* tp_weaklistoffset */
10342 PyObject_SelfIter, /* tp_iter */
10343 (iternextfunc)unicodeiter_next, /* tp_iternext */
10344 unicodeiter_methods, /* tp_methods */
10345 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010346};
10347
10348static PyObject *
10349unicode_iter(PyObject *seq)
10350{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010351 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010352
Benjamin Peterson14339b62009-01-31 16:36:08 +000010353 if (!PyUnicode_Check(seq)) {
10354 PyErr_BadInternalCall();
10355 return NULL;
10356 }
10357 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
10358 if (it == NULL)
10359 return NULL;
10360 it->it_index = 0;
10361 Py_INCREF(seq);
10362 it->it_seq = (PyUnicodeObject *)seq;
10363 _PyObject_GC_TRACK(it);
10364 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010365}
10366
Martin v. Löwis5b222132007-06-10 09:51:05 +000010367size_t
10368Py_UNICODE_strlen(const Py_UNICODE *u)
10369{
10370 int res = 0;
10371 while(*u++)
10372 res++;
10373 return res;
10374}
10375
10376Py_UNICODE*
10377Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
10378{
10379 Py_UNICODE *u = s1;
10380 while ((*u++ = *s2++));
10381 return s1;
10382}
10383
10384Py_UNICODE*
10385Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
10386{
10387 Py_UNICODE *u = s1;
10388 while ((*u++ = *s2++))
10389 if (n-- == 0)
10390 break;
10391 return s1;
10392}
10393
Victor Stinnerc4eb7652010-09-01 23:43:50 +000010394Py_UNICODE*
10395Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
10396{
10397 Py_UNICODE *u1 = s1;
10398 u1 += Py_UNICODE_strlen(u1);
10399 Py_UNICODE_strcpy(u1, s2);
10400 return s1;
10401}
10402
Martin v. Löwis5b222132007-06-10 09:51:05 +000010403int
10404Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
10405{
10406 while (*s1 && *s2 && *s1 == *s2)
10407 s1++, s2++;
10408 if (*s1 && *s2)
10409 return (*s1 < *s2) ? -1 : +1;
10410 if (*s1)
10411 return 1;
10412 if (*s2)
10413 return -1;
10414 return 0;
10415}
10416
Victor Stinneref8d95c2010-08-16 22:03:11 +000010417int
10418Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
10419{
10420 register Py_UNICODE u1, u2;
10421 for (; n != 0; n--) {
10422 u1 = *s1;
10423 u2 = *s2;
10424 if (u1 != u2)
10425 return (u1 < u2) ? -1 : +1;
10426 if (u1 == '\0')
10427 return 0;
10428 s1++;
10429 s2++;
10430 }
10431 return 0;
10432}
10433
Martin v. Löwis5b222132007-06-10 09:51:05 +000010434Py_UNICODE*
10435Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
10436{
10437 const Py_UNICODE *p;
10438 for (p = s; *p; p++)
10439 if (*p == c)
10440 return (Py_UNICODE*)p;
10441 return NULL;
10442}
10443
Victor Stinner331ea922010-08-10 16:37:20 +000010444Py_UNICODE*
10445Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
10446{
10447 const Py_UNICODE *p;
10448 p = s + Py_UNICODE_strlen(s);
10449 while (p != s) {
10450 p--;
10451 if (*p == c)
10452 return (Py_UNICODE*)p;
10453 }
10454 return NULL;
10455}
10456
Victor Stinner71133ff2010-09-01 23:43:53 +000010457Py_UNICODE*
Victor Stinner46408602010-09-03 16:18:00 +000010458PyUnicode_AsUnicodeCopy(PyObject *object)
Victor Stinner71133ff2010-09-01 23:43:53 +000010459{
10460 PyUnicodeObject *unicode = (PyUnicodeObject *)object;
10461 Py_UNICODE *copy;
10462 Py_ssize_t size;
10463
10464 /* Ensure we won't overflow the size. */
10465 if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
10466 PyErr_NoMemory();
10467 return NULL;
10468 }
10469 size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
10470 size *= sizeof(Py_UNICODE);
10471 copy = PyMem_Malloc(size);
10472 if (copy == NULL) {
10473 PyErr_NoMemory();
10474 return NULL;
10475 }
10476 memcpy(copy, PyUnicode_AS_UNICODE(unicode), size);
10477 return copy;
10478}
Martin v. Löwis5b222132007-06-10 09:51:05 +000010479
Georg Brandl66c221e2010-10-14 07:04:07 +000010480/* A _string module, to export formatter_parser and formatter_field_name_split
10481 to the string.Formatter class implemented in Python. */
10482
10483static PyMethodDef _string_methods[] = {
10484 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
10485 METH_O, PyDoc_STR("split the argument as a field name")},
10486 {"formatter_parser", (PyCFunction) formatter_parser,
10487 METH_O, PyDoc_STR("parse the argument as a format string")},
10488 {NULL, NULL}
10489};
10490
10491static struct PyModuleDef _string_module = {
10492 PyModuleDef_HEAD_INIT,
10493 "_string",
10494 PyDoc_STR("string helper module"),
10495 0,
10496 _string_methods,
10497 NULL,
10498 NULL,
10499 NULL,
10500 NULL
10501};
10502
10503PyMODINIT_FUNC
10504PyInit__string(void)
10505{
10506 return PyModule_Create(&_string_module);
10507}
10508
10509
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010510#ifdef __cplusplus
10511}
10512#endif