blob: d6cc8b5a24d45b26c0f27d21c3a3aeb613386a23 [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"
Guido van Rossumdaa251c2007-10-25 23:47:33 +000044#include "bytes_methods.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000045
Guido van Rossumd57fd912000-03-10 22:53:23 +000046#include "unicodeobject.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000047#include "ucnhash.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000048
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000049#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000050#include <windows.h>
51#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000052
Guido van Rossumd57fd912000-03-10 22:53:23 +000053/* Limit for the Unicode object free list */
54
Christian Heimes2202f872008-02-06 14:31:34 +000055#define PyUnicode_MAXFREELIST 1024
Guido van Rossumd57fd912000-03-10 22:53:23 +000056
57/* Limit for the Unicode object free list stay alive optimization.
58
59 The implementation will keep allocated Unicode memory intact for
60 all objects on the free list having a size less than this
Tim Petersced69f82003-09-16 20:30:58 +000061 limit. This reduces malloc() overhead for small Unicode objects.
Guido van Rossumd57fd912000-03-10 22:53:23 +000062
Christian Heimes2202f872008-02-06 14:31:34 +000063 At worst this will result in PyUnicode_MAXFREELIST *
Guido van Rossumfd4b9572000-04-10 13:51:10 +000064 (sizeof(PyUnicodeObject) + KEEPALIVE_SIZE_LIMIT +
Guido van Rossumd57fd912000-03-10 22:53:23 +000065 malloc()-overhead) bytes of unused garbage.
66
67 Setting the limit to 0 effectively turns the feature off.
68
Guido van Rossumfd4b9572000-04-10 13:51:10 +000069 Note: This is an experimental feature ! If you get core dumps when
70 using Unicode objects, turn this feature off.
Guido van Rossumd57fd912000-03-10 22:53:23 +000071
72*/
73
Guido van Rossumfd4b9572000-04-10 13:51:10 +000074#define KEEPALIVE_SIZE_LIMIT 9
Guido van Rossumd57fd912000-03-10 22:53:23 +000075
76/* Endianness switches; defaults to little endian */
77
78#ifdef WORDS_BIGENDIAN
79# define BYTEORDER_IS_BIG_ENDIAN
80#else
81# define BYTEORDER_IS_LITTLE_ENDIAN
82#endif
83
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000084/* --- Globals ------------------------------------------------------------
85
86 The globals are initialized by the _PyUnicode_Init() API and should
87 not be used before calling that API.
88
89*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000090
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000091
92#ifdef __cplusplus
93extern "C" {
94#endif
95
Walter Dörwald16807132007-05-25 13:52:07 +000096/* This dictionary holds all interned unicode strings. Note that references
97 to strings in this dictionary are *not* counted in the string's ob_refcnt.
98 When the interned string reaches a refcnt of 0 the string deallocation
99 function will delete the reference from this dictionary.
100
101 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000102 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000103*/
104static PyObject *interned;
105
Guido van Rossumd57fd912000-03-10 22:53:23 +0000106/* Free list for Unicode objects */
Christian Heimes2202f872008-02-06 14:31:34 +0000107static PyUnicodeObject *free_list;
108static int numfree;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000109
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000110/* The empty Unicode object is shared to improve performance. */
111static PyUnicodeObject *unicode_empty;
112
113/* Single character Unicode strings in the Latin-1 range are being
114 shared as well. */
115static PyUnicodeObject *unicode_latin1[256];
116
Christian Heimes190d79e2008-01-30 11:58:22 +0000117/* Fast detection of the most frequent whitespace characters */
118const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000119 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000120/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000121/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000122/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000123/* case 0x000C: * FORM FEED */
124/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000125 0, 1, 1, 1, 1, 1, 0, 0,
126 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000127/* case 0x001C: * FILE SEPARATOR */
128/* case 0x001D: * GROUP SEPARATOR */
129/* case 0x001E: * RECORD SEPARATOR */
130/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000131 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000132/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000133 1, 0, 0, 0, 0, 0, 0, 0,
134 0, 0, 0, 0, 0, 0, 0, 0,
135 0, 0, 0, 0, 0, 0, 0, 0,
136 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000137
Benjamin Peterson14339b62009-01-31 16:36:08 +0000138 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,
143 0, 0, 0, 0, 0, 0, 0, 0,
144 0, 0, 0, 0, 0, 0, 0, 0,
145 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000146};
147
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000148static PyObject *unicode_encode_call_errorhandler(const char *errors,
149 PyObject **errorHandler,const char *encoding, const char *reason,
150 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
151 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
152
Victor Stinner31be90b2010-04-22 19:38:16 +0000153static void raise_encode_exception(PyObject **exceptionObject,
154 const char *encoding,
155 const Py_UNICODE *unicode, Py_ssize_t size,
156 Py_ssize_t startpos, Py_ssize_t endpos,
157 const char *reason);
158
Christian Heimes190d79e2008-01-30 11:58:22 +0000159/* Same for linebreaks */
160static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000161 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000162/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000163/* 0x000B, * LINE TABULATION */
164/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000165/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000166 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000167 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000168/* 0x001C, * FILE SEPARATOR */
169/* 0x001D, * GROUP SEPARATOR */
170/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000171 0, 0, 0, 0, 1, 1, 1, 0,
172 0, 0, 0, 0, 0, 0, 0, 0,
173 0, 0, 0, 0, 0, 0, 0, 0,
174 0, 0, 0, 0, 0, 0, 0, 0,
175 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000176
Benjamin Peterson14339b62009-01-31 16:36:08 +0000177 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,
182 0, 0, 0, 0, 0, 0, 0, 0,
183 0, 0, 0, 0, 0, 0, 0, 0,
184 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000185};
186
187
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000188Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000189PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000190{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000191#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000192 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000193#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000194 /* This is actually an illegal character, so it should
195 not be passed to unichr. */
196 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000197#endif
198}
199
Thomas Wouters477c8d52006-05-27 19:21:47 +0000200/* --- Bloom Filters ----------------------------------------------------- */
201
202/* stuff to implement simple "bloom filters" for Unicode characters.
203 to keep things simple, we use a single bitmask, using the least 5
204 bits from each unicode characters as the bit index. */
205
206/* the linebreak mask is set up by Unicode_Init below */
207
Antoine Pitrouf068f942010-01-13 14:19:12 +0000208#if LONG_BIT >= 128
209#define BLOOM_WIDTH 128
210#elif LONG_BIT >= 64
211#define BLOOM_WIDTH 64
212#elif LONG_BIT >= 32
213#define BLOOM_WIDTH 32
214#else
215#error "LONG_BIT is smaller than 32"
216#endif
217
Thomas Wouters477c8d52006-05-27 19:21:47 +0000218#define BLOOM_MASK unsigned long
219
220static BLOOM_MASK bloom_linebreak;
221
Antoine Pitrouf068f942010-01-13 14:19:12 +0000222#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
223#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000224
Benjamin Peterson29060642009-01-31 22:14:21 +0000225#define BLOOM_LINEBREAK(ch) \
226 ((ch) < 128U ? ascii_linebreak[(ch)] : \
227 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000228
229Py_LOCAL_INLINE(BLOOM_MASK) make_bloom_mask(Py_UNICODE* ptr, Py_ssize_t len)
230{
231 /* calculate simple bloom-style bitmask for a given unicode string */
232
Antoine Pitrouf068f942010-01-13 14:19:12 +0000233 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000234 Py_ssize_t i;
235
236 mask = 0;
237 for (i = 0; i < len; i++)
Antoine Pitrouf2c54842010-01-13 08:07:53 +0000238 BLOOM_ADD(mask, ptr[i]);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000239
240 return mask;
241}
242
243Py_LOCAL_INLINE(int) unicode_member(Py_UNICODE chr, Py_UNICODE* set, Py_ssize_t setlen)
244{
245 Py_ssize_t i;
246
247 for (i = 0; i < setlen; i++)
248 if (set[i] == chr)
249 return 1;
250
251 return 0;
252}
253
Benjamin Peterson29060642009-01-31 22:14:21 +0000254#define BLOOM_MEMBER(mask, chr, set, setlen) \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000255 BLOOM(mask, chr) && unicode_member(chr, set, setlen)
256
Guido van Rossumd57fd912000-03-10 22:53:23 +0000257/* --- Unicode Object ----------------------------------------------------- */
258
259static
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000260int unicode_resize(register PyUnicodeObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +0000261 Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000262{
263 void *oldstr;
Tim Petersced69f82003-09-16 20:30:58 +0000264
Guido van Rossumfd4b9572000-04-10 13:51:10 +0000265 /* Shortcut if there's nothing much to do. */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000266 if (unicode->length == length)
Benjamin Peterson29060642009-01-31 22:14:21 +0000267 goto reset;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000268
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000269 /* Resizing shared object (unicode_empty or single character
270 objects) in-place is not allowed. Use PyUnicode_Resize()
271 instead ! */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000272
Benjamin Peterson14339b62009-01-31 16:36:08 +0000273 if (unicode == unicode_empty ||
Benjamin Peterson29060642009-01-31 22:14:21 +0000274 (unicode->length == 1 &&
275 unicode->str[0] < 256U &&
276 unicode_latin1[unicode->str[0]] == unicode)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +0000277 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson142957c2008-07-04 19:55:29 +0000278 "can't resize shared str objects");
Guido van Rossumd57fd912000-03-10 22:53:23 +0000279 return -1;
280 }
281
Thomas Wouters477c8d52006-05-27 19:21:47 +0000282 /* We allocate one more byte to make sure the string is Ux0000 terminated.
283 The overallocation is also used by fastsearch, which assumes that it's
284 safe to look at str[length] (without making any assumptions about what
285 it contains). */
286
Guido van Rossumd57fd912000-03-10 22:53:23 +0000287 oldstr = unicode->str;
Christian Heimesb186d002008-03-18 15:15:01 +0000288 unicode->str = PyObject_REALLOC(unicode->str,
Benjamin Peterson29060642009-01-31 22:14:21 +0000289 sizeof(Py_UNICODE) * (length + 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000290 if (!unicode->str) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000291 unicode->str = (Py_UNICODE *)oldstr;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000292 PyErr_NoMemory();
293 return -1;
294 }
295 unicode->str[length] = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000296 unicode->length = length;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000297
Benjamin Peterson29060642009-01-31 22:14:21 +0000298 reset:
Guido van Rossumd57fd912000-03-10 22:53:23 +0000299 /* Reset the object caches */
Marc-André Lemburgbff879c2000-08-03 18:46:08 +0000300 if (unicode->defenc) {
Georg Brandl8ee604b2010-07-29 14:23:06 +0000301 Py_CLEAR(unicode->defenc);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000302 }
303 unicode->hash = -1;
Tim Petersced69f82003-09-16 20:30:58 +0000304
Guido van Rossumd57fd912000-03-10 22:53:23 +0000305 return 0;
306}
307
308/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000309 Ux0000 terminated; some code (e.g. new_identifier)
310 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000311
312 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000313 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000314
315*/
316
317static
Martin v. Löwis18e16552006-02-15 17:27:45 +0000318PyUnicodeObject *_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000319{
320 register PyUnicodeObject *unicode;
321
Thomas Wouters477c8d52006-05-27 19:21:47 +0000322 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000323 if (length == 0 && unicode_empty != NULL) {
324 Py_INCREF(unicode_empty);
325 return unicode_empty;
326 }
327
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000328 /* Ensure we won't overflow the size. */
329 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
330 return (PyUnicodeObject *)PyErr_NoMemory();
331 }
332
Guido van Rossumd57fd912000-03-10 22:53:23 +0000333 /* Unicode freelist & memory allocation */
Christian Heimes2202f872008-02-06 14:31:34 +0000334 if (free_list) {
335 unicode = free_list;
336 free_list = *(PyUnicodeObject **)unicode;
337 numfree--;
Benjamin Peterson29060642009-01-31 22:14:21 +0000338 if (unicode->str) {
339 /* Keep-Alive optimization: we only upsize the buffer,
340 never downsize it. */
341 if ((unicode->length < length) &&
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +0000342 unicode_resize(unicode, length) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000343 PyObject_DEL(unicode->str);
344 unicode->str = NULL;
345 }
Benjamin Peterson14339b62009-01-31 16:36:08 +0000346 }
Guido van Rossumad98db12001-06-14 17:52:02 +0000347 else {
Benjamin Peterson29060642009-01-31 22:14:21 +0000348 size_t new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
349 unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
Guido van Rossumad98db12001-06-14 17:52:02 +0000350 }
351 PyObject_INIT(unicode, &PyUnicode_Type);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000352 }
353 else {
Benjamin Peterson29060642009-01-31 22:14:21 +0000354 size_t new_size;
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000355 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000356 if (unicode == NULL)
357 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +0000358 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
359 unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000360 }
361
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000362 if (!unicode->str) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000363 PyErr_NoMemory();
364 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000365 }
Jeremy Hyltond8082792003-09-16 19:41:39 +0000366 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000367 * the caller fails before initializing str -- unicode_resize()
368 * reads str[0], and the Keep-Alive optimization can keep memory
369 * allocated for str alive across a call to unicode_dealloc(unicode).
370 * We don't want unicode_resize to read uninitialized memory in
371 * that case.
372 */
Jeremy Hyltond8082792003-09-16 19:41:39 +0000373 unicode->str[0] = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000374 unicode->str[length] = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000375 unicode->length = length;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000376 unicode->hash = -1;
Walter Dörwald16807132007-05-25 13:52:07 +0000377 unicode->state = 0;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +0000378 unicode->defenc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000379 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000380
Benjamin Peterson29060642009-01-31 22:14:21 +0000381 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000382 /* XXX UNREF/NEWREF interface should be more symmetrical */
383 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000384 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000385 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000386 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000387}
388
389static
Guido van Rossum9475a232001-10-05 20:51:39 +0000390void unicode_dealloc(register PyUnicodeObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000391{
Walter Dörwald16807132007-05-25 13:52:07 +0000392 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000393 case SSTATE_NOT_INTERNED:
394 break;
Walter Dörwald16807132007-05-25 13:52:07 +0000395
Benjamin Peterson29060642009-01-31 22:14:21 +0000396 case SSTATE_INTERNED_MORTAL:
397 /* revive dead object temporarily for DelItem */
398 Py_REFCNT(unicode) = 3;
399 if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
400 Py_FatalError(
401 "deletion of interned string failed");
402 break;
Walter Dörwald16807132007-05-25 13:52:07 +0000403
Benjamin Peterson29060642009-01-31 22:14:21 +0000404 case SSTATE_INTERNED_IMMORTAL:
405 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +0000406
Benjamin Peterson29060642009-01-31 22:14:21 +0000407 default:
408 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +0000409 }
410
Guido van Rossum604ddf82001-12-06 20:03:56 +0000411 if (PyUnicode_CheckExact(unicode) &&
Benjamin Peterson29060642009-01-31 22:14:21 +0000412 numfree < PyUnicode_MAXFREELIST) {
Guido van Rossumfd4b9572000-04-10 13:51:10 +0000413 /* Keep-Alive optimization */
Benjamin Peterson29060642009-01-31 22:14:21 +0000414 if (unicode->length >= KEEPALIVE_SIZE_LIMIT) {
415 PyObject_DEL(unicode->str);
416 unicode->str = NULL;
417 unicode->length = 0;
418 }
419 if (unicode->defenc) {
Georg Brandl8ee604b2010-07-29 14:23:06 +0000420 Py_CLEAR(unicode->defenc);
Benjamin Peterson29060642009-01-31 22:14:21 +0000421 }
422 /* Add to free list */
Christian Heimes2202f872008-02-06 14:31:34 +0000423 *(PyUnicodeObject **)unicode = free_list;
424 free_list = unicode;
425 numfree++;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000426 }
427 else {
Benjamin Peterson29060642009-01-31 22:14:21 +0000428 PyObject_DEL(unicode->str);
429 Py_XDECREF(unicode->defenc);
430 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000431 }
432}
433
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000434static
435int _PyUnicode_Resize(PyUnicodeObject **unicode, Py_ssize_t length)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000436{
437 register PyUnicodeObject *v;
438
439 /* Argument checks */
440 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000441 PyErr_BadInternalCall();
442 return -1;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000443 }
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000444 v = *unicode;
Christian Heimes90aa7642007-12-19 02:45:37 +0000445 if (v == NULL || !PyUnicode_Check(v) || Py_REFCNT(v) != 1 || length < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000446 PyErr_BadInternalCall();
447 return -1;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000448 }
449
450 /* Resizing unicode_empty and single character objects is not
451 possible since these are being shared. We simply return a fresh
452 copy with the same Unicode content. */
Tim Petersced69f82003-09-16 20:30:58 +0000453 if (v->length != length &&
Benjamin Peterson29060642009-01-31 22:14:21 +0000454 (v == unicode_empty || v->length == 1)) {
455 PyUnicodeObject *w = _PyUnicode_New(length);
456 if (w == NULL)
457 return -1;
458 Py_UNICODE_COPY(w->str, v->str,
459 length < v->length ? length : v->length);
460 Py_DECREF(*unicode);
461 *unicode = w;
462 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000463 }
464
465 /* Note that we don't have to modify *unicode for unshared Unicode
466 objects, since we can modify them in-place. */
467 return unicode_resize(v, length);
468}
469
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000470int PyUnicode_Resize(PyObject **unicode, Py_ssize_t length)
471{
472 return _PyUnicode_Resize((PyUnicodeObject **)unicode, length);
473}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000474
Guido van Rossumd57fd912000-03-10 22:53:23 +0000475PyObject *PyUnicode_FromUnicode(const Py_UNICODE *u,
Benjamin Peterson29060642009-01-31 22:14:21 +0000476 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000477{
478 PyUnicodeObject *unicode;
479
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000480 /* If the Unicode data is known at construction time, we can apply
481 some optimizations which share commonly used objects. */
482 if (u != NULL) {
483
Benjamin Peterson29060642009-01-31 22:14:21 +0000484 /* Optimization for empty strings */
485 if (size == 0 && unicode_empty != NULL) {
486 Py_INCREF(unicode_empty);
487 return (PyObject *)unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000488 }
Benjamin Peterson29060642009-01-31 22:14:21 +0000489
490 /* Single character Unicode objects in the Latin-1 range are
491 shared when using this constructor */
492 if (size == 1 && *u < 256) {
493 unicode = unicode_latin1[*u];
494 if (!unicode) {
495 unicode = _PyUnicode_New(1);
496 if (!unicode)
497 return NULL;
498 unicode->str[0] = *u;
499 unicode_latin1[*u] = unicode;
500 }
501 Py_INCREF(unicode);
502 return (PyObject *)unicode;
503 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000504 }
Tim Petersced69f82003-09-16 20:30:58 +0000505
Guido van Rossumd57fd912000-03-10 22:53:23 +0000506 unicode = _PyUnicode_New(size);
507 if (!unicode)
508 return NULL;
509
510 /* Copy the Unicode data into the new object */
511 if (u != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +0000512 Py_UNICODE_COPY(unicode->str, u, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000513
514 return (PyObject *)unicode;
515}
516
Walter Dörwaldd2034312007-05-18 16:29:38 +0000517PyObject *PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000518{
519 PyUnicodeObject *unicode;
Christian Heimes33fe8092008-04-13 13:53:33 +0000520
Benjamin Peterson14339b62009-01-31 16:36:08 +0000521 if (size < 0) {
522 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +0000523 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +0000524 return NULL;
525 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000526
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000527 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +0000528 some optimizations which share commonly used objects.
529 Also, this means the input must be UTF-8, so fall back to the
530 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000531 if (u != NULL) {
532
Benjamin Peterson29060642009-01-31 22:14:21 +0000533 /* Optimization for empty strings */
534 if (size == 0 && unicode_empty != NULL) {
535 Py_INCREF(unicode_empty);
536 return (PyObject *)unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000537 }
Benjamin Peterson29060642009-01-31 22:14:21 +0000538
539 /* Single characters are shared when using this constructor.
540 Restrict to ASCII, since the input must be UTF-8. */
541 if (size == 1 && Py_CHARMASK(*u) < 128) {
542 unicode = unicode_latin1[Py_CHARMASK(*u)];
543 if (!unicode) {
544 unicode = _PyUnicode_New(1);
545 if (!unicode)
546 return NULL;
547 unicode->str[0] = Py_CHARMASK(*u);
548 unicode_latin1[Py_CHARMASK(*u)] = unicode;
549 }
550 Py_INCREF(unicode);
551 return (PyObject *)unicode;
552 }
Martin v. Löwis9c121062007-08-05 20:26:11 +0000553
554 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000555 }
556
Walter Dörwald55507312007-05-18 13:12:10 +0000557 unicode = _PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000558 if (!unicode)
559 return NULL;
560
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000561 return (PyObject *)unicode;
562}
563
Walter Dörwaldd2034312007-05-18 16:29:38 +0000564PyObject *PyUnicode_FromString(const char *u)
565{
566 size_t size = strlen(u);
567 if (size > PY_SSIZE_T_MAX) {
568 PyErr_SetString(PyExc_OverflowError, "input too long");
569 return NULL;
570 }
571
572 return PyUnicode_FromStringAndSize(u, size);
573}
574
Guido van Rossumd57fd912000-03-10 22:53:23 +0000575#ifdef HAVE_WCHAR_H
576
Mark Dickinson081dfee2009-03-18 14:47:41 +0000577#if (Py_UNICODE_SIZE == 2) && defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4)
578# define CONVERT_WCHAR_TO_SURROGATES
579#endif
580
581#ifdef CONVERT_WCHAR_TO_SURROGATES
582
583/* Here sizeof(wchar_t) is 4 but Py_UNICODE_SIZE == 2, so we need
584 to convert from UTF32 to UTF16. */
585
586PyObject *PyUnicode_FromWideChar(register const wchar_t *w,
587 Py_ssize_t size)
588{
589 PyUnicodeObject *unicode;
590 register Py_ssize_t i;
591 Py_ssize_t alloc;
592 const wchar_t *orig_w;
593
594 if (w == NULL) {
595 if (size == 0)
596 return PyUnicode_FromStringAndSize(NULL, 0);
597 PyErr_BadInternalCall();
598 return NULL;
599 }
600
601 if (size == -1) {
602 size = wcslen(w);
603 }
604
605 alloc = size;
606 orig_w = w;
607 for (i = size; i > 0; i--) {
608 if (*w > 0xFFFF)
609 alloc++;
610 w++;
611 }
612 w = orig_w;
613 unicode = _PyUnicode_New(alloc);
614 if (!unicode)
615 return NULL;
616
617 /* Copy the wchar_t data into the new object */
618 {
619 register Py_UNICODE *u;
620 u = PyUnicode_AS_UNICODE(unicode);
621 for (i = size; i > 0; i--) {
622 if (*w > 0xFFFF) {
623 wchar_t ordinal = *w++;
624 ordinal -= 0x10000;
625 *u++ = 0xD800 | (ordinal >> 10);
626 *u++ = 0xDC00 | (ordinal & 0x3FF);
627 }
628 else
629 *u++ = *w++;
630 }
631 }
632 return (PyObject *)unicode;
633}
634
635#else
636
Guido van Rossumd57fd912000-03-10 22:53:23 +0000637PyObject *PyUnicode_FromWideChar(register const wchar_t *w,
Benjamin Peterson29060642009-01-31 22:14:21 +0000638 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000639{
640 PyUnicodeObject *unicode;
641
642 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +0000643 if (size == 0)
644 return PyUnicode_FromStringAndSize(NULL, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +0000645 PyErr_BadInternalCall();
646 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000647 }
648
Martin v. Löwis790465f2008-04-05 20:41:37 +0000649 if (size == -1) {
650 size = wcslen(w);
651 }
652
Guido van Rossumd57fd912000-03-10 22:53:23 +0000653 unicode = _PyUnicode_New(size);
654 if (!unicode)
655 return NULL;
656
657 /* Copy the wchar_t data into the new object */
Daniel Stutzbach8515eae2010-08-24 21:57:33 +0000658#if Py_UNICODE_SIZE == SIZEOF_WCHAR_T
Guido van Rossumd57fd912000-03-10 22:53:23 +0000659 memcpy(unicode->str, w, size * sizeof(wchar_t));
Tim Petersced69f82003-09-16 20:30:58 +0000660#else
Guido van Rossumd57fd912000-03-10 22:53:23 +0000661 {
Benjamin Peterson29060642009-01-31 22:14:21 +0000662 register Py_UNICODE *u;
663 register Py_ssize_t i;
664 u = PyUnicode_AS_UNICODE(unicode);
665 for (i = size; i > 0; i--)
666 *u++ = *w++;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000667 }
668#endif
669
670 return (PyObject *)unicode;
671}
672
Mark Dickinson081dfee2009-03-18 14:47:41 +0000673#endif /* CONVERT_WCHAR_TO_SURROGATES */
674
675#undef CONVERT_WCHAR_TO_SURROGATES
676
Walter Dörwald346737f2007-05-31 10:44:43 +0000677static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000678makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
679 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +0000680{
Benjamin Peterson14339b62009-01-31 16:36:08 +0000681 *fmt++ = '%';
682 if (width) {
683 if (zeropad)
684 *fmt++ = '0';
685 fmt += sprintf(fmt, "%d", width);
686 }
687 if (precision)
688 fmt += sprintf(fmt, ".%d", precision);
689 if (longflag)
690 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000691 else if (longlongflag) {
692 /* longlongflag should only ever be nonzero on machines with
693 HAVE_LONG_LONG defined */
694#ifdef HAVE_LONG_LONG
695 char *f = PY_FORMAT_LONG_LONG;
696 while (*f)
697 *fmt++ = *f++;
698#else
699 /* we shouldn't ever get here */
700 assert(0);
701 *fmt++ = 'l';
702#endif
703 }
Benjamin Peterson14339b62009-01-31 16:36:08 +0000704 else if (size_tflag) {
705 char *f = PY_FORMAT_SIZE_T;
706 while (*f)
707 *fmt++ = *f++;
708 }
709 *fmt++ = c;
710 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +0000711}
712
Walter Dörwaldd2034312007-05-18 16:29:38 +0000713#define appendstring(string) {for (copy = string;*copy;) *s++ = *copy++;}
714
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000715/* size of fixed-size buffer for formatting single arguments */
716#define ITEM_BUFFER_LEN 21
717/* maximum number of characters required for output of %ld. 21 characters
718 allows for 64-bit integers (in decimal) and an optional sign. */
719#define MAX_LONG_CHARS 21
720/* maximum number of characters required for output of %lld.
721 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
722 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
723#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
724
Walter Dörwaldd2034312007-05-18 16:29:38 +0000725PyObject *
726PyUnicode_FromFormatV(const char *format, va_list vargs)
727{
Benjamin Peterson14339b62009-01-31 16:36:08 +0000728 va_list count;
729 Py_ssize_t callcount = 0;
730 PyObject **callresults = NULL;
731 PyObject **callresult = NULL;
732 Py_ssize_t n = 0;
733 int width = 0;
734 int precision = 0;
735 int zeropad;
736 const char* f;
737 Py_UNICODE *s;
738 PyObject *string;
739 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000740 char buffer[ITEM_BUFFER_LEN+1];
Benjamin Peterson14339b62009-01-31 16:36:08 +0000741 /* use abuffer instead of buffer, if we need more space
742 * (which can happen if there's a format specifier with width). */
743 char *abuffer = NULL;
744 char *realbuffer;
745 Py_ssize_t abuffersize = 0;
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000746 char fmt[61]; /* should be enough for %0width.precisionlld */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000747 const char *copy;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000748
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000749 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000750 /* step 1: count the number of %S/%R/%A/%s format specifications
751 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
752 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
753 * result in an array) */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000754 for (f = format; *f; f++) {
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000755 if (*f == '%') {
756 if (*(f+1)=='%')
757 continue;
758 if (*(f+1)=='S' || *(f+1)=='R' || *(f+1)=='A')
759 ++callcount;
David Malcolm96960882010-11-05 17:23:41 +0000760 while (Py_ISDIGIT((unsigned)*f))
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000761 width = (width*10) + *f++ - '0';
David Malcolm96960882010-11-05 17:23:41 +0000762 while (*++f && *f != '%' && !Py_ISALPHA((unsigned)*f))
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000763 ;
764 if (*f == 's')
765 ++callcount;
766 }
Benjamin Peterson9be0b2e2010-09-12 03:40:54 +0000767 else if (128 <= (unsigned char)*f) {
768 PyErr_Format(PyExc_ValueError,
769 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
Victor Stinner4c7db312010-09-12 07:51:18 +0000770 "string, got a non-ASCII byte: 0x%02x",
Benjamin Peterson9be0b2e2010-09-12 03:40:54 +0000771 (unsigned char)*f);
Benjamin Petersond4ac96a2010-09-12 16:40:53 +0000772 return NULL;
Benjamin Peterson9be0b2e2010-09-12 03:40:54 +0000773 }
Benjamin Peterson14339b62009-01-31 16:36:08 +0000774 }
775 /* step 2: allocate memory for the results of
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000776 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000777 if (callcount) {
778 callresults = PyObject_Malloc(sizeof(PyObject *)*callcount);
779 if (!callresults) {
780 PyErr_NoMemory();
781 return NULL;
782 }
783 callresult = callresults;
784 }
785 /* step 3: figure out how large a buffer we need */
786 for (f = format; *f; f++) {
787 if (*f == '%') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000788#ifdef HAVE_LONG_LONG
789 int longlongflag = 0;
790#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +0000791 const char* p = f;
792 width = 0;
David Malcolm96960882010-11-05 17:23:41 +0000793 while (Py_ISDIGIT((unsigned)*f))
Benjamin Peterson14339b62009-01-31 16:36:08 +0000794 width = (width*10) + *f++ - '0';
David Malcolm96960882010-11-05 17:23:41 +0000795 while (*++f && *f != '%' && !Py_ISALPHA((unsigned)*f))
Benjamin Peterson14339b62009-01-31 16:36:08 +0000796 ;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000797
Benjamin Peterson14339b62009-01-31 16:36:08 +0000798 /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
799 * they don't affect the amount of space we reserve.
800 */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000801 if (*f == 'l') {
802 if (f[1] == 'd' || f[1] == 'u') {
803 ++f;
804 }
805#ifdef HAVE_LONG_LONG
806 else if (f[1] == 'l' &&
807 (f[2] == 'd' || f[2] == 'u')) {
808 longlongflag = 1;
809 f += 2;
810 }
811#endif
812 }
813 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000814 ++f;
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000815 }
Walter Dörwaldd2034312007-05-18 16:29:38 +0000816
Benjamin Peterson14339b62009-01-31 16:36:08 +0000817 switch (*f) {
818 case 'c':
819 (void)va_arg(count, int);
820 /* fall through... */
821 case '%':
822 n++;
823 break;
824 case 'd': case 'u': case 'i': case 'x':
825 (void) va_arg(count, int);
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000826#ifdef HAVE_LONG_LONG
827 if (longlongflag) {
828 if (width < MAX_LONG_LONG_CHARS)
829 width = MAX_LONG_LONG_CHARS;
830 }
831 else
832#endif
833 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
834 including sign. Decimal takes the most space. This
835 isn't enough for octal. If a width is specified we
836 need more (which we allocate later). */
837 if (width < MAX_LONG_CHARS)
838 width = MAX_LONG_CHARS;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000839 n += width;
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000840 /* XXX should allow for large precision here too. */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000841 if (abuffersize < width)
842 abuffersize = width;
843 break;
844 case 's':
845 {
846 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +0000847 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000848 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
849 if (!str)
850 goto fail;
851 n += PyUnicode_GET_SIZE(str);
852 /* Remember the str and switch to the next slot */
853 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000854 break;
855 }
856 case 'U':
857 {
858 PyObject *obj = va_arg(count, PyObject *);
859 assert(obj && PyUnicode_Check(obj));
860 n += PyUnicode_GET_SIZE(obj);
861 break;
862 }
863 case 'V':
864 {
865 PyObject *obj = va_arg(count, PyObject *);
866 const char *str = va_arg(count, const char *);
867 assert(obj || str);
868 assert(!obj || PyUnicode_Check(obj));
869 if (obj)
870 n += PyUnicode_GET_SIZE(obj);
871 else
872 n += strlen(str);
873 break;
874 }
875 case 'S':
876 {
877 PyObject *obj = va_arg(count, PyObject *);
878 PyObject *str;
879 assert(obj);
880 str = PyObject_Str(obj);
881 if (!str)
882 goto fail;
883 n += PyUnicode_GET_SIZE(str);
884 /* Remember the str and switch to the next slot */
885 *callresult++ = str;
886 break;
887 }
888 case 'R':
889 {
890 PyObject *obj = va_arg(count, PyObject *);
891 PyObject *repr;
892 assert(obj);
893 repr = PyObject_Repr(obj);
894 if (!repr)
895 goto fail;
896 n += PyUnicode_GET_SIZE(repr);
897 /* Remember the repr and switch to the next slot */
898 *callresult++ = repr;
899 break;
900 }
901 case 'A':
902 {
903 PyObject *obj = va_arg(count, PyObject *);
904 PyObject *ascii;
905 assert(obj);
906 ascii = PyObject_ASCII(obj);
907 if (!ascii)
908 goto fail;
909 n += PyUnicode_GET_SIZE(ascii);
910 /* Remember the repr and switch to the next slot */
911 *callresult++ = ascii;
912 break;
913 }
914 case 'p':
915 (void) va_arg(count, int);
916 /* maximum 64-bit pointer representation:
917 * 0xffffffffffffffff
918 * so 19 characters is enough.
919 * XXX I count 18 -- what's the extra for?
920 */
921 n += 19;
922 break;
923 default:
924 /* if we stumble upon an unknown
925 formatting code, copy the rest of
926 the format string to the output
927 string. (we cannot just skip the
928 code, since there's no way to know
929 what's in the argument list) */
930 n += strlen(p);
931 goto expand;
932 }
933 } else
934 n++;
935 }
Benjamin Peterson29060642009-01-31 22:14:21 +0000936 expand:
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000937 if (abuffersize > ITEM_BUFFER_LEN) {
938 /* add 1 for sprintf's trailing null byte */
939 abuffer = PyObject_Malloc(abuffersize + 1);
Benjamin Peterson14339b62009-01-31 16:36:08 +0000940 if (!abuffer) {
941 PyErr_NoMemory();
942 goto fail;
943 }
944 realbuffer = abuffer;
945 }
946 else
947 realbuffer = buffer;
948 /* step 4: fill the buffer */
949 /* Since we've analyzed how much space we need for the worst case,
950 we don't have to resize the string.
951 There can be no errors beyond this point. */
952 string = PyUnicode_FromUnicode(NULL, n);
953 if (!string)
954 goto fail;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000955
Benjamin Peterson14339b62009-01-31 16:36:08 +0000956 s = PyUnicode_AS_UNICODE(string);
957 callresult = callresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000958
Benjamin Peterson14339b62009-01-31 16:36:08 +0000959 for (f = format; *f; f++) {
960 if (*f == '%') {
961 const char* p = f++;
962 int longflag = 0;
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000963 int longlongflag = 0;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000964 int size_tflag = 0;
965 zeropad = (*f == '0');
966 /* parse the width.precision part */
967 width = 0;
David Malcolm96960882010-11-05 17:23:41 +0000968 while (Py_ISDIGIT((unsigned)*f))
Benjamin Peterson14339b62009-01-31 16:36:08 +0000969 width = (width*10) + *f++ - '0';
970 precision = 0;
971 if (*f == '.') {
972 f++;
David Malcolm96960882010-11-05 17:23:41 +0000973 while (Py_ISDIGIT((unsigned)*f))
Benjamin Peterson14339b62009-01-31 16:36:08 +0000974 precision = (precision*10) + *f++ - '0';
975 }
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000976 /* Handle %ld, %lu, %lld and %llu. */
977 if (*f == 'l') {
978 if (f[1] == 'd' || f[1] == 'u') {
979 longflag = 1;
980 ++f;
981 }
982#ifdef HAVE_LONG_LONG
983 else if (f[1] == 'l' &&
984 (f[2] == 'd' || f[2] == 'u')) {
985 longlongflag = 1;
986 f += 2;
987 }
988#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +0000989 }
990 /* handle the size_t flag. */
991 if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
992 size_tflag = 1;
993 ++f;
994 }
Walter Dörwaldd2034312007-05-18 16:29:38 +0000995
Benjamin Peterson14339b62009-01-31 16:36:08 +0000996 switch (*f) {
997 case 'c':
998 *s++ = va_arg(vargs, int);
999 break;
1000 case 'd':
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001001 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
1002 width, precision, 'd');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001003 if (longflag)
1004 sprintf(realbuffer, fmt, va_arg(vargs, long));
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001005#ifdef HAVE_LONG_LONG
1006 else if (longlongflag)
1007 sprintf(realbuffer, fmt, va_arg(vargs, PY_LONG_LONG));
1008#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001009 else if (size_tflag)
1010 sprintf(realbuffer, fmt, va_arg(vargs, Py_ssize_t));
1011 else
1012 sprintf(realbuffer, fmt, va_arg(vargs, int));
1013 appendstring(realbuffer);
1014 break;
1015 case 'u':
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001016 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
1017 width, precision, 'u');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001018 if (longflag)
1019 sprintf(realbuffer, fmt, va_arg(vargs, unsigned long));
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001020#ifdef HAVE_LONG_LONG
1021 else if (longlongflag)
1022 sprintf(realbuffer, fmt, va_arg(vargs,
1023 unsigned PY_LONG_LONG));
1024#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001025 else if (size_tflag)
1026 sprintf(realbuffer, fmt, va_arg(vargs, size_t));
1027 else
1028 sprintf(realbuffer, fmt, va_arg(vargs, unsigned int));
1029 appendstring(realbuffer);
1030 break;
1031 case 'i':
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001032 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'i');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001033 sprintf(realbuffer, fmt, va_arg(vargs, int));
1034 appendstring(realbuffer);
1035 break;
1036 case 'x':
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001037 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001038 sprintf(realbuffer, fmt, va_arg(vargs, int));
1039 appendstring(realbuffer);
1040 break;
1041 case 's':
1042 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001043 /* unused, since we already have the result */
1044 (void) va_arg(vargs, char *);
1045 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(*callresult),
1046 PyUnicode_GET_SIZE(*callresult));
1047 s += PyUnicode_GET_SIZE(*callresult);
1048 /* We're done with the unicode()/repr() => forget it */
1049 Py_DECREF(*callresult);
1050 /* switch to next unicode()/repr() result */
1051 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001052 break;
1053 }
1054 case 'U':
1055 {
1056 PyObject *obj = va_arg(vargs, PyObject *);
1057 Py_ssize_t size = PyUnicode_GET_SIZE(obj);
1058 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size);
1059 s += size;
1060 break;
1061 }
1062 case 'V':
1063 {
1064 PyObject *obj = va_arg(vargs, PyObject *);
1065 const char *str = va_arg(vargs, const char *);
1066 if (obj) {
1067 Py_ssize_t size = PyUnicode_GET_SIZE(obj);
1068 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size);
1069 s += size;
1070 } else {
1071 appendstring(str);
1072 }
1073 break;
1074 }
1075 case 'S':
1076 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00001077 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00001078 {
1079 Py_UNICODE *ucopy;
1080 Py_ssize_t usize;
1081 Py_ssize_t upos;
1082 /* unused, since we already have the result */
1083 (void) va_arg(vargs, PyObject *);
1084 ucopy = PyUnicode_AS_UNICODE(*callresult);
1085 usize = PyUnicode_GET_SIZE(*callresult);
1086 for (upos = 0; upos<usize;)
1087 *s++ = ucopy[upos++];
1088 /* We're done with the unicode()/repr() => forget it */
1089 Py_DECREF(*callresult);
1090 /* switch to next unicode()/repr() result */
1091 ++callresult;
1092 break;
1093 }
1094 case 'p':
1095 sprintf(buffer, "%p", va_arg(vargs, void*));
1096 /* %p is ill-defined: ensure leading 0x. */
1097 if (buffer[1] == 'X')
1098 buffer[1] = 'x';
1099 else if (buffer[1] != 'x') {
1100 memmove(buffer+2, buffer, strlen(buffer)+1);
1101 buffer[0] = '0';
1102 buffer[1] = 'x';
1103 }
1104 appendstring(buffer);
1105 break;
1106 case '%':
1107 *s++ = '%';
1108 break;
1109 default:
1110 appendstring(p);
1111 goto end;
1112 }
Victor Stinner1205f272010-09-11 00:54:47 +00001113 }
Victor Stinner1205f272010-09-11 00:54:47 +00001114 else
Benjamin Peterson14339b62009-01-31 16:36:08 +00001115 *s++ = *f;
1116 }
Walter Dörwaldd2034312007-05-18 16:29:38 +00001117
Benjamin Peterson29060642009-01-31 22:14:21 +00001118 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001119 if (callresults)
1120 PyObject_Free(callresults);
1121 if (abuffer)
1122 PyObject_Free(abuffer);
1123 PyUnicode_Resize(&string, s - PyUnicode_AS_UNICODE(string));
1124 return string;
Benjamin Peterson29060642009-01-31 22:14:21 +00001125 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001126 if (callresults) {
1127 PyObject **callresult2 = callresults;
1128 while (callresult2 < callresult) {
1129 Py_DECREF(*callresult2);
1130 ++callresult2;
1131 }
1132 PyObject_Free(callresults);
1133 }
1134 if (abuffer)
1135 PyObject_Free(abuffer);
1136 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001137}
1138
1139#undef appendstring
1140
1141PyObject *
1142PyUnicode_FromFormat(const char *format, ...)
1143{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001144 PyObject* ret;
1145 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001146
1147#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00001148 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001149#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00001150 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001151#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001152 ret = PyUnicode_FromFormatV(format, vargs);
1153 va_end(vargs);
1154 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001155}
1156
Victor Stinner5593d8a2010-10-02 11:11:27 +00001157/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
1158 convert a Unicode object to a wide character string.
1159
1160 - If w is NULL: return the number of wide characters (including the nul
1161 character) required to convert the unicode object. Ignore size argument.
1162
1163 - Otherwise: return the number of wide characters (excluding the nul
1164 character) written into w. Write at most size wide characters (including
1165 the nul character). */
1166static Py_ssize_t
Victor Stinner137c34c2010-09-29 10:25:54 +00001167unicode_aswidechar(PyUnicodeObject *unicode,
1168 wchar_t *w,
1169 Py_ssize_t size)
1170{
1171#if Py_UNICODE_SIZE == SIZEOF_WCHAR_T
Victor Stinner5593d8a2010-10-02 11:11:27 +00001172 Py_ssize_t res;
1173 if (w != NULL) {
1174 res = PyUnicode_GET_SIZE(unicode);
1175 if (size > res)
1176 size = res + 1;
1177 else
1178 res = size;
1179 memcpy(w, unicode->str, size * sizeof(wchar_t));
1180 return res;
1181 }
1182 else
1183 return PyUnicode_GET_SIZE(unicode) + 1;
1184#elif Py_UNICODE_SIZE == 2 && SIZEOF_WCHAR_T == 4
1185 register const Py_UNICODE *u;
1186 const Py_UNICODE *uend;
1187 const wchar_t *worig, *wend;
1188 Py_ssize_t nchar;
1189
Victor Stinner137c34c2010-09-29 10:25:54 +00001190 u = PyUnicode_AS_UNICODE(unicode);
Victor Stinner5593d8a2010-10-02 11:11:27 +00001191 uend = u + PyUnicode_GET_SIZE(unicode);
1192 if (w != NULL) {
1193 worig = w;
1194 wend = w + size;
1195 while (u != uend && w != wend) {
1196 if (0xD800 <= u[0] && u[0] <= 0xDBFF
1197 && 0xDC00 <= u[1] && u[1] <= 0xDFFF)
1198 {
1199 *w = (((u[0] & 0x3FF) << 10) | (u[1] & 0x3FF)) + 0x10000;
1200 u += 2;
1201 }
1202 else {
1203 *w = *u;
1204 u++;
1205 }
1206 w++;
1207 }
1208 if (w != wend)
1209 *w = L'\0';
1210 return w - worig;
1211 }
1212 else {
1213 nchar = 1; /* nul character at the end */
1214 while (u != uend) {
1215 if (0xD800 <= u[0] && u[0] <= 0xDBFF
1216 && 0xDC00 <= u[1] && u[1] <= 0xDFFF)
1217 u += 2;
1218 else
1219 u++;
1220 nchar++;
1221 }
1222 }
1223 return nchar;
1224#elif Py_UNICODE_SIZE == 4 && SIZEOF_WCHAR_T == 2
1225 register Py_UNICODE *u, *uend, ordinal;
1226 register Py_ssize_t i;
1227 wchar_t *worig, *wend;
1228 Py_ssize_t nchar;
1229
1230 u = PyUnicode_AS_UNICODE(unicode);
1231 uend = u + PyUnicode_GET_SIZE(u);
1232 if (w != NULL) {
1233 worig = w;
1234 wend = w + size;
1235 while (u != uend && w != wend) {
1236 ordinal = *u;
1237 if (ordinal > 0xffff) {
1238 ordinal -= 0x10000;
1239 *w++ = 0xD800 | (ordinal >> 10);
1240 *w++ = 0xDC00 | (ordinal & 0x3FF);
1241 }
1242 else
1243 *w++ = ordinal;
1244 u++;
1245 }
1246 if (w != wend)
1247 *w = 0;
1248 return w - worig;
1249 }
1250 else {
1251 nchar = 1; /* nul character */
1252 while (u != uend) {
1253 if (*u > 0xffff)
1254 nchar += 2;
1255 else
1256 nchar++;
1257 u++;
1258 }
1259 return nchar;
1260 }
1261#else
1262# error "unsupported wchar_t and Py_UNICODE sizes, see issue #8670"
Victor Stinner137c34c2010-09-29 10:25:54 +00001263#endif
1264}
1265
1266Py_ssize_t
1267PyUnicode_AsWideChar(PyUnicodeObject *unicode,
1268 wchar_t *w,
1269 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001270{
1271 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001272 PyErr_BadInternalCall();
1273 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001274 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00001275 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001276}
1277
Victor Stinner137c34c2010-09-29 10:25:54 +00001278wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00001279PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00001280 Py_ssize_t *size)
1281{
1282 wchar_t* buffer;
1283 Py_ssize_t buflen;
1284
1285 if (unicode == NULL) {
1286 PyErr_BadInternalCall();
1287 return NULL;
1288 }
1289
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00001290 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, NULL, 0);
Victor Stinner5593d8a2010-10-02 11:11:27 +00001291 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00001292 PyErr_NoMemory();
1293 return NULL;
1294 }
1295
Victor Stinner137c34c2010-09-29 10:25:54 +00001296 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
1297 if (buffer == NULL) {
1298 PyErr_NoMemory();
1299 return NULL;
1300 }
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00001301 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, buffer, buflen);
Victor Stinner5593d8a2010-10-02 11:11:27 +00001302 if (size != NULL)
1303 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00001304 return buffer;
1305}
1306
Guido van Rossumd57fd912000-03-10 22:53:23 +00001307#endif
1308
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001309PyObject *PyUnicode_FromOrdinal(int ordinal)
1310{
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001311 Py_UNICODE s[2];
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001312
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001313 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001314 PyErr_SetString(PyExc_ValueError,
1315 "chr() arg not in range(0x110000)");
1316 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001317 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001318
1319#ifndef Py_UNICODE_WIDE
1320 if (ordinal > 0xffff) {
1321 ordinal -= 0x10000;
1322 s[0] = 0xD800 | (ordinal >> 10);
1323 s[1] = 0xDC00 | (ordinal & 0x3FF);
1324 return PyUnicode_FromUnicode(s, 2);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001325 }
1326#endif
1327
Hye-Shik Chang40574832004-04-06 07:24:51 +00001328 s[0] = (Py_UNICODE)ordinal;
1329 return PyUnicode_FromUnicode(s, 1);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001330}
1331
Guido van Rossumd57fd912000-03-10 22:53:23 +00001332PyObject *PyUnicode_FromObject(register PyObject *obj)
1333{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001334 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00001335 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001336 if (PyUnicode_CheckExact(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001337 Py_INCREF(obj);
1338 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001339 }
1340 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001341 /* For a Unicode subtype that's not a Unicode object,
1342 return a true Unicode object with the same data. */
1343 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(obj),
1344 PyUnicode_GET_SIZE(obj));
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001345 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001346 PyErr_Format(PyExc_TypeError,
1347 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00001348 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001349 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001350}
1351
1352PyObject *PyUnicode_FromEncodedObject(register PyObject *obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00001353 const char *encoding,
1354 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001355{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001356 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001357 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00001358
Guido van Rossumd57fd912000-03-10 22:53:23 +00001359 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001360 PyErr_BadInternalCall();
1361 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001362 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001363
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001364 /* Decoding bytes objects is the most common case and should be fast */
1365 if (PyBytes_Check(obj)) {
1366 if (PyBytes_GET_SIZE(obj) == 0) {
1367 Py_INCREF(unicode_empty);
1368 v = (PyObject *) unicode_empty;
1369 }
1370 else {
1371 v = PyUnicode_Decode(
1372 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
1373 encoding, errors);
1374 }
1375 return v;
1376 }
1377
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001378 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001379 PyErr_SetString(PyExc_TypeError,
1380 "decoding str is not supported");
1381 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001382 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001383
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001384 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
1385 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
1386 PyErr_Format(PyExc_TypeError,
1387 "coercing to str: need bytes, bytearray "
1388 "or buffer-like object, %.80s found",
1389 Py_TYPE(obj)->tp_name);
1390 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00001391 }
Tim Petersced69f82003-09-16 20:30:58 +00001392
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001393 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001394 Py_INCREF(unicode_empty);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001395 v = (PyObject *) unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001396 }
Tim Petersced69f82003-09-16 20:30:58 +00001397 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001398 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00001399
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001400 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001401 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001402}
1403
Victor Stinner600d3be2010-06-10 12:00:55 +00001404/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00001405 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
1406 1 on success. */
1407static int
1408normalize_encoding(const char *encoding,
1409 char *lower,
1410 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001411{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001412 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00001413 char *l;
1414 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001415
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001416 e = encoding;
1417 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00001418 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00001419 while (*e) {
1420 if (l == l_end)
1421 return 0;
David Malcolm96960882010-11-05 17:23:41 +00001422 if (Py_ISUPPER(*e)) {
1423 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001424 }
1425 else if (*e == '_') {
1426 *l++ = '-';
1427 e++;
1428 }
1429 else {
1430 *l++ = *e++;
1431 }
1432 }
1433 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00001434 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00001435}
1436
1437PyObject *PyUnicode_Decode(const char *s,
1438 Py_ssize_t size,
1439 const char *encoding,
1440 const char *errors)
1441{
1442 PyObject *buffer = NULL, *unicode;
1443 Py_buffer info;
1444 char lower[11]; /* Enough for any encoding shortcut */
1445
1446 if (encoding == NULL)
1447 encoding = PyUnicode_GetDefaultEncoding();
Fred Drakee4315f52000-05-09 19:53:39 +00001448
1449 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00001450 if (normalize_encoding(encoding, lower, sizeof(lower))) {
1451 if (strcmp(lower, "utf-8") == 0)
1452 return PyUnicode_DecodeUTF8(s, size, errors);
1453 else if ((strcmp(lower, "latin-1") == 0) ||
1454 (strcmp(lower, "iso-8859-1") == 0))
1455 return PyUnicode_DecodeLatin1(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001456#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Victor Stinner37296e82010-06-10 13:36:23 +00001457 else if (strcmp(lower, "mbcs") == 0)
1458 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001459#endif
Victor Stinner37296e82010-06-10 13:36:23 +00001460 else if (strcmp(lower, "ascii") == 0)
1461 return PyUnicode_DecodeASCII(s, size, errors);
1462 else if (strcmp(lower, "utf-16") == 0)
1463 return PyUnicode_DecodeUTF16(s, size, errors, 0);
1464 else if (strcmp(lower, "utf-32") == 0)
1465 return PyUnicode_DecodeUTF32(s, size, errors, 0);
1466 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001467
1468 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00001469 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00001470 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00001471 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00001472 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001473 if (buffer == NULL)
1474 goto onError;
1475 unicode = PyCodec_Decode(buffer, encoding, errors);
1476 if (unicode == NULL)
1477 goto onError;
1478 if (!PyUnicode_Check(unicode)) {
1479 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001480 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00001481 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001482 Py_DECREF(unicode);
1483 goto onError;
1484 }
1485 Py_DECREF(buffer);
1486 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00001487
Benjamin Peterson29060642009-01-31 22:14:21 +00001488 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001489 Py_XDECREF(buffer);
1490 return NULL;
1491}
1492
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001493PyObject *PyUnicode_AsDecodedObject(PyObject *unicode,
1494 const char *encoding,
1495 const char *errors)
1496{
1497 PyObject *v;
1498
1499 if (!PyUnicode_Check(unicode)) {
1500 PyErr_BadArgument();
1501 goto onError;
1502 }
1503
1504 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001505 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001506
1507 /* Decode via the codec registry */
1508 v = PyCodec_Decode(unicode, encoding, errors);
1509 if (v == NULL)
1510 goto onError;
1511 return v;
1512
Benjamin Peterson29060642009-01-31 22:14:21 +00001513 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001514 return NULL;
1515}
1516
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001517PyObject *PyUnicode_AsDecodedUnicode(PyObject *unicode,
1518 const char *encoding,
1519 const char *errors)
1520{
1521 PyObject *v;
1522
1523 if (!PyUnicode_Check(unicode)) {
1524 PyErr_BadArgument();
1525 goto onError;
1526 }
1527
1528 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001529 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001530
1531 /* Decode via the codec registry */
1532 v = PyCodec_Decode(unicode, encoding, errors);
1533 if (v == NULL)
1534 goto onError;
1535 if (!PyUnicode_Check(v)) {
1536 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001537 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001538 Py_TYPE(v)->tp_name);
1539 Py_DECREF(v);
1540 goto onError;
1541 }
1542 return v;
1543
Benjamin Peterson29060642009-01-31 22:14:21 +00001544 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001545 return NULL;
1546}
1547
Guido van Rossumd57fd912000-03-10 22:53:23 +00001548PyObject *PyUnicode_Encode(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00001549 Py_ssize_t size,
1550 const char *encoding,
1551 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001552{
1553 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00001554
Guido van Rossumd57fd912000-03-10 22:53:23 +00001555 unicode = PyUnicode_FromUnicode(s, size);
1556 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001557 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001558 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
1559 Py_DECREF(unicode);
1560 return v;
1561}
1562
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001563PyObject *PyUnicode_AsEncodedObject(PyObject *unicode,
1564 const char *encoding,
1565 const char *errors)
1566{
1567 PyObject *v;
1568
1569 if (!PyUnicode_Check(unicode)) {
1570 PyErr_BadArgument();
1571 goto onError;
1572 }
1573
1574 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001575 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001576
1577 /* Encode via the codec registry */
1578 v = PyCodec_Encode(unicode, encoding, errors);
1579 if (v == NULL)
1580 goto onError;
1581 return v;
1582
Benjamin Peterson29060642009-01-31 22:14:21 +00001583 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001584 return NULL;
1585}
1586
Victor Stinnerad158722010-10-27 00:25:46 +00001587PyObject *
1588PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00001589{
Victor Stinner313a1202010-06-11 23:56:51 +00001590#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Victor Stinnerad158722010-10-27 00:25:46 +00001591 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
1592 PyUnicode_GET_SIZE(unicode),
1593 NULL);
1594#elif defined(__APPLE__)
1595 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
1596 PyUnicode_GET_SIZE(unicode),
1597 "surrogateescape");
1598#else
1599 if (Py_FileSystemDefaultEncoding) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00001600 return PyUnicode_AsEncodedString(unicode,
1601 Py_FileSystemDefaultEncoding,
1602 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00001603 }
1604 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001605 /* locale encoding with surrogateescape */
1606 wchar_t *wchar;
1607 char *bytes;
1608 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00001609 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001610
1611 wchar = PyUnicode_AsWideCharString(unicode, NULL);
1612 if (wchar == NULL)
1613 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00001614 bytes = _Py_wchar2char(wchar, &error_pos);
1615 if (bytes == NULL) {
1616 if (error_pos != (size_t)-1) {
1617 char *errmsg = strerror(errno);
1618 PyObject *exc = NULL;
1619 if (errmsg == NULL)
1620 errmsg = "Py_wchar2char() failed";
1621 raise_encode_exception(&exc,
1622 "filesystemencoding",
1623 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
1624 error_pos, error_pos+1,
1625 errmsg);
1626 Py_XDECREF(exc);
1627 }
1628 else
1629 PyErr_NoMemory();
1630 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001631 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00001632 }
1633 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001634
1635 bytes_obj = PyBytes_FromString(bytes);
1636 PyMem_Free(bytes);
1637 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00001638 }
Victor Stinnerad158722010-10-27 00:25:46 +00001639#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00001640}
1641
Guido van Rossumd57fd912000-03-10 22:53:23 +00001642PyObject *PyUnicode_AsEncodedString(PyObject *unicode,
1643 const char *encoding,
1644 const char *errors)
1645{
1646 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00001647 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00001648
Guido van Rossumd57fd912000-03-10 22:53:23 +00001649 if (!PyUnicode_Check(unicode)) {
1650 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001651 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001652 }
Fred Drakee4315f52000-05-09 19:53:39 +00001653
Tim Petersced69f82003-09-16 20:30:58 +00001654 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001655 encoding = PyUnicode_GetDefaultEncoding();
Fred Drakee4315f52000-05-09 19:53:39 +00001656
1657 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00001658 if (normalize_encoding(encoding, lower, sizeof(lower))) {
1659 if (strcmp(lower, "utf-8") == 0)
1660 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
1661 PyUnicode_GET_SIZE(unicode),
1662 errors);
1663 else if ((strcmp(lower, "latin-1") == 0) ||
1664 (strcmp(lower, "iso-8859-1") == 0))
1665 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
1666 PyUnicode_GET_SIZE(unicode),
1667 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001668#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Victor Stinner37296e82010-06-10 13:36:23 +00001669 else if (strcmp(lower, "mbcs") == 0)
1670 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
1671 PyUnicode_GET_SIZE(unicode),
1672 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001673#endif
Victor Stinner37296e82010-06-10 13:36:23 +00001674 else if (strcmp(lower, "ascii") == 0)
1675 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
1676 PyUnicode_GET_SIZE(unicode),
1677 errors);
1678 }
Victor Stinner59e62db2010-05-15 13:14:32 +00001679 /* During bootstrap, we may need to find the encodings
1680 package, to load the file system encoding, and require the
1681 file system encoding in order to load the encodings
1682 package.
Christian Heimes6a27efa2008-10-30 21:48:26 +00001683
Victor Stinner59e62db2010-05-15 13:14:32 +00001684 Break out of this dependency by assuming that the path to
1685 the encodings module is ASCII-only. XXX could try wcstombs
1686 instead, if the file system encoding is the locale's
1687 encoding. */
Victor Stinner37296e82010-06-10 13:36:23 +00001688 if (Py_FileSystemDefaultEncoding &&
Victor Stinner59e62db2010-05-15 13:14:32 +00001689 strcmp(encoding, Py_FileSystemDefaultEncoding) == 0 &&
1690 !PyThreadState_GET()->interp->codecs_initialized)
1691 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
1692 PyUnicode_GET_SIZE(unicode),
1693 errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001694
1695 /* Encode via the codec registry */
1696 v = PyCodec_Encode(unicode, encoding, errors);
1697 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001698 return NULL;
1699
1700 /* The normal path */
1701 if (PyBytes_Check(v))
1702 return v;
1703
1704 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001705 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001706 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001707 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001708
1709 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1710 "encoder %s returned bytearray instead of bytes",
1711 encoding);
1712 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001713 Py_DECREF(v);
1714 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001715 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001716
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001717 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
1718 Py_DECREF(v);
1719 return b;
1720 }
1721
1722 PyErr_Format(PyExc_TypeError,
1723 "encoder did not return a bytes object (type=%.400s)",
1724 Py_TYPE(v)->tp_name);
1725 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001726 return NULL;
1727}
1728
1729PyObject *PyUnicode_AsEncodedUnicode(PyObject *unicode,
1730 const char *encoding,
1731 const char *errors)
1732{
1733 PyObject *v;
1734
1735 if (!PyUnicode_Check(unicode)) {
1736 PyErr_BadArgument();
1737 goto onError;
1738 }
1739
1740 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001741 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001742
1743 /* Encode via the codec registry */
1744 v = PyCodec_Encode(unicode, encoding, errors);
1745 if (v == NULL)
1746 goto onError;
1747 if (!PyUnicode_Check(v)) {
1748 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001749 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001750 Py_TYPE(v)->tp_name);
1751 Py_DECREF(v);
1752 goto onError;
1753 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001754 return v;
Tim Petersced69f82003-09-16 20:30:58 +00001755
Benjamin Peterson29060642009-01-31 22:14:21 +00001756 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001757 return NULL;
1758}
1759
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001760PyObject *_PyUnicode_AsDefaultEncodedString(PyObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00001761 const char *errors)
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001762{
1763 PyObject *v = ((PyUnicodeObject *)unicode)->defenc;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001764 if (v)
1765 return v;
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001766 if (errors != NULL)
1767 Py_FatalError("non-NULL encoding in _PyUnicode_AsDefaultEncodedString");
Guido van Rossum98297ee2007-11-06 21:34:58 +00001768 v = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
Guido van Rossum06610092007-08-16 21:02:22 +00001769 PyUnicode_GET_SIZE(unicode),
1770 NULL);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001771 if (!v)
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001772 return NULL;
Guido van Rossume7a0d392007-07-12 07:53:00 +00001773 ((PyUnicodeObject *)unicode)->defenc = v;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001774 return v;
1775}
1776
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001777PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00001778PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001779 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00001780 return PyUnicode_DecodeFSDefaultAndSize(s, size);
1781}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001782
Christian Heimes5894ba72007-11-04 11:43:14 +00001783PyObject*
1784PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
1785{
Victor Stinnerad158722010-10-27 00:25:46 +00001786#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
1787 return PyUnicode_DecodeMBCS(s, size, NULL);
1788#elif defined(__APPLE__)
1789 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
1790#else
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001791 /* During the early bootstrapping process, Py_FileSystemDefaultEncoding
1792 can be undefined. If it is case, decode using UTF-8. The following assumes
1793 that Py_FileSystemDefaultEncoding is set to a built-in encoding during the
1794 bootstrapping process where the codecs aren't ready yet.
1795 */
1796 if (Py_FileSystemDefaultEncoding) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001797 return PyUnicode_Decode(s, size,
1798 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00001799 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001800 }
1801 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001802 /* locale encoding with surrogateescape */
1803 wchar_t *wchar;
1804 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00001805 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001806
1807 if (s[size] != '\0' || size != strlen(s)) {
1808 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
1809 return NULL;
1810 }
1811
Victor Stinner168e1172010-10-16 23:16:16 +00001812 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001813 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00001814 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001815
Victor Stinner168e1172010-10-16 23:16:16 +00001816 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00001817 PyMem_Free(wchar);
1818 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001819 }
Victor Stinnerad158722010-10-27 00:25:46 +00001820#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001821}
1822
Martin v. Löwis011e8422009-05-05 04:43:17 +00001823
1824int
1825PyUnicode_FSConverter(PyObject* arg, void* addr)
1826{
1827 PyObject *output = NULL;
1828 Py_ssize_t size;
1829 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00001830 if (arg == NULL) {
1831 Py_DECREF(*(PyObject**)addr);
1832 return 1;
1833 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00001834 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00001835 output = arg;
1836 Py_INCREF(output);
1837 }
1838 else {
1839 arg = PyUnicode_FromObject(arg);
1840 if (!arg)
1841 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00001842 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00001843 Py_DECREF(arg);
1844 if (!output)
1845 return 0;
1846 if (!PyBytes_Check(output)) {
1847 Py_DECREF(output);
1848 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
1849 return 0;
1850 }
1851 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00001852 size = PyBytes_GET_SIZE(output);
1853 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00001854 if (size != strlen(data)) {
1855 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
1856 Py_DECREF(output);
1857 return 0;
1858 }
1859 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00001860 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00001861}
1862
1863
Victor Stinner47fcb5b2010-08-13 23:59:58 +00001864int
1865PyUnicode_FSDecoder(PyObject* arg, void* addr)
1866{
1867 PyObject *output = NULL;
1868 Py_ssize_t size;
1869 void *data;
1870 if (arg == NULL) {
1871 Py_DECREF(*(PyObject**)addr);
1872 return 1;
1873 }
1874 if (PyUnicode_Check(arg)) {
1875 output = arg;
1876 Py_INCREF(output);
1877 }
1878 else {
1879 arg = PyBytes_FromObject(arg);
1880 if (!arg)
1881 return 0;
1882 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
1883 PyBytes_GET_SIZE(arg));
1884 Py_DECREF(arg);
1885 if (!output)
1886 return 0;
1887 if (!PyUnicode_Check(output)) {
1888 Py_DECREF(output);
1889 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
1890 return 0;
1891 }
1892 }
1893 size = PyUnicode_GET_SIZE(output);
1894 data = PyUnicode_AS_UNICODE(output);
1895 if (size != Py_UNICODE_strlen(data)) {
1896 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
1897 Py_DECREF(output);
1898 return 0;
1899 }
1900 *(PyObject**)addr = output;
1901 return Py_CLEANUP_SUPPORTED;
1902}
1903
1904
Martin v. Löwis5b222132007-06-10 09:51:05 +00001905char*
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001906_PyUnicode_AsStringAndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00001907{
Christian Heimesf3863112007-11-22 07:46:41 +00001908 PyObject *bytes;
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00001909 if (!PyUnicode_Check(unicode)) {
1910 PyErr_BadArgument();
1911 return NULL;
1912 }
Christian Heimesf3863112007-11-22 07:46:41 +00001913 bytes = _PyUnicode_AsDefaultEncodedString(unicode, NULL);
1914 if (bytes == NULL)
Martin v. Löwis5b222132007-06-10 09:51:05 +00001915 return NULL;
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001916 if (psize != NULL)
Christian Heimes72b710a2008-05-26 13:28:38 +00001917 *psize = PyBytes_GET_SIZE(bytes);
1918 return PyBytes_AS_STRING(bytes);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001919}
1920
1921char*
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001922_PyUnicode_AsString(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001923{
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001924 return _PyUnicode_AsStringAndSize(unicode, NULL);
Martin v. Löwis5b222132007-06-10 09:51:05 +00001925}
1926
Guido van Rossumd57fd912000-03-10 22:53:23 +00001927Py_UNICODE *PyUnicode_AsUnicode(PyObject *unicode)
1928{
1929 if (!PyUnicode_Check(unicode)) {
1930 PyErr_BadArgument();
1931 goto onError;
1932 }
1933 return PyUnicode_AS_UNICODE(unicode);
1934
Benjamin Peterson29060642009-01-31 22:14:21 +00001935 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001936 return NULL;
1937}
1938
Martin v. Löwis18e16552006-02-15 17:27:45 +00001939Py_ssize_t PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001940{
1941 if (!PyUnicode_Check(unicode)) {
1942 PyErr_BadArgument();
1943 goto onError;
1944 }
1945 return PyUnicode_GET_SIZE(unicode);
1946
Benjamin Peterson29060642009-01-31 22:14:21 +00001947 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001948 return -1;
1949}
1950
Thomas Wouters78890102000-07-22 19:25:51 +00001951const char *PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00001952{
Victor Stinner42cb4622010-09-01 19:39:01 +00001953 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00001954}
1955
Victor Stinner554f3f02010-06-16 23:33:54 +00001956/* create or adjust a UnicodeDecodeError */
1957static void
1958make_decode_exception(PyObject **exceptionObject,
1959 const char *encoding,
1960 const char *input, Py_ssize_t length,
1961 Py_ssize_t startpos, Py_ssize_t endpos,
1962 const char *reason)
1963{
1964 if (*exceptionObject == NULL) {
1965 *exceptionObject = PyUnicodeDecodeError_Create(
1966 encoding, input, length, startpos, endpos, reason);
1967 }
1968 else {
1969 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
1970 goto onError;
1971 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
1972 goto onError;
1973 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
1974 goto onError;
1975 }
1976 return;
1977
1978onError:
1979 Py_DECREF(*exceptionObject);
1980 *exceptionObject = NULL;
1981}
1982
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001983/* error handling callback helper:
1984 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00001985 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001986 and adjust various state variables.
1987 return 0 on success, -1 on error
1988*/
1989
1990static
1991int unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00001992 const char *encoding, const char *reason,
1993 const char **input, const char **inend, Py_ssize_t *startinpos,
1994 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
1995 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001996{
Benjamin Peterson142957c2008-07-04 19:55:29 +00001997 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001998
1999 PyObject *restuple = NULL;
2000 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002001 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002002 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002003 Py_ssize_t requiredsize;
2004 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002005 Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002006 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002007 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002008 int res = -1;
2009
2010 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002011 *errorHandler = PyCodec_LookupError(errors);
2012 if (*errorHandler == NULL)
2013 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002014 }
2015
Victor Stinner554f3f02010-06-16 23:33:54 +00002016 make_decode_exception(exceptionObject,
2017 encoding,
2018 *input, *inend - *input,
2019 *startinpos, *endinpos,
2020 reason);
2021 if (*exceptionObject == NULL)
2022 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002023
2024 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
2025 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002026 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002027 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00002028 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00002029 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002030 }
2031 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00002032 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002033
2034 /* Copy back the bytes variables, which might have been modified by the
2035 callback */
2036 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
2037 if (!inputobj)
2038 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00002039 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002040 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00002041 }
Christian Heimes72b710a2008-05-26 13:28:38 +00002042 *input = PyBytes_AS_STRING(inputobj);
2043 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002044 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00002045 /* we can DECREF safely, as the exception has another reference,
2046 so the object won't go away. */
2047 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002048
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002049 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00002050 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00002051 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002052 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
2053 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00002054 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002055
2056 /* need more space? (at least enough for what we
2057 have+the replacement+the rest of the string (starting
2058 at the new input position), so we won't have to check space
2059 when there are no errors in the rest of the string) */
2060 repptr = PyUnicode_AS_UNICODE(repunicode);
2061 repsize = PyUnicode_GET_SIZE(repunicode);
2062 requiredsize = *outpos + repsize + insize-newpos;
2063 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002064 if (requiredsize<2*outsize)
2065 requiredsize = 2*outsize;
2066 if (_PyUnicode_Resize(output, requiredsize) < 0)
2067 goto onError;
2068 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002069 }
2070 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002071 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002072 Py_UNICODE_COPY(*outptr, repptr, repsize);
2073 *outptr += repsize;
2074 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002075
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002076 /* we made it! */
2077 res = 0;
2078
Benjamin Peterson29060642009-01-31 22:14:21 +00002079 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002080 Py_XDECREF(restuple);
2081 return res;
2082}
2083
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002084/* --- UTF-7 Codec -------------------------------------------------------- */
2085
Antoine Pitrou244651a2009-05-04 18:56:13 +00002086/* See RFC2152 for details. We encode conservatively and decode liberally. */
2087
2088/* Three simple macros defining base-64. */
2089
2090/* Is c a base-64 character? */
2091
2092#define IS_BASE64(c) \
2093 (((c) >= 'A' && (c) <= 'Z') || \
2094 ((c) >= 'a' && (c) <= 'z') || \
2095 ((c) >= '0' && (c) <= '9') || \
2096 (c) == '+' || (c) == '/')
2097
2098/* given that c is a base-64 character, what is its base-64 value? */
2099
2100#define FROM_BASE64(c) \
2101 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
2102 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
2103 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
2104 (c) == '+' ? 62 : 63)
2105
2106/* What is the base-64 character of the bottom 6 bits of n? */
2107
2108#define TO_BASE64(n) \
2109 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
2110
2111/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
2112 * decoded as itself. We are permissive on decoding; the only ASCII
2113 * byte not decoding to itself is the + which begins a base64
2114 * string. */
2115
2116#define DECODE_DIRECT(c) \
2117 ((c) <= 127 && (c) != '+')
2118
2119/* The UTF-7 encoder treats ASCII characters differently according to
2120 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
2121 * the above). See RFC2152. This array identifies these different
2122 * sets:
2123 * 0 : "Set D"
2124 * alphanumeric and '(),-./:?
2125 * 1 : "Set O"
2126 * !"#$%&*;<=>@[]^_`{|}
2127 * 2 : "whitespace"
2128 * ht nl cr sp
2129 * 3 : special (must be base64 encoded)
2130 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
2131 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002132
Tim Petersced69f82003-09-16 20:30:58 +00002133static
Antoine Pitrou244651a2009-05-04 18:56:13 +00002134char utf7_category[128] = {
2135/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
2136 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
2137/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
2138 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2139/* sp ! " # $ % & ' ( ) * + , - . / */
2140 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
2141/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
2142 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
2143/* @ A B C D E F G H I J K L M N O */
2144 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2145/* P Q R S T U V W X Y Z [ \ ] ^ _ */
2146 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
2147/* ` a b c d e f g h i j k l m n o */
2148 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2149/* p q r s t u v w x y z { | } ~ del */
2150 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002151};
2152
Antoine Pitrou244651a2009-05-04 18:56:13 +00002153/* ENCODE_DIRECT: this character should be encoded as itself. The
2154 * answer depends on whether we are encoding set O as itself, and also
2155 * on whether we are encoding whitespace as itself. RFC2152 makes it
2156 * clear that the answers to these questions vary between
2157 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00002158
Antoine Pitrou244651a2009-05-04 18:56:13 +00002159#define ENCODE_DIRECT(c, directO, directWS) \
2160 ((c) < 128 && (c) > 0 && \
2161 ((utf7_category[(c)] == 0) || \
2162 (directWS && (utf7_category[(c)] == 2)) || \
2163 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002164
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002165PyObject *PyUnicode_DecodeUTF7(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002166 Py_ssize_t size,
2167 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002168{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002169 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
2170}
2171
Antoine Pitrou244651a2009-05-04 18:56:13 +00002172/* The decoder. The only state we preserve is our read position,
2173 * i.e. how many characters we have consumed. So if we end in the
2174 * middle of a shift sequence we have to back off the read position
2175 * and the output to the beginning of the sequence, otherwise we lose
2176 * all the shift state (seen bits, number of bits seen, high
2177 * surrogate). */
2178
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002179PyObject *PyUnicode_DecodeUTF7Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002180 Py_ssize_t size,
2181 const char *errors,
2182 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002183{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002184 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002185 Py_ssize_t startinpos;
2186 Py_ssize_t endinpos;
2187 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002188 const char *e;
2189 PyUnicodeObject *unicode;
2190 Py_UNICODE *p;
2191 const char *errmsg = "";
2192 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002193 Py_UNICODE *shiftOutStart;
2194 unsigned int base64bits = 0;
2195 unsigned long base64buffer = 0;
2196 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002197 PyObject *errorHandler = NULL;
2198 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002199
2200 unicode = _PyUnicode_New(size);
2201 if (!unicode)
2202 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002203 if (size == 0) {
2204 if (consumed)
2205 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002206 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002207 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002208
2209 p = unicode->str;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002210 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002211 e = s + size;
2212
2213 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002214 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00002215 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00002216 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002217
Antoine Pitrou244651a2009-05-04 18:56:13 +00002218 if (inShift) { /* in a base-64 section */
2219 if (IS_BASE64(ch)) { /* consume a base-64 character */
2220 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
2221 base64bits += 6;
2222 s++;
2223 if (base64bits >= 16) {
2224 /* we have enough bits for a UTF-16 value */
2225 Py_UNICODE outCh = (Py_UNICODE)
2226 (base64buffer >> (base64bits-16));
2227 base64bits -= 16;
2228 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
2229 if (surrogate) {
2230 /* expecting a second surrogate */
2231 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
2232#ifdef Py_UNICODE_WIDE
2233 *p++ = (((surrogate & 0x3FF)<<10)
2234 | (outCh & 0x3FF)) + 0x10000;
2235#else
2236 *p++ = surrogate;
2237 *p++ = outCh;
2238#endif
2239 surrogate = 0;
2240 }
2241 else {
2242 surrogate = 0;
2243 errmsg = "second surrogate missing";
2244 goto utf7Error;
2245 }
2246 }
2247 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
2248 /* first surrogate */
2249 surrogate = outCh;
2250 }
2251 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
2252 errmsg = "unexpected second surrogate";
2253 goto utf7Error;
2254 }
2255 else {
2256 *p++ = outCh;
2257 }
2258 }
2259 }
2260 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002261 inShift = 0;
2262 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002263 if (surrogate) {
2264 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00002265 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002266 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002267 if (base64bits > 0) { /* left-over bits */
2268 if (base64bits >= 6) {
2269 /* We've seen at least one base-64 character */
2270 errmsg = "partial character in shift sequence";
2271 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002272 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002273 else {
2274 /* Some bits remain; they should be zero */
2275 if (base64buffer != 0) {
2276 errmsg = "non-zero padding bits in shift sequence";
2277 goto utf7Error;
2278 }
2279 }
2280 }
2281 if (ch != '-') {
2282 /* '-' is absorbed; other terminating
2283 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002284 *p++ = ch;
2285 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002286 }
2287 }
2288 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002289 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002290 s++; /* consume '+' */
2291 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002292 s++;
2293 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00002294 }
2295 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002296 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002297 shiftOutStart = p;
2298 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002299 }
2300 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002301 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002302 *p++ = ch;
2303 s++;
2304 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002305 else {
2306 startinpos = s-starts;
2307 s++;
2308 errmsg = "unexpected special character";
2309 goto utf7Error;
2310 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002311 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002312utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002313 outpos = p-PyUnicode_AS_UNICODE(unicode);
2314 endinpos = s-starts;
2315 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00002316 errors, &errorHandler,
2317 "utf7", errmsg,
2318 &starts, &e, &startinpos, &endinpos, &exc, &s,
2319 &unicode, &outpos, &p))
2320 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002321 }
2322
Antoine Pitrou244651a2009-05-04 18:56:13 +00002323 /* end of string */
2324
2325 if (inShift && !consumed) { /* in shift sequence, no more to follow */
2326 /* if we're in an inconsistent state, that's an error */
2327 if (surrogate ||
2328 (base64bits >= 6) ||
2329 (base64bits > 0 && base64buffer != 0)) {
2330 outpos = p-PyUnicode_AS_UNICODE(unicode);
2331 endinpos = size;
2332 if (unicode_decode_call_errorhandler(
2333 errors, &errorHandler,
2334 "utf7", "unterminated shift sequence",
2335 &starts, &e, &startinpos, &endinpos, &exc, &s,
2336 &unicode, &outpos, &p))
2337 goto onError;
2338 if (s < e)
2339 goto restart;
2340 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002341 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002342
2343 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002344 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00002345 if (inShift) {
2346 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002347 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002348 }
2349 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002350 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002351 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002352 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002353
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00002354 if (_PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002355 goto onError;
2356
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002357 Py_XDECREF(errorHandler);
2358 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002359 return (PyObject *)unicode;
2360
Benjamin Peterson29060642009-01-31 22:14:21 +00002361 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002362 Py_XDECREF(errorHandler);
2363 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002364 Py_DECREF(unicode);
2365 return NULL;
2366}
2367
2368
2369PyObject *PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002370 Py_ssize_t size,
Antoine Pitrou244651a2009-05-04 18:56:13 +00002371 int base64SetO,
2372 int base64WhiteSpace,
Benjamin Peterson29060642009-01-31 22:14:21 +00002373 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002374{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002375 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002376 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00002377 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002378 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002379 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002380 unsigned int base64bits = 0;
2381 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002382 char * out;
2383 char * start;
2384
2385 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00002386 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002387
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00002388 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00002389 return PyErr_NoMemory();
2390
Antoine Pitrou244651a2009-05-04 18:56:13 +00002391 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002392 if (v == NULL)
2393 return NULL;
2394
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002395 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002396 for (;i < size; ++i) {
2397 Py_UNICODE ch = s[i];
2398
Antoine Pitrou244651a2009-05-04 18:56:13 +00002399 if (inShift) {
2400 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
2401 /* shifting out */
2402 if (base64bits) { /* output remaining bits */
2403 *out++ = TO_BASE64(base64buffer << (6-base64bits));
2404 base64buffer = 0;
2405 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002406 }
2407 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002408 /* Characters not in the BASE64 set implicitly unshift the sequence
2409 so no '-' is required, except if the character is itself a '-' */
2410 if (IS_BASE64(ch) || ch == '-') {
2411 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002412 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002413 *out++ = (char) ch;
2414 }
2415 else {
2416 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00002417 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002418 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002419 else { /* not in a shift sequence */
2420 if (ch == '+') {
2421 *out++ = '+';
2422 *out++ = '-';
2423 }
2424 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
2425 *out++ = (char) ch;
2426 }
2427 else {
2428 *out++ = '+';
2429 inShift = 1;
2430 goto encode_char;
2431 }
2432 }
2433 continue;
2434encode_char:
2435#ifdef Py_UNICODE_WIDE
2436 if (ch >= 0x10000) {
2437 /* code first surrogate */
2438 base64bits += 16;
2439 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
2440 while (base64bits >= 6) {
2441 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
2442 base64bits -= 6;
2443 }
2444 /* prepare second surrogate */
2445 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
2446 }
2447#endif
2448 base64bits += 16;
2449 base64buffer = (base64buffer << 16) | ch;
2450 while (base64bits >= 6) {
2451 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
2452 base64bits -= 6;
2453 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00002454 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002455 if (base64bits)
2456 *out++= TO_BASE64(base64buffer << (6-base64bits) );
2457 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002458 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002459 if (_PyBytes_Resize(&v, out - start) < 0)
2460 return NULL;
2461 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002462}
2463
Antoine Pitrou244651a2009-05-04 18:56:13 +00002464#undef IS_BASE64
2465#undef FROM_BASE64
2466#undef TO_BASE64
2467#undef DECODE_DIRECT
2468#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002469
Guido van Rossumd57fd912000-03-10 22:53:23 +00002470/* --- UTF-8 Codec -------------------------------------------------------- */
2471
Tim Petersced69f82003-09-16 20:30:58 +00002472static
Guido van Rossumd57fd912000-03-10 22:53:23 +00002473char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00002474 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
2475 illegal prefix. See RFC 3629 for details */
2476 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
2477 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002478 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00002479 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2480 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2481 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2482 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00002483 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
2484 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 +00002485 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2486 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00002487 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
2488 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
2489 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
2490 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
2491 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 +00002492};
2493
Guido van Rossumd57fd912000-03-10 22:53:23 +00002494PyObject *PyUnicode_DecodeUTF8(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002495 Py_ssize_t size,
2496 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002497{
Walter Dörwald69652032004-09-07 20:24:22 +00002498 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
2499}
2500
Antoine Pitrouab868312009-01-10 15:40:25 +00002501/* Mask to check or force alignment of a pointer to C 'long' boundaries */
2502#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
2503
2504/* Mask to quickly check whether a C 'long' contains a
2505 non-ASCII, UTF8-encoded char. */
2506#if (SIZEOF_LONG == 8)
2507# define ASCII_CHAR_MASK 0x8080808080808080L
2508#elif (SIZEOF_LONG == 4)
2509# define ASCII_CHAR_MASK 0x80808080L
2510#else
2511# error C 'long' size should be either 4 or 8!
2512#endif
2513
Walter Dörwald69652032004-09-07 20:24:22 +00002514PyObject *PyUnicode_DecodeUTF8Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002515 Py_ssize_t size,
2516 const char *errors,
2517 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00002518{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002519 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002520 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00002521 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002522 Py_ssize_t startinpos;
2523 Py_ssize_t endinpos;
2524 Py_ssize_t outpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00002525 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002526 PyUnicodeObject *unicode;
2527 Py_UNICODE *p;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002528 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002529 PyObject *errorHandler = NULL;
2530 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002531
2532 /* Note: size will always be longer than the resulting Unicode
2533 character count */
2534 unicode = _PyUnicode_New(size);
2535 if (!unicode)
2536 return NULL;
Walter Dörwald69652032004-09-07 20:24:22 +00002537 if (size == 0) {
2538 if (consumed)
2539 *consumed = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002540 return (PyObject *)unicode;
Walter Dörwald69652032004-09-07 20:24:22 +00002541 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002542
2543 /* Unpack UTF-8 encoded data */
2544 p = unicode->str;
2545 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00002546 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002547
2548 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002549 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002550
2551 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00002552 /* Fast path for runs of ASCII characters. Given that common UTF-8
2553 input will consist of an overwhelming majority of ASCII
2554 characters, we try to optimize for this case by checking
2555 as many characters as a C 'long' can contain.
2556 First, check if we can do an aligned read, as most CPUs have
2557 a penalty for unaligned reads.
2558 */
2559 if (!((size_t) s & LONG_PTR_MASK)) {
2560 /* Help register allocation */
2561 register const char *_s = s;
2562 register Py_UNICODE *_p = p;
2563 while (_s < aligned_end) {
2564 /* Read a whole long at a time (either 4 or 8 bytes),
2565 and do a fast unrolled copy if it only contains ASCII
2566 characters. */
2567 unsigned long data = *(unsigned long *) _s;
2568 if (data & ASCII_CHAR_MASK)
2569 break;
2570 _p[0] = (unsigned char) _s[0];
2571 _p[1] = (unsigned char) _s[1];
2572 _p[2] = (unsigned char) _s[2];
2573 _p[3] = (unsigned char) _s[3];
2574#if (SIZEOF_LONG == 8)
2575 _p[4] = (unsigned char) _s[4];
2576 _p[5] = (unsigned char) _s[5];
2577 _p[6] = (unsigned char) _s[6];
2578 _p[7] = (unsigned char) _s[7];
2579#endif
2580 _s += SIZEOF_LONG;
2581 _p += SIZEOF_LONG;
2582 }
2583 s = _s;
2584 p = _p;
2585 if (s == e)
2586 break;
2587 ch = (unsigned char)*s;
2588 }
2589 }
2590
2591 if (ch < 0x80) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002592 *p++ = (Py_UNICODE)ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002593 s++;
2594 continue;
2595 }
2596
2597 n = utf8_code_length[ch];
2598
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002599 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002600 if (consumed)
2601 break;
2602 else {
2603 errmsg = "unexpected end of data";
2604 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002605 endinpos = startinpos+1;
2606 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
2607 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00002608 goto utf8Error;
2609 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002610 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002611
2612 switch (n) {
2613
2614 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00002615 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002616 startinpos = s-starts;
2617 endinpos = startinpos+1;
2618 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002619
2620 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002621 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00002622 startinpos = s-starts;
2623 endinpos = startinpos+1;
2624 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002625
2626 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002627 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00002628 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002629 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002630 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00002631 goto utf8Error;
2632 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002633 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00002634 assert ((ch > 0x007F) && (ch <= 0x07FF));
2635 *p++ = (Py_UNICODE)ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002636 break;
2637
2638 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00002639 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
2640 will result in surrogates in range d800-dfff. Surrogates are
2641 not valid UTF-8 so they are rejected.
2642 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
2643 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00002644 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00002645 (s[2] & 0xc0) != 0x80 ||
2646 ((unsigned char)s[0] == 0xE0 &&
2647 (unsigned char)s[1] < 0xA0) ||
2648 ((unsigned char)s[0] == 0xED &&
2649 (unsigned char)s[1] > 0x9F)) {
2650 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002651 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002652 endinpos = startinpos + 1;
2653
2654 /* if s[1] first two bits are 1 and 0, then the invalid
2655 continuation byte is s[2], so increment endinpos by 1,
2656 if not, s[1] is invalid and endinpos doesn't need to
2657 be incremented. */
2658 if ((s[1] & 0xC0) == 0x80)
2659 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00002660 goto utf8Error;
2661 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002662 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00002663 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
2664 *p++ = (Py_UNICODE)ch;
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002665 break;
2666
2667 case 4:
2668 if ((s[1] & 0xc0) != 0x80 ||
2669 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00002670 (s[3] & 0xc0) != 0x80 ||
2671 ((unsigned char)s[0] == 0xF0 &&
2672 (unsigned char)s[1] < 0x90) ||
2673 ((unsigned char)s[0] == 0xF4 &&
2674 (unsigned char)s[1] > 0x8F)) {
2675 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002676 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002677 endinpos = startinpos + 1;
2678 if ((s[1] & 0xC0) == 0x80) {
2679 endinpos++;
2680 if ((s[2] & 0xC0) == 0x80)
2681 endinpos++;
2682 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002683 goto utf8Error;
2684 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002685 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00002686 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
2687 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
2688
Fredrik Lundh8f455852001-06-27 18:59:43 +00002689#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00002690 *p++ = (Py_UNICODE)ch;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002691#else
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002692 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00002693
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002694 /* translate from 10000..10FFFF to 0..FFFF */
2695 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00002696
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002697 /* high surrogate = top 10 bits added to D800 */
2698 *p++ = (Py_UNICODE)(0xD800 + (ch >> 10));
Tim Petersced69f82003-09-16 20:30:58 +00002699
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002700 /* low surrogate = bottom 10 bits added to DC00 */
Fredrik Lundh45714e92001-06-26 16:39:36 +00002701 *p++ = (Py_UNICODE)(0xDC00 + (ch & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002702#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00002703 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002704 }
2705 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00002706 continue;
Tim Petersced69f82003-09-16 20:30:58 +00002707
Benjamin Peterson29060642009-01-31 22:14:21 +00002708 utf8Error:
2709 outpos = p-PyUnicode_AS_UNICODE(unicode);
2710 if (unicode_decode_call_errorhandler(
2711 errors, &errorHandler,
2712 "utf8", errmsg,
2713 &starts, &e, &startinpos, &endinpos, &exc, &s,
2714 &unicode, &outpos, &p))
2715 goto onError;
2716 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002717 }
Walter Dörwald69652032004-09-07 20:24:22 +00002718 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00002719 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002720
2721 /* Adjust length */
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00002722 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002723 goto onError;
2724
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002725 Py_XDECREF(errorHandler);
2726 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002727 return (PyObject *)unicode;
2728
Benjamin Peterson29060642009-01-31 22:14:21 +00002729 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002730 Py_XDECREF(errorHandler);
2731 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002732 Py_DECREF(unicode);
2733 return NULL;
2734}
2735
Antoine Pitrouab868312009-01-10 15:40:25 +00002736#undef ASCII_CHAR_MASK
2737
Victor Stinnerf933e1a2010-10-20 22:58:25 +00002738#ifdef __APPLE__
2739
2740/* Simplified UTF-8 decoder using surrogateescape error handler,
2741 used to decode the command line arguments on Mac OS X. */
2742
2743wchar_t*
2744_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
2745{
2746 int n;
2747 const char *e;
2748 wchar_t *unicode, *p;
2749
2750 /* Note: size will always be longer than the resulting Unicode
2751 character count */
2752 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
2753 PyErr_NoMemory();
2754 return NULL;
2755 }
2756 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
2757 if (!unicode)
2758 return NULL;
2759
2760 /* Unpack UTF-8 encoded data */
2761 p = unicode;
2762 e = s + size;
2763 while (s < e) {
2764 Py_UCS4 ch = (unsigned char)*s;
2765
2766 if (ch < 0x80) {
2767 *p++ = (wchar_t)ch;
2768 s++;
2769 continue;
2770 }
2771
2772 n = utf8_code_length[ch];
2773 if (s + n > e) {
2774 goto surrogateescape;
2775 }
2776
2777 switch (n) {
2778 case 0:
2779 case 1:
2780 goto surrogateescape;
2781
2782 case 2:
2783 if ((s[1] & 0xc0) != 0x80)
2784 goto surrogateescape;
2785 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
2786 assert ((ch > 0x007F) && (ch <= 0x07FF));
2787 *p++ = (wchar_t)ch;
2788 break;
2789
2790 case 3:
2791 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
2792 will result in surrogates in range d800-dfff. Surrogates are
2793 not valid UTF-8 so they are rejected.
2794 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
2795 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
2796 if ((s[1] & 0xc0) != 0x80 ||
2797 (s[2] & 0xc0) != 0x80 ||
2798 ((unsigned char)s[0] == 0xE0 &&
2799 (unsigned char)s[1] < 0xA0) ||
2800 ((unsigned char)s[0] == 0xED &&
2801 (unsigned char)s[1] > 0x9F)) {
2802
2803 goto surrogateescape;
2804 }
2805 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
2806 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
2807 *p++ = (Py_UNICODE)ch;
2808 break;
2809
2810 case 4:
2811 if ((s[1] & 0xc0) != 0x80 ||
2812 (s[2] & 0xc0) != 0x80 ||
2813 (s[3] & 0xc0) != 0x80 ||
2814 ((unsigned char)s[0] == 0xF0 &&
2815 (unsigned char)s[1] < 0x90) ||
2816 ((unsigned char)s[0] == 0xF4 &&
2817 (unsigned char)s[1] > 0x8F)) {
2818 goto surrogateescape;
2819 }
2820 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
2821 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
2822 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
2823
2824#if SIZEOF_WCHAR_T == 4
2825 *p++ = (wchar_t)ch;
2826#else
2827 /* compute and append the two surrogates: */
2828
2829 /* translate from 10000..10FFFF to 0..FFFF */
2830 ch -= 0x10000;
2831
2832 /* high surrogate = top 10 bits added to D800 */
2833 *p++ = (wchar_t)(0xD800 + (ch >> 10));
2834
2835 /* low surrogate = bottom 10 bits added to DC00 */
2836 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
2837#endif
2838 break;
2839 }
2840 s += n;
2841 continue;
2842
2843 surrogateescape:
2844 *p++ = 0xDC00 + ch;
2845 s++;
2846 }
2847 *p = L'\0';
2848 return unicode;
2849}
2850
2851#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00002852
Tim Peters602f7402002-04-27 18:03:26 +00002853/* Allocation strategy: if the string is short, convert into a stack buffer
2854 and allocate exactly as much space needed at the end. Else allocate the
2855 maximum possible needed (4 result bytes per Unicode character), and return
2856 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002857*/
Tim Peters7e3d9612002-04-21 03:26:37 +00002858PyObject *
2859PyUnicode_EncodeUTF8(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002860 Py_ssize_t size,
2861 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002862{
Tim Peters602f7402002-04-27 18:03:26 +00002863#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00002864
Guido van Rossum98297ee2007-11-06 21:34:58 +00002865 Py_ssize_t i; /* index into s of next input byte */
2866 PyObject *result; /* result string object */
2867 char *p; /* next free byte in output buffer */
2868 Py_ssize_t nallocated; /* number of result bytes allocated */
2869 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00002870 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002871 PyObject *errorHandler = NULL;
2872 PyObject *exc = NULL;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00002873
Tim Peters602f7402002-04-27 18:03:26 +00002874 assert(s != NULL);
2875 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002876
Tim Peters602f7402002-04-27 18:03:26 +00002877 if (size <= MAX_SHORT_UNICHARS) {
2878 /* Write into the stack buffer; nallocated can't overflow.
2879 * At the end, we'll allocate exactly as much heap space as it
2880 * turns out we need.
2881 */
2882 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002883 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00002884 p = stackbuf;
2885 }
2886 else {
2887 /* Overallocate on the heap, and give the excess back at the end. */
2888 nallocated = size * 4;
2889 if (nallocated / 4 != size) /* overflow! */
2890 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00002891 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002892 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00002893 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00002894 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00002895 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002896
Tim Peters602f7402002-04-27 18:03:26 +00002897 for (i = 0; i < size;) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002898 Py_UCS4 ch = s[i++];
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002899
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002900 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00002901 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002902 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002903
Guido van Rossumd57fd912000-03-10 22:53:23 +00002904 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00002905 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00002906 *p++ = (char)(0xc0 | (ch >> 6));
2907 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00002908 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002909#ifndef Py_UNICODE_WIDE
Victor Stinner31be90b2010-04-22 19:38:16 +00002910 /* Special case: check for high and low surrogate */
2911 if (ch <= 0xDBFF && i != size && 0xDC00 <= s[i] && s[i] <= 0xDFFF) {
2912 Py_UCS4 ch2 = s[i];
2913 /* Combine the two surrogates to form a UCS4 value */
2914 ch = ((ch - 0xD800) << 10 | (ch2 - 0xDC00)) + 0x10000;
2915 i++;
2916
2917 /* Encode UCS4 Unicode ordinals */
2918 *p++ = (char)(0xf0 | (ch >> 18));
2919 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
Tim Peters602f7402002-04-27 18:03:26 +00002920 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2921 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00002922 } else {
Victor Stinner445a6232010-04-22 20:01:57 +00002923#endif
Victor Stinner31be90b2010-04-22 19:38:16 +00002924 Py_ssize_t newpos;
2925 PyObject *rep;
2926 Py_ssize_t repsize, k;
2927 rep = unicode_encode_call_errorhandler
2928 (errors, &errorHandler, "utf-8", "surrogates not allowed",
2929 s, size, &exc, i-1, i, &newpos);
2930 if (!rep)
2931 goto error;
2932
2933 if (PyBytes_Check(rep))
2934 repsize = PyBytes_GET_SIZE(rep);
2935 else
2936 repsize = PyUnicode_GET_SIZE(rep);
2937
2938 if (repsize > 4) {
2939 Py_ssize_t offset;
2940
2941 if (result == NULL)
2942 offset = p - stackbuf;
2943 else
2944 offset = p - PyBytes_AS_STRING(result);
2945
2946 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
2947 /* integer overflow */
2948 PyErr_NoMemory();
2949 goto error;
2950 }
2951 nallocated += repsize - 4;
2952 if (result != NULL) {
2953 if (_PyBytes_Resize(&result, nallocated) < 0)
2954 goto error;
2955 } else {
2956 result = PyBytes_FromStringAndSize(NULL, nallocated);
2957 if (result == NULL)
2958 goto error;
2959 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
2960 }
2961 p = PyBytes_AS_STRING(result) + offset;
2962 }
2963
2964 if (PyBytes_Check(rep)) {
2965 char *prep = PyBytes_AS_STRING(rep);
2966 for(k = repsize; k > 0; k--)
2967 *p++ = *prep++;
2968 } else /* rep is unicode */ {
2969 Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
2970 Py_UNICODE c;
2971
2972 for(k=0; k<repsize; k++) {
2973 c = prep[k];
2974 if (0x80 <= c) {
2975 raise_encode_exception(&exc, "utf-8", s, size,
2976 i-1, i, "surrogates not allowed");
2977 goto error;
2978 }
2979 *p++ = (char)prep[k];
2980 }
2981 }
2982 Py_DECREF(rep);
Victor Stinner445a6232010-04-22 20:01:57 +00002983#ifndef Py_UNICODE_WIDE
Victor Stinner31be90b2010-04-22 19:38:16 +00002984 }
Victor Stinner445a6232010-04-22 20:01:57 +00002985#endif
Victor Stinner31be90b2010-04-22 19:38:16 +00002986 } else if (ch < 0x10000) {
2987 *p++ = (char)(0xe0 | (ch >> 12));
2988 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2989 *p++ = (char)(0x80 | (ch & 0x3f));
2990 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00002991 /* Encode UCS4 Unicode ordinals */
2992 *p++ = (char)(0xf0 | (ch >> 18));
2993 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
2994 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2995 *p++ = (char)(0x80 | (ch & 0x3f));
2996 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002997 }
Tim Peters0eca65c2002-04-21 17:28:06 +00002998
Guido van Rossum98297ee2007-11-06 21:34:58 +00002999 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00003000 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003001 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00003002 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00003003 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00003004 }
3005 else {
Christian Heimesf3863112007-11-22 07:46:41 +00003006 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00003007 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00003008 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00003009 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00003010 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00003011 Py_XDECREF(errorHandler);
3012 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003013 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00003014 error:
3015 Py_XDECREF(errorHandler);
3016 Py_XDECREF(exc);
3017 Py_XDECREF(result);
3018 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00003019
Tim Peters602f7402002-04-27 18:03:26 +00003020#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00003021}
3022
Guido van Rossumd57fd912000-03-10 22:53:23 +00003023PyObject *PyUnicode_AsUTF8String(PyObject *unicode)
3024{
Guido van Rossumd57fd912000-03-10 22:53:23 +00003025 if (!PyUnicode_Check(unicode)) {
3026 PyErr_BadArgument();
3027 return NULL;
3028 }
Barry Warsaw2dd4abf2000-08-18 06:58:15 +00003029 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003030 PyUnicode_GET_SIZE(unicode),
3031 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003032}
3033
Walter Dörwald41980ca2007-08-16 21:55:45 +00003034/* --- UTF-32 Codec ------------------------------------------------------- */
3035
3036PyObject *
3037PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003038 Py_ssize_t size,
3039 const char *errors,
3040 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00003041{
3042 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
3043}
3044
3045PyObject *
3046PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003047 Py_ssize_t size,
3048 const char *errors,
3049 int *byteorder,
3050 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00003051{
3052 const char *starts = s;
3053 Py_ssize_t startinpos;
3054 Py_ssize_t endinpos;
3055 Py_ssize_t outpos;
3056 PyUnicodeObject *unicode;
3057 Py_UNICODE *p;
3058#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00003059 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00003060 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003061#else
3062 const int pairs = 0;
3063#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00003064 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003065 int bo = 0; /* assume native ordering by default */
3066 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00003067 /* Offsets from q for retrieving bytes in the right order. */
3068#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3069 int iorder[] = {0, 1, 2, 3};
3070#else
3071 int iorder[] = {3, 2, 1, 0};
3072#endif
3073 PyObject *errorHandler = NULL;
3074 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00003075
Walter Dörwald41980ca2007-08-16 21:55:45 +00003076 q = (unsigned char *)s;
3077 e = q + size;
3078
3079 if (byteorder)
3080 bo = *byteorder;
3081
3082 /* Check for BOM marks (U+FEFF) in the input and adjust current
3083 byte order setting accordingly. In native mode, the leading BOM
3084 mark is skipped, in all other modes, it is copied to the output
3085 stream as-is (giving a ZWNBSP character). */
3086 if (bo == 0) {
3087 if (size >= 4) {
3088 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00003089 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00003090#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00003091 if (bom == 0x0000FEFF) {
3092 q += 4;
3093 bo = -1;
3094 }
3095 else if (bom == 0xFFFE0000) {
3096 q += 4;
3097 bo = 1;
3098 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003099#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003100 if (bom == 0x0000FEFF) {
3101 q += 4;
3102 bo = 1;
3103 }
3104 else if (bom == 0xFFFE0000) {
3105 q += 4;
3106 bo = -1;
3107 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003108#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003109 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003110 }
3111
3112 if (bo == -1) {
3113 /* force LE */
3114 iorder[0] = 0;
3115 iorder[1] = 1;
3116 iorder[2] = 2;
3117 iorder[3] = 3;
3118 }
3119 else if (bo == 1) {
3120 /* force BE */
3121 iorder[0] = 3;
3122 iorder[1] = 2;
3123 iorder[2] = 1;
3124 iorder[3] = 0;
3125 }
3126
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00003127 /* On narrow builds we split characters outside the BMP into two
3128 codepoints => count how much extra space we need. */
3129#ifndef Py_UNICODE_WIDE
3130 for (qq = q; qq < e; qq += 4)
3131 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
3132 pairs++;
3133#endif
3134
3135 /* This might be one to much, because of a BOM */
3136 unicode = _PyUnicode_New((size+3)/4+pairs);
3137 if (!unicode)
3138 return NULL;
3139 if (size == 0)
3140 return (PyObject *)unicode;
3141
3142 /* Unpack UTF-32 encoded data */
3143 p = unicode->str;
3144
Walter Dörwald41980ca2007-08-16 21:55:45 +00003145 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003146 Py_UCS4 ch;
3147 /* remaining bytes at the end? (size should be divisible by 4) */
3148 if (e-q<4) {
3149 if (consumed)
3150 break;
3151 errmsg = "truncated data";
3152 startinpos = ((const char *)q)-starts;
3153 endinpos = ((const char *)e)-starts;
3154 goto utf32Error;
3155 /* The remaining input chars are ignored if the callback
3156 chooses to skip the input */
3157 }
3158 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
3159 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00003160
Benjamin Peterson29060642009-01-31 22:14:21 +00003161 if (ch >= 0x110000)
3162 {
3163 errmsg = "codepoint not in range(0x110000)";
3164 startinpos = ((const char *)q)-starts;
3165 endinpos = startinpos+4;
3166 goto utf32Error;
3167 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003168#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003169 if (ch >= 0x10000)
3170 {
3171 *p++ = 0xD800 | ((ch-0x10000) >> 10);
3172 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
3173 }
3174 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00003175#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003176 *p++ = ch;
3177 q += 4;
3178 continue;
3179 utf32Error:
3180 outpos = p-PyUnicode_AS_UNICODE(unicode);
3181 if (unicode_decode_call_errorhandler(
3182 errors, &errorHandler,
3183 "utf32", errmsg,
3184 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
3185 &unicode, &outpos, &p))
3186 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003187 }
3188
3189 if (byteorder)
3190 *byteorder = bo;
3191
3192 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00003193 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003194
3195 /* Adjust length */
3196 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
3197 goto onError;
3198
3199 Py_XDECREF(errorHandler);
3200 Py_XDECREF(exc);
3201 return (PyObject *)unicode;
3202
Benjamin Peterson29060642009-01-31 22:14:21 +00003203 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00003204 Py_DECREF(unicode);
3205 Py_XDECREF(errorHandler);
3206 Py_XDECREF(exc);
3207 return NULL;
3208}
3209
3210PyObject *
3211PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003212 Py_ssize_t size,
3213 const char *errors,
3214 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00003215{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003216 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003217 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003218 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003219#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003220 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003221#else
3222 const int pairs = 0;
3223#endif
3224 /* Offsets from p for storing byte pairs in the right order. */
3225#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3226 int iorder[] = {0, 1, 2, 3};
3227#else
3228 int iorder[] = {3, 2, 1, 0};
3229#endif
3230
Benjamin Peterson29060642009-01-31 22:14:21 +00003231#define STORECHAR(CH) \
3232 do { \
3233 p[iorder[3]] = ((CH) >> 24) & 0xff; \
3234 p[iorder[2]] = ((CH) >> 16) & 0xff; \
3235 p[iorder[1]] = ((CH) >> 8) & 0xff; \
3236 p[iorder[0]] = (CH) & 0xff; \
3237 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00003238 } while(0)
3239
3240 /* In narrow builds we can output surrogate pairs as one codepoint,
3241 so we need less space. */
3242#ifndef Py_UNICODE_WIDE
3243 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00003244 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
3245 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
3246 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003247#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003248 nsize = (size - pairs + (byteorder == 0));
3249 bytesize = nsize * 4;
3250 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003251 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003252 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003253 if (v == NULL)
3254 return NULL;
3255
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003256 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003257 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003258 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003259 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00003260 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003261
3262 if (byteorder == -1) {
3263 /* force LE */
3264 iorder[0] = 0;
3265 iorder[1] = 1;
3266 iorder[2] = 2;
3267 iorder[3] = 3;
3268 }
3269 else if (byteorder == 1) {
3270 /* force BE */
3271 iorder[0] = 3;
3272 iorder[1] = 2;
3273 iorder[2] = 1;
3274 iorder[3] = 0;
3275 }
3276
3277 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003278 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003279#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003280 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
3281 Py_UCS4 ch2 = *s;
3282 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
3283 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
3284 s++;
3285 size--;
3286 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00003287 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003288#endif
3289 STORECHAR(ch);
3290 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003291
3292 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003293 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003294#undef STORECHAR
3295}
3296
3297PyObject *PyUnicode_AsUTF32String(PyObject *unicode)
3298{
3299 if (!PyUnicode_Check(unicode)) {
3300 PyErr_BadArgument();
3301 return NULL;
3302 }
3303 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003304 PyUnicode_GET_SIZE(unicode),
3305 NULL,
3306 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003307}
3308
Guido van Rossumd57fd912000-03-10 22:53:23 +00003309/* --- UTF-16 Codec ------------------------------------------------------- */
3310
Tim Peters772747b2001-08-09 22:21:55 +00003311PyObject *
3312PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003313 Py_ssize_t size,
3314 const char *errors,
3315 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003316{
Walter Dörwald69652032004-09-07 20:24:22 +00003317 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
3318}
3319
Antoine Pitrouab868312009-01-10 15:40:25 +00003320/* Two masks for fast checking of whether a C 'long' may contain
3321 UTF16-encoded surrogate characters. This is an efficient heuristic,
3322 assuming that non-surrogate characters with a code point >= 0x8000 are
3323 rare in most input.
3324 FAST_CHAR_MASK is used when the input is in native byte ordering,
3325 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00003326*/
Antoine Pitrouab868312009-01-10 15:40:25 +00003327#if (SIZEOF_LONG == 8)
3328# define FAST_CHAR_MASK 0x8000800080008000L
3329# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
3330#elif (SIZEOF_LONG == 4)
3331# define FAST_CHAR_MASK 0x80008000L
3332# define SWAPPED_FAST_CHAR_MASK 0x00800080L
3333#else
3334# error C 'long' size should be either 4 or 8!
3335#endif
3336
Walter Dörwald69652032004-09-07 20:24:22 +00003337PyObject *
3338PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003339 Py_ssize_t size,
3340 const char *errors,
3341 int *byteorder,
3342 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00003343{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003344 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003345 Py_ssize_t startinpos;
3346 Py_ssize_t endinpos;
3347 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003348 PyUnicodeObject *unicode;
3349 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00003350 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00003351 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00003352 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003353 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00003354 /* Offsets from q for retrieving byte pairs in the right order. */
3355#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3356 int ihi = 1, ilo = 0;
3357#else
3358 int ihi = 0, ilo = 1;
3359#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003360 PyObject *errorHandler = NULL;
3361 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003362
3363 /* Note: size will always be longer than the resulting Unicode
3364 character count */
3365 unicode = _PyUnicode_New(size);
3366 if (!unicode)
3367 return NULL;
3368 if (size == 0)
3369 return (PyObject *)unicode;
3370
3371 /* Unpack UTF-16 encoded data */
3372 p = unicode->str;
Tim Peters772747b2001-08-09 22:21:55 +00003373 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00003374 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003375
3376 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00003377 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003378
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003379 /* Check for BOM marks (U+FEFF) in the input and adjust current
3380 byte order setting accordingly. In native mode, the leading BOM
3381 mark is skipped, in all other modes, it is copied to the output
3382 stream as-is (giving a ZWNBSP character). */
3383 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00003384 if (size >= 2) {
3385 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003386#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00003387 if (bom == 0xFEFF) {
3388 q += 2;
3389 bo = -1;
3390 }
3391 else if (bom == 0xFFFE) {
3392 q += 2;
3393 bo = 1;
3394 }
Tim Petersced69f82003-09-16 20:30:58 +00003395#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003396 if (bom == 0xFEFF) {
3397 q += 2;
3398 bo = 1;
3399 }
3400 else if (bom == 0xFFFE) {
3401 q += 2;
3402 bo = -1;
3403 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003404#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003405 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003406 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003407
Tim Peters772747b2001-08-09 22:21:55 +00003408 if (bo == -1) {
3409 /* force LE */
3410 ihi = 1;
3411 ilo = 0;
3412 }
3413 else if (bo == 1) {
3414 /* force BE */
3415 ihi = 0;
3416 ilo = 1;
3417 }
Antoine Pitrouab868312009-01-10 15:40:25 +00003418#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3419 native_ordering = ilo < ihi;
3420#else
3421 native_ordering = ilo > ihi;
3422#endif
Tim Peters772747b2001-08-09 22:21:55 +00003423
Antoine Pitrouab868312009-01-10 15:40:25 +00003424 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00003425 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003426 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00003427 /* First check for possible aligned read of a C 'long'. Unaligned
3428 reads are more expensive, better to defer to another iteration. */
3429 if (!((size_t) q & LONG_PTR_MASK)) {
3430 /* Fast path for runs of non-surrogate chars. */
3431 register const unsigned char *_q = q;
3432 Py_UNICODE *_p = p;
3433 if (native_ordering) {
3434 /* Native ordering is simple: as long as the input cannot
3435 possibly contain a surrogate char, do an unrolled copy
3436 of several 16-bit code points to the target object.
3437 The non-surrogate check is done on several input bytes
3438 at a time (as many as a C 'long' can contain). */
3439 while (_q < aligned_end) {
3440 unsigned long data = * (unsigned long *) _q;
3441 if (data & FAST_CHAR_MASK)
3442 break;
3443 _p[0] = ((unsigned short *) _q)[0];
3444 _p[1] = ((unsigned short *) _q)[1];
3445#if (SIZEOF_LONG == 8)
3446 _p[2] = ((unsigned short *) _q)[2];
3447 _p[3] = ((unsigned short *) _q)[3];
3448#endif
3449 _q += SIZEOF_LONG;
3450 _p += SIZEOF_LONG / 2;
3451 }
3452 }
3453 else {
3454 /* Byteswapped ordering is similar, but we must decompose
3455 the copy bytewise, and take care of zero'ing out the
3456 upper bytes if the target object is in 32-bit units
3457 (that is, in UCS-4 builds). */
3458 while (_q < aligned_end) {
3459 unsigned long data = * (unsigned long *) _q;
3460 if (data & SWAPPED_FAST_CHAR_MASK)
3461 break;
3462 /* Zero upper bytes in UCS-4 builds */
3463#if (Py_UNICODE_SIZE > 2)
3464 _p[0] = 0;
3465 _p[1] = 0;
3466#if (SIZEOF_LONG == 8)
3467 _p[2] = 0;
3468 _p[3] = 0;
3469#endif
3470#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00003471 /* Issue #4916; UCS-4 builds on big endian machines must
3472 fill the two last bytes of each 4-byte unit. */
3473#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
3474# define OFF 2
3475#else
3476# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00003477#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00003478 ((unsigned char *) _p)[OFF + 1] = _q[0];
3479 ((unsigned char *) _p)[OFF + 0] = _q[1];
3480 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
3481 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
3482#if (SIZEOF_LONG == 8)
3483 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
3484 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
3485 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
3486 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
3487#endif
3488#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00003489 _q += SIZEOF_LONG;
3490 _p += SIZEOF_LONG / 2;
3491 }
3492 }
3493 p = _p;
3494 q = _q;
3495 if (q >= e)
3496 break;
3497 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003498 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003499
Benjamin Peterson14339b62009-01-31 16:36:08 +00003500 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00003501
3502 if (ch < 0xD800 || ch > 0xDFFF) {
3503 *p++ = ch;
3504 continue;
3505 }
3506
3507 /* UTF-16 code pair: */
3508 if (q > e) {
3509 errmsg = "unexpected end of data";
3510 startinpos = (((const char *)q) - 2) - starts;
3511 endinpos = ((const char *)e) + 1 - starts;
3512 goto utf16Error;
3513 }
3514 if (0xD800 <= ch && ch <= 0xDBFF) {
3515 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
3516 q += 2;
3517 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00003518#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003519 *p++ = ch;
3520 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003521#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003522 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003523#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003524 continue;
3525 }
3526 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003527 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00003528 startinpos = (((const char *)q)-4)-starts;
3529 endinpos = startinpos+2;
3530 goto utf16Error;
3531 }
3532
Benjamin Peterson14339b62009-01-31 16:36:08 +00003533 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003534 errmsg = "illegal encoding";
3535 startinpos = (((const char *)q)-2)-starts;
3536 endinpos = startinpos+2;
3537 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003538
Benjamin Peterson29060642009-01-31 22:14:21 +00003539 utf16Error:
3540 outpos = p - PyUnicode_AS_UNICODE(unicode);
3541 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00003542 errors,
3543 &errorHandler,
3544 "utf16", errmsg,
3545 &starts,
3546 (const char **)&e,
3547 &startinpos,
3548 &endinpos,
3549 &exc,
3550 (const char **)&q,
3551 &unicode,
3552 &outpos,
3553 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00003554 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003555 }
Antoine Pitrouab868312009-01-10 15:40:25 +00003556 /* remaining byte at the end? (size should be even) */
3557 if (e == q) {
3558 if (!consumed) {
3559 errmsg = "truncated data";
3560 startinpos = ((const char *)q) - starts;
3561 endinpos = ((const char *)e) + 1 - starts;
3562 outpos = p - PyUnicode_AS_UNICODE(unicode);
3563 if (unicode_decode_call_errorhandler(
3564 errors,
3565 &errorHandler,
3566 "utf16", errmsg,
3567 &starts,
3568 (const char **)&e,
3569 &startinpos,
3570 &endinpos,
3571 &exc,
3572 (const char **)&q,
3573 &unicode,
3574 &outpos,
3575 &p))
3576 goto onError;
3577 /* The remaining input chars are ignored if the callback
3578 chooses to skip the input */
3579 }
3580 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003581
3582 if (byteorder)
3583 *byteorder = bo;
3584
Walter Dörwald69652032004-09-07 20:24:22 +00003585 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00003586 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00003587
Guido van Rossumd57fd912000-03-10 22:53:23 +00003588 /* Adjust length */
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00003589 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003590 goto onError;
3591
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003592 Py_XDECREF(errorHandler);
3593 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003594 return (PyObject *)unicode;
3595
Benjamin Peterson29060642009-01-31 22:14:21 +00003596 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003597 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003598 Py_XDECREF(errorHandler);
3599 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003600 return NULL;
3601}
3602
Antoine Pitrouab868312009-01-10 15:40:25 +00003603#undef FAST_CHAR_MASK
3604#undef SWAPPED_FAST_CHAR_MASK
3605
Tim Peters772747b2001-08-09 22:21:55 +00003606PyObject *
3607PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003608 Py_ssize_t size,
3609 const char *errors,
3610 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003611{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003612 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00003613 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003614 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003615#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003616 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003617#else
3618 const int pairs = 0;
3619#endif
Tim Peters772747b2001-08-09 22:21:55 +00003620 /* Offsets from p for storing byte pairs in the right order. */
3621#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3622 int ihi = 1, ilo = 0;
3623#else
3624 int ihi = 0, ilo = 1;
3625#endif
3626
Benjamin Peterson29060642009-01-31 22:14:21 +00003627#define STORECHAR(CH) \
3628 do { \
3629 p[ihi] = ((CH) >> 8) & 0xff; \
3630 p[ilo] = (CH) & 0xff; \
3631 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00003632 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003633
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003634#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003635 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00003636 if (s[i] >= 0x10000)
3637 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003638#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003639 /* 2 * (size + pairs + (byteorder == 0)) */
3640 if (size > PY_SSIZE_T_MAX ||
3641 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00003642 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003643 nsize = size + pairs + (byteorder == 0);
3644 bytesize = nsize * 2;
3645 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003646 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003647 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003648 if (v == NULL)
3649 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003650
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003651 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003652 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003653 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00003654 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00003655 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00003656
3657 if (byteorder == -1) {
3658 /* force LE */
3659 ihi = 1;
3660 ilo = 0;
3661 }
3662 else if (byteorder == 1) {
3663 /* force BE */
3664 ihi = 0;
3665 ilo = 1;
3666 }
3667
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003668 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003669 Py_UNICODE ch = *s++;
3670 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003671#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003672 if (ch >= 0x10000) {
3673 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
3674 ch = 0xD800 | ((ch-0x10000) >> 10);
3675 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003676#endif
Tim Peters772747b2001-08-09 22:21:55 +00003677 STORECHAR(ch);
3678 if (ch2)
3679 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003680 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003681
3682 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003683 return v;
Tim Peters772747b2001-08-09 22:21:55 +00003684#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00003685}
3686
3687PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
3688{
3689 if (!PyUnicode_Check(unicode)) {
3690 PyErr_BadArgument();
3691 return NULL;
3692 }
3693 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003694 PyUnicode_GET_SIZE(unicode),
3695 NULL,
3696 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003697}
3698
3699/* --- Unicode Escape Codec ----------------------------------------------- */
3700
Fredrik Lundh06d12682001-01-24 07:59:11 +00003701static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00003702
Guido van Rossumd57fd912000-03-10 22:53:23 +00003703PyObject *PyUnicode_DecodeUnicodeEscape(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003704 Py_ssize_t size,
3705 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003706{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003707 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003708 Py_ssize_t startinpos;
3709 Py_ssize_t endinpos;
3710 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003711 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003712 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003713 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003714 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003715 char* message;
3716 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003717 PyObject *errorHandler = NULL;
3718 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003719
Guido van Rossumd57fd912000-03-10 22:53:23 +00003720 /* Escaped strings will always be longer than the resulting
3721 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003722 length after conversion to the true value.
3723 (but if the error callback returns a long replacement string
3724 we'll have to allocate more space) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003725 v = _PyUnicode_New(size);
3726 if (v == NULL)
3727 goto onError;
3728 if (size == 0)
3729 return (PyObject *)v;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003730
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003731 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003732 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003733
Guido van Rossumd57fd912000-03-10 22:53:23 +00003734 while (s < end) {
3735 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00003736 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003737 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003738
3739 /* Non-escape characters are interpreted as Unicode ordinals */
3740 if (*s != '\\') {
Fredrik Lundhccc74732001-02-18 22:13:49 +00003741 *p++ = (unsigned char) *s++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003742 continue;
3743 }
3744
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003745 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003746 /* \ - Escapes */
3747 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003748 c = *s++;
3749 if (s > end)
3750 c = '\0'; /* Invalid after \ */
3751 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003752
Benjamin Peterson29060642009-01-31 22:14:21 +00003753 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003754 case '\n': break;
3755 case '\\': *p++ = '\\'; break;
3756 case '\'': *p++ = '\''; break;
3757 case '\"': *p++ = '\"'; break;
3758 case 'b': *p++ = '\b'; break;
3759 case 'f': *p++ = '\014'; break; /* FF */
3760 case 't': *p++ = '\t'; break;
3761 case 'n': *p++ = '\n'; break;
3762 case 'r': *p++ = '\r'; break;
3763 case 'v': *p++ = '\013'; break; /* VT */
3764 case 'a': *p++ = '\007'; break; /* BEL, not classic C */
3765
Benjamin Peterson29060642009-01-31 22:14:21 +00003766 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003767 case '0': case '1': case '2': case '3':
3768 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003769 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003770 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003771 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003772 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003773 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00003774 }
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003775 *p++ = x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003776 break;
3777
Benjamin Peterson29060642009-01-31 22:14:21 +00003778 /* hex escapes */
3779 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003780 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003781 digits = 2;
3782 message = "truncated \\xXX escape";
3783 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003784
Benjamin Peterson29060642009-01-31 22:14:21 +00003785 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003786 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003787 digits = 4;
3788 message = "truncated \\uXXXX escape";
3789 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003790
Benjamin Peterson29060642009-01-31 22:14:21 +00003791 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00003792 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003793 digits = 8;
3794 message = "truncated \\UXXXXXXXX escape";
3795 hexescape:
3796 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003797 outpos = p-PyUnicode_AS_UNICODE(v);
3798 if (s+digits>end) {
3799 endinpos = size;
3800 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003801 errors, &errorHandler,
3802 "unicodeescape", "end of string in escape sequence",
3803 &starts, &end, &startinpos, &endinpos, &exc, &s,
3804 &v, &outpos, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003805 goto onError;
3806 goto nextByte;
3807 }
3808 for (i = 0; i < digits; ++i) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00003809 c = (unsigned char) s[i];
David Malcolm96960882010-11-05 17:23:41 +00003810 if (!Py_ISXDIGIT(c)) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003811 endinpos = (s+i+1)-starts;
3812 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003813 errors, &errorHandler,
3814 "unicodeescape", message,
3815 &starts, &end, &startinpos, &endinpos, &exc, &s,
3816 &v, &outpos, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00003817 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003818 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00003819 }
3820 chr = (chr<<4) & ~0xF;
3821 if (c >= '0' && c <= '9')
3822 chr += c - '0';
3823 else if (c >= 'a' && c <= 'f')
3824 chr += 10 + c - 'a';
3825 else
3826 chr += 10 + c - 'A';
3827 }
3828 s += i;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00003829 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003830 /* _decoding_error will have already written into the
3831 target buffer. */
3832 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003833 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00003834 /* when we get here, chr is a 32-bit unicode character */
3835 if (chr <= 0xffff)
3836 /* UCS-2 character */
3837 *p++ = (Py_UNICODE) chr;
3838 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00003839 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00003840 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00003841#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003842 *p++ = chr;
3843#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00003844 chr -= 0x10000L;
3845 *p++ = 0xD800 + (Py_UNICODE) (chr >> 10);
Fredrik Lundh45714e92001-06-26 16:39:36 +00003846 *p++ = 0xDC00 + (Py_UNICODE) (chr & 0x03FF);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003847#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00003848 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003849 endinpos = s-starts;
3850 outpos = p-PyUnicode_AS_UNICODE(v);
3851 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003852 errors, &errorHandler,
3853 "unicodeescape", "illegal Unicode character",
3854 &starts, &end, &startinpos, &endinpos, &exc, &s,
3855 &v, &outpos, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00003856 goto onError;
3857 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00003858 break;
3859
Benjamin Peterson29060642009-01-31 22:14:21 +00003860 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00003861 case 'N':
3862 message = "malformed \\N character escape";
3863 if (ucnhash_CAPI == NULL) {
3864 /* load the unicode data module */
Benjamin Petersonb173f782009-05-05 22:31:58 +00003865 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00003866 if (ucnhash_CAPI == NULL)
3867 goto ucnhashError;
3868 }
3869 if (*s == '{') {
3870 const char *start = s+1;
3871 /* look for the closing brace */
3872 while (*s != '}' && s < end)
3873 s++;
3874 if (s > start && s < end && *s == '}') {
3875 /* found a name. look it up in the unicode database */
3876 message = "unknown Unicode character name";
3877 s++;
Martin v. Löwis480f1bb2006-03-09 23:38:20 +00003878 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1), &chr))
Fredrik Lundhccc74732001-02-18 22:13:49 +00003879 goto store;
3880 }
3881 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003882 endinpos = s-starts;
3883 outpos = p-PyUnicode_AS_UNICODE(v);
3884 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003885 errors, &errorHandler,
3886 "unicodeescape", message,
3887 &starts, &end, &startinpos, &endinpos, &exc, &s,
3888 &v, &outpos, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00003889 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003890 break;
3891
3892 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00003893 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003894 message = "\\ at end of string";
3895 s--;
3896 endinpos = s-starts;
3897 outpos = p-PyUnicode_AS_UNICODE(v);
3898 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003899 errors, &errorHandler,
3900 "unicodeescape", message,
3901 &starts, &end, &startinpos, &endinpos, &exc, &s,
3902 &v, &outpos, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00003903 goto onError;
3904 }
3905 else {
3906 *p++ = '\\';
3907 *p++ = (unsigned char)s[-1];
3908 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00003909 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003910 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003911 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003912 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003913 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003914 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003915 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00003916 Py_XDECREF(errorHandler);
3917 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003918 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00003919
Benjamin Peterson29060642009-01-31 22:14:21 +00003920 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00003921 PyErr_SetString(
3922 PyExc_UnicodeError,
3923 "\\N escapes not supported (can't load unicodedata module)"
3924 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003925 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003926 Py_XDECREF(errorHandler);
3927 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00003928 return NULL;
3929
Benjamin Peterson29060642009-01-31 22:14:21 +00003930 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003931 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003932 Py_XDECREF(errorHandler);
3933 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003934 return NULL;
3935}
3936
3937/* Return a Unicode-Escape string version of the Unicode object.
3938
3939 If quotes is true, the string is enclosed in u"" or u'' quotes as
3940 appropriate.
3941
3942*/
3943
Thomas Wouters477c8d52006-05-27 19:21:47 +00003944Py_LOCAL_INLINE(const Py_UNICODE *) findchar(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003945 Py_ssize_t size,
3946 Py_UNICODE ch)
Thomas Wouters477c8d52006-05-27 19:21:47 +00003947{
3948 /* like wcschr, but doesn't stop at NULL characters */
3949
3950 while (size-- > 0) {
3951 if (*s == ch)
3952 return s;
3953 s++;
3954 }
3955
3956 return NULL;
3957}
Barry Warsaw51ac5802000-03-20 16:36:48 +00003958
Walter Dörwald79e913e2007-05-12 11:08:06 +00003959static const char *hexdigits = "0123456789abcdef";
3960
3961PyObject *PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003962 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003963{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003964 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003965 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003966
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003967#ifdef Py_UNICODE_WIDE
3968 const Py_ssize_t expandsize = 10;
3969#else
3970 const Py_ssize_t expandsize = 6;
3971#endif
3972
Thomas Wouters89f507f2006-12-13 04:49:30 +00003973 /* XXX(nnorwitz): rather than over-allocating, it would be
3974 better to choose a different scheme. Perhaps scan the
3975 first N-chars of the string and allocate based on that size.
3976 */
3977 /* Initial allocation is based on the longest-possible unichr
3978 escape.
3979
3980 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
3981 unichr, so in this case it's the longest unichr escape. In
3982 narrow (UTF-16) builds this is five chars per source unichr
3983 since there are two unichrs in the surrogate pair, so in narrow
3984 (UTF-16) builds it's not the longest unichr escape.
3985
3986 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
3987 so in the narrow (UTF-16) build case it's the longest unichr
3988 escape.
3989 */
3990
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003991 if (size == 0)
3992 return PyBytes_FromStringAndSize(NULL, 0);
3993
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003994 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003995 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003996
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003997 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00003998 2
3999 + expandsize*size
4000 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004001 if (repr == NULL)
4002 return NULL;
4003
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004004 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004005
Guido van Rossumd57fd912000-03-10 22:53:23 +00004006 while (size-- > 0) {
4007 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004008
Walter Dörwald79e913e2007-05-12 11:08:06 +00004009 /* Escape backslashes */
4010 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004011 *p++ = '\\';
4012 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00004013 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004014 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004015
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00004016#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004017 /* Map 21-bit characters to '\U00xxxxxx' */
4018 else if (ch >= 0x10000) {
4019 *p++ = '\\';
4020 *p++ = 'U';
Walter Dörwald79e913e2007-05-12 11:08:06 +00004021 *p++ = hexdigits[(ch >> 28) & 0x0000000F];
4022 *p++ = hexdigits[(ch >> 24) & 0x0000000F];
4023 *p++ = hexdigits[(ch >> 20) & 0x0000000F];
4024 *p++ = hexdigits[(ch >> 16) & 0x0000000F];
4025 *p++ = hexdigits[(ch >> 12) & 0x0000000F];
4026 *p++ = hexdigits[(ch >> 8) & 0x0000000F];
4027 *p++ = hexdigits[(ch >> 4) & 0x0000000F];
4028 *p++ = hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00004029 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004030 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00004031#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004032 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
4033 else if (ch >= 0xD800 && ch < 0xDC00) {
4034 Py_UNICODE ch2;
4035 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00004036
Benjamin Peterson29060642009-01-31 22:14:21 +00004037 ch2 = *s++;
4038 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00004039 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004040 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
4041 *p++ = '\\';
4042 *p++ = 'U';
4043 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
4044 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
4045 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
4046 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
4047 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
4048 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
4049 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
4050 *p++ = hexdigits[ucs & 0x0000000F];
4051 continue;
4052 }
4053 /* Fall through: isolated surrogates are copied as-is */
4054 s--;
4055 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004056 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00004057#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00004058
Guido van Rossumd57fd912000-03-10 22:53:23 +00004059 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00004060 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004061 *p++ = '\\';
4062 *p++ = 'u';
Walter Dörwald79e913e2007-05-12 11:08:06 +00004063 *p++ = hexdigits[(ch >> 12) & 0x000F];
4064 *p++ = hexdigits[(ch >> 8) & 0x000F];
4065 *p++ = hexdigits[(ch >> 4) & 0x000F];
4066 *p++ = hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00004067 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004068
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00004069 /* Map special whitespace to '\t', \n', '\r' */
4070 else if (ch == '\t') {
4071 *p++ = '\\';
4072 *p++ = 't';
4073 }
4074 else if (ch == '\n') {
4075 *p++ = '\\';
4076 *p++ = 'n';
4077 }
4078 else if (ch == '\r') {
4079 *p++ = '\\';
4080 *p++ = 'r';
4081 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004082
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00004083 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00004084 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004085 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00004086 *p++ = 'x';
Walter Dörwald79e913e2007-05-12 11:08:06 +00004087 *p++ = hexdigits[(ch >> 4) & 0x000F];
4088 *p++ = hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00004089 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00004090
Guido van Rossumd57fd912000-03-10 22:53:23 +00004091 /* Copy everything else as-is */
4092 else
4093 *p++ = (char) ch;
4094 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004095
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004096 assert(p - PyBytes_AS_STRING(repr) > 0);
4097 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
4098 return NULL;
4099 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004100}
4101
Alexandre Vassalotti2056bed2008-12-27 19:46:35 +00004102PyObject *PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004103{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004104 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004105 if (!PyUnicode_Check(unicode)) {
4106 PyErr_BadArgument();
4107 return NULL;
4108 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00004109 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
4110 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004111 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004112}
4113
4114/* --- Raw Unicode Escape Codec ------------------------------------------- */
4115
4116PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004117 Py_ssize_t size,
4118 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004119{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004120 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004121 Py_ssize_t startinpos;
4122 Py_ssize_t endinpos;
4123 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004124 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004125 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004126 const char *end;
4127 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004128 PyObject *errorHandler = NULL;
4129 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00004130
Guido van Rossumd57fd912000-03-10 22:53:23 +00004131 /* Escaped strings will always be longer than the resulting
4132 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004133 length after conversion to the true value. (But decoding error
4134 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004135 v = _PyUnicode_New(size);
4136 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004137 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004138 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004139 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004140 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004141 end = s + size;
4142 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004143 unsigned char c;
4144 Py_UCS4 x;
4145 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004146 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004147
Benjamin Peterson29060642009-01-31 22:14:21 +00004148 /* Non-escape characters are interpreted as Unicode ordinals */
4149 if (*s != '\\') {
4150 *p++ = (unsigned char)*s++;
4151 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004152 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004153 startinpos = s-starts;
4154
4155 /* \u-escapes are only interpreted iff the number of leading
4156 backslashes if odd */
4157 bs = s;
4158 for (;s < end;) {
4159 if (*s != '\\')
4160 break;
4161 *p++ = (unsigned char)*s++;
4162 }
4163 if (((s - bs) & 1) == 0 ||
4164 s >= end ||
4165 (*s != 'u' && *s != 'U')) {
4166 continue;
4167 }
4168 p--;
4169 count = *s=='u' ? 4 : 8;
4170 s++;
4171
4172 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
4173 outpos = p-PyUnicode_AS_UNICODE(v);
4174 for (x = 0, i = 0; i < count; ++i, ++s) {
4175 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00004176 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004177 endinpos = s-starts;
4178 if (unicode_decode_call_errorhandler(
4179 errors, &errorHandler,
4180 "rawunicodeescape", "truncated \\uXXXX",
4181 &starts, &end, &startinpos, &endinpos, &exc, &s,
4182 &v, &outpos, &p))
4183 goto onError;
4184 goto nextByte;
4185 }
4186 x = (x<<4) & ~0xF;
4187 if (c >= '0' && c <= '9')
4188 x += c - '0';
4189 else if (c >= 'a' && c <= 'f')
4190 x += 10 + c - 'a';
4191 else
4192 x += 10 + c - 'A';
4193 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00004194 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00004195 /* UCS-2 character */
4196 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004197 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004198 /* UCS-4 character. Either store directly, or as
4199 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00004200#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004201 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004202#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004203 x -= 0x10000L;
4204 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
4205 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00004206#endif
4207 } else {
4208 endinpos = s-starts;
4209 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004210 if (unicode_decode_call_errorhandler(
4211 errors, &errorHandler,
4212 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00004213 &starts, &end, &startinpos, &endinpos, &exc, &s,
4214 &v, &outpos, &p))
4215 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004216 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004217 nextByte:
4218 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004219 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004220 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004221 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004222 Py_XDECREF(errorHandler);
4223 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004224 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004225
Benjamin Peterson29060642009-01-31 22:14:21 +00004226 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004227 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004228 Py_XDECREF(errorHandler);
4229 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004230 return NULL;
4231}
4232
4233PyObject *PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004234 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004235{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004236 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004237 char *p;
4238 char *q;
4239
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004240#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004241 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004242#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004243 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004244#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00004245
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004246 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00004247 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00004248
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004249 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004250 if (repr == NULL)
4251 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00004252 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004253 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004254
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004255 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004256 while (size-- > 0) {
4257 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004258#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004259 /* Map 32-bit characters to '\Uxxxxxxxx' */
4260 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004261 *p++ = '\\';
4262 *p++ = 'U';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00004263 *p++ = hexdigits[(ch >> 28) & 0xf];
4264 *p++ = hexdigits[(ch >> 24) & 0xf];
4265 *p++ = hexdigits[(ch >> 20) & 0xf];
4266 *p++ = hexdigits[(ch >> 16) & 0xf];
4267 *p++ = hexdigits[(ch >> 12) & 0xf];
4268 *p++ = hexdigits[(ch >> 8) & 0xf];
4269 *p++ = hexdigits[(ch >> 4) & 0xf];
4270 *p++ = hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00004271 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004272 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00004273#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004274 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
4275 if (ch >= 0xD800 && ch < 0xDC00) {
4276 Py_UNICODE ch2;
4277 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004278
Benjamin Peterson29060642009-01-31 22:14:21 +00004279 ch2 = *s++;
4280 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00004281 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004282 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
4283 *p++ = '\\';
4284 *p++ = 'U';
4285 *p++ = hexdigits[(ucs >> 28) & 0xf];
4286 *p++ = hexdigits[(ucs >> 24) & 0xf];
4287 *p++ = hexdigits[(ucs >> 20) & 0xf];
4288 *p++ = hexdigits[(ucs >> 16) & 0xf];
4289 *p++ = hexdigits[(ucs >> 12) & 0xf];
4290 *p++ = hexdigits[(ucs >> 8) & 0xf];
4291 *p++ = hexdigits[(ucs >> 4) & 0xf];
4292 *p++ = hexdigits[ucs & 0xf];
4293 continue;
4294 }
4295 /* Fall through: isolated surrogates are copied as-is */
4296 s--;
4297 size++;
4298 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004299#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004300 /* Map 16-bit characters to '\uxxxx' */
4301 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004302 *p++ = '\\';
4303 *p++ = 'u';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00004304 *p++ = hexdigits[(ch >> 12) & 0xf];
4305 *p++ = hexdigits[(ch >> 8) & 0xf];
4306 *p++ = hexdigits[(ch >> 4) & 0xf];
4307 *p++ = hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00004308 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004309 /* Copy everything else as-is */
4310 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00004311 *p++ = (char) ch;
4312 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00004313 size = p - q;
4314
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004315 assert(size > 0);
4316 if (_PyBytes_Resize(&repr, size) < 0)
4317 return NULL;
4318 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004319}
4320
4321PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
4322{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004323 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004324 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00004325 PyErr_BadArgument();
4326 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004327 }
Walter Dörwald711005d2007-05-12 12:03:26 +00004328 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
4329 PyUnicode_GET_SIZE(unicode));
4330
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004331 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004332}
4333
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004334/* --- Unicode Internal Codec ------------------------------------------- */
4335
4336PyObject *_PyUnicode_DecodeUnicodeInternal(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004337 Py_ssize_t size,
4338 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004339{
4340 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004341 Py_ssize_t startinpos;
4342 Py_ssize_t endinpos;
4343 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004344 PyUnicodeObject *v;
4345 Py_UNICODE *p;
4346 const char *end;
4347 const char *reason;
4348 PyObject *errorHandler = NULL;
4349 PyObject *exc = NULL;
4350
Neal Norwitzd43069c2006-01-08 01:12:10 +00004351#ifdef Py_UNICODE_WIDE
4352 Py_UNICODE unimax = PyUnicode_GetMax();
4353#endif
4354
Thomas Wouters89f507f2006-12-13 04:49:30 +00004355 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004356 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
4357 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004358 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004359 if (PyUnicode_GetSize((PyObject *)v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004360 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004361 p = PyUnicode_AS_UNICODE(v);
4362 end = s + size;
4363
4364 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00004365 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004366 /* We have to sanity check the raw data, otherwise doom looms for
4367 some malformed UCS-4 data. */
4368 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00004369#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004370 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00004371#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004372 end-s < Py_UNICODE_SIZE
4373 )
Benjamin Peterson29060642009-01-31 22:14:21 +00004374 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004375 startinpos = s - starts;
4376 if (end-s < Py_UNICODE_SIZE) {
4377 endinpos = end-starts;
4378 reason = "truncated input";
4379 }
4380 else {
4381 endinpos = s - starts + Py_UNICODE_SIZE;
4382 reason = "illegal code point (> 0x10FFFF)";
4383 }
4384 outpos = p - PyUnicode_AS_UNICODE(v);
4385 if (unicode_decode_call_errorhandler(
4386 errors, &errorHandler,
4387 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00004388 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00004389 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004390 goto onError;
4391 }
4392 }
4393 else {
4394 p++;
4395 s += Py_UNICODE_SIZE;
4396 }
4397 }
4398
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004399 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004400 goto onError;
4401 Py_XDECREF(errorHandler);
4402 Py_XDECREF(exc);
4403 return (PyObject *)v;
4404
Benjamin Peterson29060642009-01-31 22:14:21 +00004405 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004406 Py_XDECREF(v);
4407 Py_XDECREF(errorHandler);
4408 Py_XDECREF(exc);
4409 return NULL;
4410}
4411
Guido van Rossumd57fd912000-03-10 22:53:23 +00004412/* --- Latin-1 Codec ------------------------------------------------------ */
4413
4414PyObject *PyUnicode_DecodeLatin1(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004415 Py_ssize_t size,
4416 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004417{
4418 PyUnicodeObject *v;
4419 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00004420 const char *e, *unrolled_end;
Tim Petersced69f82003-09-16 20:30:58 +00004421
Guido van Rossumd57fd912000-03-10 22:53:23 +00004422 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004423 if (size == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004424 Py_UNICODE r = *(unsigned char*)s;
4425 return PyUnicode_FromUnicode(&r, 1);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004426 }
4427
Guido van Rossumd57fd912000-03-10 22:53:23 +00004428 v = _PyUnicode_New(size);
4429 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004430 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004431 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004432 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004433 p = PyUnicode_AS_UNICODE(v);
Antoine Pitrouab868312009-01-10 15:40:25 +00004434 e = s + size;
4435 /* Unrolling the copy makes it much faster by reducing the looping
4436 overhead. This is similar to what many memcpy() implementations do. */
4437 unrolled_end = e - 4;
4438 while (s < unrolled_end) {
4439 p[0] = (unsigned char) s[0];
4440 p[1] = (unsigned char) s[1];
4441 p[2] = (unsigned char) s[2];
4442 p[3] = (unsigned char) s[3];
4443 s += 4;
4444 p += 4;
4445 }
4446 while (s < e)
4447 *p++ = (unsigned char) *s++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004448 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004449
Benjamin Peterson29060642009-01-31 22:14:21 +00004450 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004451 Py_XDECREF(v);
4452 return NULL;
4453}
4454
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004455/* create or adjust a UnicodeEncodeError */
4456static void make_encode_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004457 const char *encoding,
4458 const Py_UNICODE *unicode, Py_ssize_t size,
4459 Py_ssize_t startpos, Py_ssize_t endpos,
4460 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004461{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004462 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004463 *exceptionObject = PyUnicodeEncodeError_Create(
4464 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004465 }
4466 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004467 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
4468 goto onError;
4469 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
4470 goto onError;
4471 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
4472 goto onError;
4473 return;
4474 onError:
4475 Py_DECREF(*exceptionObject);
4476 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004477 }
4478}
4479
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004480/* raises a UnicodeEncodeError */
4481static void raise_encode_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004482 const char *encoding,
4483 const Py_UNICODE *unicode, Py_ssize_t size,
4484 Py_ssize_t startpos, Py_ssize_t endpos,
4485 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004486{
4487 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004488 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004489 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004490 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004491}
4492
4493/* error handling callback helper:
4494 build arguments, call the callback and check the arguments,
4495 put the result into newpos and return the replacement string, which
4496 has to be freed by the caller */
4497static PyObject *unicode_encode_call_errorhandler(const char *errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00004498 PyObject **errorHandler,
4499 const char *encoding, const char *reason,
4500 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
4501 Py_ssize_t startpos, Py_ssize_t endpos,
4502 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004503{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004504 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004505
4506 PyObject *restuple;
4507 PyObject *resunicode;
4508
4509 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004510 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004511 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004512 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004513 }
4514
4515 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004516 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004517 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004518 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004519
4520 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00004521 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004522 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004523 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004524 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004525 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004526 Py_DECREF(restuple);
4527 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004528 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004529 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00004530 &resunicode, newpos)) {
4531 Py_DECREF(restuple);
4532 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004533 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004534 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
4535 PyErr_SetString(PyExc_TypeError, &argparse[3]);
4536 Py_DECREF(restuple);
4537 return NULL;
4538 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004539 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004540 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004541 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004542 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
4543 Py_DECREF(restuple);
4544 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004545 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004546 Py_INCREF(resunicode);
4547 Py_DECREF(restuple);
4548 return resunicode;
4549}
4550
4551static PyObject *unicode_encode_ucs1(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004552 Py_ssize_t size,
4553 const char *errors,
4554 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004555{
4556 /* output object */
4557 PyObject *res;
4558 /* pointers to the beginning and end+1 of input */
4559 const Py_UNICODE *startp = p;
4560 const Py_UNICODE *endp = p + size;
4561 /* pointer to the beginning of the unencodable characters */
4562 /* const Py_UNICODE *badp = NULL; */
4563 /* pointer into the output */
4564 char *str;
4565 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00004566 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004567 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
4568 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004569 PyObject *errorHandler = NULL;
4570 PyObject *exc = NULL;
4571 /* the following variable is used for caching string comparisons
4572 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
4573 int known_errorHandler = -1;
4574
4575 /* allocate enough for a simple encoding without
4576 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00004577 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00004578 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004579 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004580 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00004581 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004582 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004583 ressize = size;
4584
4585 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004586 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004587
Benjamin Peterson29060642009-01-31 22:14:21 +00004588 /* can we encode this? */
4589 if (c<limit) {
4590 /* no overflow check, because we know that the space is enough */
4591 *str++ = (char)c;
4592 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004593 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004594 else {
4595 Py_ssize_t unicodepos = p-startp;
4596 Py_ssize_t requiredsize;
4597 PyObject *repunicode;
4598 Py_ssize_t repsize;
4599 Py_ssize_t newpos;
4600 Py_ssize_t respos;
4601 Py_UNICODE *uni2;
4602 /* startpos for collecting unencodable chars */
4603 const Py_UNICODE *collstart = p;
4604 const Py_UNICODE *collend = p;
4605 /* find all unecodable characters */
4606 while ((collend < endp) && ((*collend)>=limit))
4607 ++collend;
4608 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
4609 if (known_errorHandler==-1) {
4610 if ((errors==NULL) || (!strcmp(errors, "strict")))
4611 known_errorHandler = 1;
4612 else if (!strcmp(errors, "replace"))
4613 known_errorHandler = 2;
4614 else if (!strcmp(errors, "ignore"))
4615 known_errorHandler = 3;
4616 else if (!strcmp(errors, "xmlcharrefreplace"))
4617 known_errorHandler = 4;
4618 else
4619 known_errorHandler = 0;
4620 }
4621 switch (known_errorHandler) {
4622 case 1: /* strict */
4623 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
4624 goto onError;
4625 case 2: /* replace */
4626 while (collstart++<collend)
4627 *str++ = '?'; /* fall through */
4628 case 3: /* ignore */
4629 p = collend;
4630 break;
4631 case 4: /* xmlcharrefreplace */
4632 respos = str - PyBytes_AS_STRING(res);
4633 /* determine replacement size (temporarily (mis)uses p) */
4634 for (p = collstart, repsize = 0; p < collend; ++p) {
4635 if (*p<10)
4636 repsize += 2+1+1;
4637 else if (*p<100)
4638 repsize += 2+2+1;
4639 else if (*p<1000)
4640 repsize += 2+3+1;
4641 else if (*p<10000)
4642 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00004643#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004644 else
4645 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00004646#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004647 else if (*p<100000)
4648 repsize += 2+5+1;
4649 else if (*p<1000000)
4650 repsize += 2+6+1;
4651 else
4652 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004653#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004654 }
4655 requiredsize = respos+repsize+(endp-collend);
4656 if (requiredsize > ressize) {
4657 if (requiredsize<2*ressize)
4658 requiredsize = 2*ressize;
4659 if (_PyBytes_Resize(&res, requiredsize))
4660 goto onError;
4661 str = PyBytes_AS_STRING(res) + respos;
4662 ressize = requiredsize;
4663 }
4664 /* generate replacement (temporarily (mis)uses p) */
4665 for (p = collstart; p < collend; ++p) {
4666 str += sprintf(str, "&#%d;", (int)*p);
4667 }
4668 p = collend;
4669 break;
4670 default:
4671 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
4672 encoding, reason, startp, size, &exc,
4673 collstart-startp, collend-startp, &newpos);
4674 if (repunicode == NULL)
4675 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004676 if (PyBytes_Check(repunicode)) {
4677 /* Directly copy bytes result to output. */
4678 repsize = PyBytes_Size(repunicode);
4679 if (repsize > 1) {
4680 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00004681 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00004682 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
4683 Py_DECREF(repunicode);
4684 goto onError;
4685 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00004686 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004687 ressize += repsize-1;
4688 }
4689 memcpy(str, PyBytes_AsString(repunicode), repsize);
4690 str += repsize;
4691 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004692 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00004693 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004694 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004695 /* need more space? (at least enough for what we
4696 have+the replacement+the rest of the string, so
4697 we won't have to check space for encodable characters) */
4698 respos = str - PyBytes_AS_STRING(res);
4699 repsize = PyUnicode_GET_SIZE(repunicode);
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 Py_DECREF(repunicode);
4706 goto onError;
4707 }
4708 str = PyBytes_AS_STRING(res) + respos;
4709 ressize = requiredsize;
4710 }
4711 /* check if there is anything unencodable in the replacement
4712 and copy it to the output */
4713 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
4714 c = *uni2;
4715 if (c >= limit) {
4716 raise_encode_exception(&exc, encoding, startp, size,
4717 unicodepos, unicodepos+1, reason);
4718 Py_DECREF(repunicode);
4719 goto onError;
4720 }
4721 *str = (char)c;
4722 }
4723 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004724 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00004725 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004726 }
4727 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004728 /* Resize if we allocated to much */
4729 size = str - PyBytes_AS_STRING(res);
4730 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00004731 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004732 if (_PyBytes_Resize(&res, size) < 0)
4733 goto onError;
4734 }
4735
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004736 Py_XDECREF(errorHandler);
4737 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004738 return res;
4739
4740 onError:
4741 Py_XDECREF(res);
4742 Py_XDECREF(errorHandler);
4743 Py_XDECREF(exc);
4744 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004745}
4746
Guido van Rossumd57fd912000-03-10 22:53:23 +00004747PyObject *PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004748 Py_ssize_t size,
4749 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004750{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004751 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004752}
4753
4754PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
4755{
4756 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004757 PyErr_BadArgument();
4758 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004759 }
4760 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004761 PyUnicode_GET_SIZE(unicode),
4762 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004763}
4764
4765/* --- 7-bit ASCII Codec -------------------------------------------------- */
4766
Guido van Rossumd57fd912000-03-10 22:53:23 +00004767PyObject *PyUnicode_DecodeASCII(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004768 Py_ssize_t size,
4769 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004770{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004771 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004772 PyUnicodeObject *v;
4773 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004774 Py_ssize_t startinpos;
4775 Py_ssize_t endinpos;
4776 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004777 const char *e;
4778 PyObject *errorHandler = NULL;
4779 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00004780
Guido van Rossumd57fd912000-03-10 22:53:23 +00004781 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004782 if (size == 1 && *(unsigned char*)s < 128) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004783 Py_UNICODE r = *(unsigned char*)s;
4784 return PyUnicode_FromUnicode(&r, 1);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004785 }
Tim Petersced69f82003-09-16 20:30:58 +00004786
Guido van Rossumd57fd912000-03-10 22:53:23 +00004787 v = _PyUnicode_New(size);
4788 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004789 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004790 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004791 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004792 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004793 e = s + size;
4794 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004795 register unsigned char c = (unsigned char)*s;
4796 if (c < 128) {
4797 *p++ = c;
4798 ++s;
4799 }
4800 else {
4801 startinpos = s-starts;
4802 endinpos = startinpos + 1;
4803 outpos = p - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
4804 if (unicode_decode_call_errorhandler(
4805 errors, &errorHandler,
4806 "ascii", "ordinal not in range(128)",
4807 &starts, &e, &startinpos, &endinpos, &exc, &s,
4808 &v, &outpos, &p))
4809 goto onError;
4810 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004811 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00004812 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00004813 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
4814 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004815 Py_XDECREF(errorHandler);
4816 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004817 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004818
Benjamin Peterson29060642009-01-31 22:14:21 +00004819 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004820 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004821 Py_XDECREF(errorHandler);
4822 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004823 return NULL;
4824}
4825
Guido van Rossumd57fd912000-03-10 22:53:23 +00004826PyObject *PyUnicode_EncodeASCII(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004827 Py_ssize_t size,
4828 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004829{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004830 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004831}
4832
4833PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
4834{
4835 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004836 PyErr_BadArgument();
4837 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004838 }
4839 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004840 PyUnicode_GET_SIZE(unicode),
4841 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004842}
4843
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004844#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004845
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004846/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004847
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00004848#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004849#define NEED_RETRY
4850#endif
4851
4852/* XXX This code is limited to "true" double-byte encodings, as
4853 a) it assumes an incomplete character consists of a single byte, and
4854 b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
Benjamin Peterson29060642009-01-31 22:14:21 +00004855 encodings, see IsDBCSLeadByteEx documentation. */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004856
4857static int is_dbcs_lead_byte(const char *s, int offset)
4858{
4859 const char *curr = s + offset;
4860
4861 if (IsDBCSLeadByte(*curr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004862 const char *prev = CharPrev(s, curr);
4863 return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004864 }
4865 return 0;
4866}
4867
4868/*
4869 * Decode MBCS string into unicode object. If 'final' is set, converts
4870 * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
4871 */
4872static int decode_mbcs(PyUnicodeObject **v,
Benjamin Peterson29060642009-01-31 22:14:21 +00004873 const char *s, /* MBCS string */
4874 int size, /* sizeof MBCS string */
Victor Stinner554f3f02010-06-16 23:33:54 +00004875 int final,
4876 const char *errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004877{
4878 Py_UNICODE *p;
Victor Stinner554f3f02010-06-16 23:33:54 +00004879 Py_ssize_t n;
4880 DWORD usize;
4881 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004882
4883 assert(size >= 0);
4884
Victor Stinner554f3f02010-06-16 23:33:54 +00004885 /* check and handle 'errors' arg */
4886 if (errors==NULL || strcmp(errors, "strict")==0)
4887 flags = MB_ERR_INVALID_CHARS;
4888 else if (strcmp(errors, "ignore")==0)
4889 flags = 0;
4890 else {
4891 PyErr_Format(PyExc_ValueError,
4892 "mbcs encoding does not support errors='%s'",
4893 errors);
4894 return -1;
4895 }
4896
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004897 /* Skip trailing lead-byte unless 'final' is set */
4898 if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
Benjamin Peterson29060642009-01-31 22:14:21 +00004899 --size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004900
4901 /* First get the size of the result */
4902 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00004903 usize = MultiByteToWideChar(CP_ACP, flags, s, size, NULL, 0);
4904 if (usize==0)
4905 goto mbcs_decode_error;
4906 } else
4907 usize = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004908
4909 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004910 /* Create unicode object */
4911 *v = _PyUnicode_New(usize);
4912 if (*v == NULL)
4913 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00004914 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004915 }
4916 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004917 /* Extend unicode object */
4918 n = PyUnicode_GET_SIZE(*v);
4919 if (_PyUnicode_Resize(v, n + usize) < 0)
4920 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004921 }
4922
4923 /* Do the conversion */
Victor Stinner554f3f02010-06-16 23:33:54 +00004924 if (usize > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004925 p = PyUnicode_AS_UNICODE(*v) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00004926 if (0 == MultiByteToWideChar(CP_ACP, flags, s, size, p, usize)) {
4927 goto mbcs_decode_error;
Benjamin Peterson29060642009-01-31 22:14:21 +00004928 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004929 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004930 return size;
Victor Stinner554f3f02010-06-16 23:33:54 +00004931
4932mbcs_decode_error:
4933 /* If the last error was ERROR_NO_UNICODE_TRANSLATION, then
4934 we raise a UnicodeDecodeError - else it is a 'generic'
4935 windows error
4936 */
4937 if (GetLastError()==ERROR_NO_UNICODE_TRANSLATION) {
4938 /* Ideally, we should get reason from FormatMessage - this
4939 is the Windows 2000 English version of the message
4940 */
4941 PyObject *exc = NULL;
4942 const char *reason = "No mapping for the Unicode character exists "
4943 "in the target multi-byte code page.";
4944 make_decode_exception(&exc, "mbcs", s, size, 0, 0, reason);
4945 if (exc != NULL) {
4946 PyCodec_StrictErrors(exc);
4947 Py_DECREF(exc);
4948 }
4949 } else {
4950 PyErr_SetFromWindowsErrWithFilename(0, NULL);
4951 }
4952 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004953}
4954
4955PyObject *PyUnicode_DecodeMBCSStateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004956 Py_ssize_t size,
4957 const char *errors,
4958 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004959{
4960 PyUnicodeObject *v = NULL;
4961 int done;
4962
4963 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004964 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004965
4966#ifdef NEED_RETRY
4967 retry:
4968 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00004969 done = decode_mbcs(&v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004970 else
4971#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00004972 done = decode_mbcs(&v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004973
4974 if (done < 0) {
4975 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00004976 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004977 }
4978
4979 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004980 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004981
4982#ifdef NEED_RETRY
4983 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004984 s += done;
4985 size -= done;
4986 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004987 }
4988#endif
4989
4990 return (PyObject *)v;
4991}
4992
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004993PyObject *PyUnicode_DecodeMBCS(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004994 Py_ssize_t size,
4995 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004996{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004997 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
4998}
4999
5000/*
5001 * Convert unicode into string object (MBCS).
5002 * Returns 0 if succeed, -1 otherwise.
5003 */
5004static int encode_mbcs(PyObject **repr,
Benjamin Peterson29060642009-01-31 22:14:21 +00005005 const Py_UNICODE *p, /* unicode */
Victor Stinner554f3f02010-06-16 23:33:54 +00005006 int size, /* size of unicode */
5007 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005008{
Victor Stinner554f3f02010-06-16 23:33:54 +00005009 BOOL usedDefaultChar = FALSE;
5010 BOOL *pusedDefaultChar;
5011 int mbcssize;
5012 Py_ssize_t n;
5013 PyObject *exc = NULL;
5014 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005015
5016 assert(size >= 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005017
Victor Stinner554f3f02010-06-16 23:33:54 +00005018 /* check and handle 'errors' arg */
5019 if (errors==NULL || strcmp(errors, "strict")==0) {
5020 flags = WC_NO_BEST_FIT_CHARS;
5021 pusedDefaultChar = &usedDefaultChar;
5022 } else if (strcmp(errors, "replace")==0) {
5023 flags = 0;
5024 pusedDefaultChar = NULL;
5025 } else {
5026 PyErr_Format(PyExc_ValueError,
5027 "mbcs encoding does not support errors='%s'",
5028 errors);
5029 return -1;
5030 }
5031
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005032 /* First get the size of the result */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005033 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00005034 mbcssize = WideCharToMultiByte(CP_ACP, flags, p, size, NULL, 0,
5035 NULL, pusedDefaultChar);
Benjamin Peterson29060642009-01-31 22:14:21 +00005036 if (mbcssize == 0) {
5037 PyErr_SetFromWindowsErrWithFilename(0, NULL);
5038 return -1;
5039 }
Victor Stinner554f3f02010-06-16 23:33:54 +00005040 /* If we used a default char, then we failed! */
5041 if (pusedDefaultChar && *pusedDefaultChar)
5042 goto mbcs_encode_error;
5043 } else {
5044 mbcssize = 0;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005045 }
5046
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005047 if (*repr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005048 /* Create string object */
5049 *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
5050 if (*repr == NULL)
5051 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00005052 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005053 }
5054 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005055 /* Extend string object */
5056 n = PyBytes_Size(*repr);
5057 if (_PyBytes_Resize(repr, n + mbcssize) < 0)
5058 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005059 }
5060
5061 /* Do the conversion */
5062 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005063 char *s = PyBytes_AS_STRING(*repr) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00005064 if (0 == WideCharToMultiByte(CP_ACP, flags, p, size, s, mbcssize,
5065 NULL, pusedDefaultChar)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005066 PyErr_SetFromWindowsErrWithFilename(0, NULL);
5067 return -1;
5068 }
Victor Stinner554f3f02010-06-16 23:33:54 +00005069 if (pusedDefaultChar && *pusedDefaultChar)
5070 goto mbcs_encode_error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005071 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005072 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00005073
5074mbcs_encode_error:
5075 raise_encode_exception(&exc, "mbcs", p, size, 0, 0, "invalid character");
5076 Py_XDECREF(exc);
5077 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005078}
5079
5080PyObject *PyUnicode_EncodeMBCS(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00005081 Py_ssize_t size,
5082 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005083{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005084 PyObject *repr = NULL;
5085 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00005086
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005087#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00005088 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005089 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00005090 ret = encode_mbcs(&repr, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005091 else
5092#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00005093 ret = encode_mbcs(&repr, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005094
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005095 if (ret < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005096 Py_XDECREF(repr);
5097 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005098 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005099
5100#ifdef NEED_RETRY
5101 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005102 p += INT_MAX;
5103 size -= INT_MAX;
5104 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005105 }
5106#endif
5107
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005108 return repr;
5109}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00005110
Mark Hammond0ccda1e2003-07-01 00:13:27 +00005111PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
5112{
5113 if (!PyUnicode_Check(unicode)) {
5114 PyErr_BadArgument();
5115 return NULL;
5116 }
5117 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005118 PyUnicode_GET_SIZE(unicode),
5119 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00005120}
5121
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005122#undef NEED_RETRY
5123
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00005124#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00005125
Guido van Rossumd57fd912000-03-10 22:53:23 +00005126/* --- Character Mapping Codec -------------------------------------------- */
5127
Guido van Rossumd57fd912000-03-10 22:53:23 +00005128PyObject *PyUnicode_DecodeCharmap(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005129 Py_ssize_t size,
5130 PyObject *mapping,
5131 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005132{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005133 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005134 Py_ssize_t startinpos;
5135 Py_ssize_t endinpos;
5136 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005137 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005138 PyUnicodeObject *v;
5139 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005140 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005141 PyObject *errorHandler = NULL;
5142 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005143 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005144 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00005145
Guido van Rossumd57fd912000-03-10 22:53:23 +00005146 /* Default to Latin-1 */
5147 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005148 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005149
5150 v = _PyUnicode_New(size);
5151 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005152 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005153 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005154 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005155 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005156 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005157 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005158 mapstring = PyUnicode_AS_UNICODE(mapping);
5159 maplen = PyUnicode_GET_SIZE(mapping);
5160 while (s < e) {
5161 unsigned char ch = *s;
5162 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005163
Benjamin Peterson29060642009-01-31 22:14:21 +00005164 if (ch < maplen)
5165 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005166
Benjamin Peterson29060642009-01-31 22:14:21 +00005167 if (x == 0xfffe) {
5168 /* undefined mapping */
5169 outpos = p-PyUnicode_AS_UNICODE(v);
5170 startinpos = s-starts;
5171 endinpos = startinpos+1;
5172 if (unicode_decode_call_errorhandler(
5173 errors, &errorHandler,
5174 "charmap", "character maps to <undefined>",
5175 &starts, &e, &startinpos, &endinpos, &exc, &s,
5176 &v, &outpos, &p)) {
5177 goto onError;
5178 }
5179 continue;
5180 }
5181 *p++ = x;
5182 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005183 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005184 }
5185 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005186 while (s < e) {
5187 unsigned char ch = *s;
5188 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005189
Benjamin Peterson29060642009-01-31 22:14:21 +00005190 /* Get mapping (char ordinal -> integer, Unicode char or None) */
5191 w = PyLong_FromLong((long)ch);
5192 if (w == NULL)
5193 goto onError;
5194 x = PyObject_GetItem(mapping, w);
5195 Py_DECREF(w);
5196 if (x == NULL) {
5197 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5198 /* No mapping found means: mapping is undefined. */
5199 PyErr_Clear();
5200 x = Py_None;
5201 Py_INCREF(x);
5202 } else
5203 goto onError;
5204 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005205
Benjamin Peterson29060642009-01-31 22:14:21 +00005206 /* Apply mapping */
5207 if (PyLong_Check(x)) {
5208 long value = PyLong_AS_LONG(x);
5209 if (value < 0 || value > 65535) {
5210 PyErr_SetString(PyExc_TypeError,
5211 "character mapping must be in range(65536)");
5212 Py_DECREF(x);
5213 goto onError;
5214 }
5215 *p++ = (Py_UNICODE)value;
5216 }
5217 else if (x == Py_None) {
5218 /* undefined mapping */
5219 outpos = p-PyUnicode_AS_UNICODE(v);
5220 startinpos = s-starts;
5221 endinpos = startinpos+1;
5222 if (unicode_decode_call_errorhandler(
5223 errors, &errorHandler,
5224 "charmap", "character maps to <undefined>",
5225 &starts, &e, &startinpos, &endinpos, &exc, &s,
5226 &v, &outpos, &p)) {
5227 Py_DECREF(x);
5228 goto onError;
5229 }
5230 Py_DECREF(x);
5231 continue;
5232 }
5233 else if (PyUnicode_Check(x)) {
5234 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005235
Benjamin Peterson29060642009-01-31 22:14:21 +00005236 if (targetsize == 1)
5237 /* 1-1 mapping */
5238 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005239
Benjamin Peterson29060642009-01-31 22:14:21 +00005240 else if (targetsize > 1) {
5241 /* 1-n mapping */
5242 if (targetsize > extrachars) {
5243 /* resize first */
5244 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
5245 Py_ssize_t needed = (targetsize - extrachars) + \
5246 (targetsize << 2);
5247 extrachars += needed;
5248 /* XXX overflow detection missing */
5249 if (_PyUnicode_Resize(&v,
5250 PyUnicode_GET_SIZE(v) + needed) < 0) {
5251 Py_DECREF(x);
5252 goto onError;
5253 }
5254 p = PyUnicode_AS_UNICODE(v) + oldpos;
5255 }
5256 Py_UNICODE_COPY(p,
5257 PyUnicode_AS_UNICODE(x),
5258 targetsize);
5259 p += targetsize;
5260 extrachars -= targetsize;
5261 }
5262 /* 1-0 mapping: skip the character */
5263 }
5264 else {
5265 /* wrong return value */
5266 PyErr_SetString(PyExc_TypeError,
5267 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00005268 Py_DECREF(x);
5269 goto onError;
5270 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005271 Py_DECREF(x);
5272 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005273 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005274 }
5275 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00005276 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
5277 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005278 Py_XDECREF(errorHandler);
5279 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005280 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00005281
Benjamin Peterson29060642009-01-31 22:14:21 +00005282 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005283 Py_XDECREF(errorHandler);
5284 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005285 Py_XDECREF(v);
5286 return NULL;
5287}
5288
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005289/* Charmap encoding: the lookup table */
5290
5291struct encoding_map{
Benjamin Peterson29060642009-01-31 22:14:21 +00005292 PyObject_HEAD
5293 unsigned char level1[32];
5294 int count2, count3;
5295 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005296};
5297
5298static PyObject*
5299encoding_map_size(PyObject *obj, PyObject* args)
5300{
5301 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005302 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00005303 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005304}
5305
5306static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005307 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00005308 PyDoc_STR("Return the size (in bytes) of this object") },
5309 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005310};
5311
5312static void
5313encoding_map_dealloc(PyObject* o)
5314{
Benjamin Peterson14339b62009-01-31 16:36:08 +00005315 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005316}
5317
5318static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005319 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005320 "EncodingMap", /*tp_name*/
5321 sizeof(struct encoding_map), /*tp_basicsize*/
5322 0, /*tp_itemsize*/
5323 /* methods */
5324 encoding_map_dealloc, /*tp_dealloc*/
5325 0, /*tp_print*/
5326 0, /*tp_getattr*/
5327 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00005328 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00005329 0, /*tp_repr*/
5330 0, /*tp_as_number*/
5331 0, /*tp_as_sequence*/
5332 0, /*tp_as_mapping*/
5333 0, /*tp_hash*/
5334 0, /*tp_call*/
5335 0, /*tp_str*/
5336 0, /*tp_getattro*/
5337 0, /*tp_setattro*/
5338 0, /*tp_as_buffer*/
5339 Py_TPFLAGS_DEFAULT, /*tp_flags*/
5340 0, /*tp_doc*/
5341 0, /*tp_traverse*/
5342 0, /*tp_clear*/
5343 0, /*tp_richcompare*/
5344 0, /*tp_weaklistoffset*/
5345 0, /*tp_iter*/
5346 0, /*tp_iternext*/
5347 encoding_map_methods, /*tp_methods*/
5348 0, /*tp_members*/
5349 0, /*tp_getset*/
5350 0, /*tp_base*/
5351 0, /*tp_dict*/
5352 0, /*tp_descr_get*/
5353 0, /*tp_descr_set*/
5354 0, /*tp_dictoffset*/
5355 0, /*tp_init*/
5356 0, /*tp_alloc*/
5357 0, /*tp_new*/
5358 0, /*tp_free*/
5359 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005360};
5361
5362PyObject*
5363PyUnicode_BuildEncodingMap(PyObject* string)
5364{
5365 Py_UNICODE *decode;
5366 PyObject *result;
5367 struct encoding_map *mresult;
5368 int i;
5369 int need_dict = 0;
5370 unsigned char level1[32];
5371 unsigned char level2[512];
5372 unsigned char *mlevel1, *mlevel2, *mlevel3;
5373 int count2 = 0, count3 = 0;
5374
5375 if (!PyUnicode_Check(string) || PyUnicode_GetSize(string) != 256) {
5376 PyErr_BadArgument();
5377 return NULL;
5378 }
5379 decode = PyUnicode_AS_UNICODE(string);
5380 memset(level1, 0xFF, sizeof level1);
5381 memset(level2, 0xFF, sizeof level2);
5382
5383 /* If there isn't a one-to-one mapping of NULL to \0,
5384 or if there are non-BMP characters, we need to use
5385 a mapping dictionary. */
5386 if (decode[0] != 0)
5387 need_dict = 1;
5388 for (i = 1; i < 256; i++) {
5389 int l1, l2;
5390 if (decode[i] == 0
Benjamin Peterson29060642009-01-31 22:14:21 +00005391#ifdef Py_UNICODE_WIDE
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005392 || decode[i] > 0xFFFF
Benjamin Peterson29060642009-01-31 22:14:21 +00005393#endif
5394 ) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005395 need_dict = 1;
5396 break;
5397 }
5398 if (decode[i] == 0xFFFE)
5399 /* unmapped character */
5400 continue;
5401 l1 = decode[i] >> 11;
5402 l2 = decode[i] >> 7;
5403 if (level1[l1] == 0xFF)
5404 level1[l1] = count2++;
5405 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00005406 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005407 }
5408
5409 if (count2 >= 0xFF || count3 >= 0xFF)
5410 need_dict = 1;
5411
5412 if (need_dict) {
5413 PyObject *result = PyDict_New();
5414 PyObject *key, *value;
5415 if (!result)
5416 return NULL;
5417 for (i = 0; i < 256; i++) {
5418 key = value = NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00005419 key = PyLong_FromLong(decode[i]);
5420 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005421 if (!key || !value)
5422 goto failed1;
5423 if (PyDict_SetItem(result, key, value) == -1)
5424 goto failed1;
5425 Py_DECREF(key);
5426 Py_DECREF(value);
5427 }
5428 return result;
5429 failed1:
5430 Py_XDECREF(key);
5431 Py_XDECREF(value);
5432 Py_DECREF(result);
5433 return NULL;
5434 }
5435
5436 /* Create a three-level trie */
5437 result = PyObject_MALLOC(sizeof(struct encoding_map) +
5438 16*count2 + 128*count3 - 1);
5439 if (!result)
5440 return PyErr_NoMemory();
5441 PyObject_Init(result, &EncodingMapType);
5442 mresult = (struct encoding_map*)result;
5443 mresult->count2 = count2;
5444 mresult->count3 = count3;
5445 mlevel1 = mresult->level1;
5446 mlevel2 = mresult->level23;
5447 mlevel3 = mresult->level23 + 16*count2;
5448 memcpy(mlevel1, level1, 32);
5449 memset(mlevel2, 0xFF, 16*count2);
5450 memset(mlevel3, 0, 128*count3);
5451 count3 = 0;
5452 for (i = 1; i < 256; i++) {
5453 int o1, o2, o3, i2, i3;
5454 if (decode[i] == 0xFFFE)
5455 /* unmapped character */
5456 continue;
5457 o1 = decode[i]>>11;
5458 o2 = (decode[i]>>7) & 0xF;
5459 i2 = 16*mlevel1[o1] + o2;
5460 if (mlevel2[i2] == 0xFF)
5461 mlevel2[i2] = count3++;
5462 o3 = decode[i] & 0x7F;
5463 i3 = 128*mlevel2[i2] + o3;
5464 mlevel3[i3] = i;
5465 }
5466 return result;
5467}
5468
5469static int
5470encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
5471{
5472 struct encoding_map *map = (struct encoding_map*)mapping;
5473 int l1 = c>>11;
5474 int l2 = (c>>7) & 0xF;
5475 int l3 = c & 0x7F;
5476 int i;
5477
5478#ifdef Py_UNICODE_WIDE
5479 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005480 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005481 }
5482#endif
5483 if (c == 0)
5484 return 0;
5485 /* level 1*/
5486 i = map->level1[l1];
5487 if (i == 0xFF) {
5488 return -1;
5489 }
5490 /* level 2*/
5491 i = map->level23[16*i+l2];
5492 if (i == 0xFF) {
5493 return -1;
5494 }
5495 /* level 3 */
5496 i = map->level23[16*map->count2 + 128*i + l3];
5497 if (i == 0) {
5498 return -1;
5499 }
5500 return i;
5501}
5502
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005503/* Lookup the character ch in the mapping. If the character
5504 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00005505 error occurred). */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005506static PyObject *charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005507{
Christian Heimes217cfd12007-12-02 14:31:20 +00005508 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005509 PyObject *x;
5510
5511 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005512 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005513 x = PyObject_GetItem(mapping, w);
5514 Py_DECREF(w);
5515 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005516 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5517 /* No mapping found means: mapping is undefined. */
5518 PyErr_Clear();
5519 x = Py_None;
5520 Py_INCREF(x);
5521 return x;
5522 } else
5523 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005524 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00005525 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00005526 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00005527 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005528 long value = PyLong_AS_LONG(x);
5529 if (value < 0 || value > 255) {
5530 PyErr_SetString(PyExc_TypeError,
5531 "character mapping must be in range(256)");
5532 Py_DECREF(x);
5533 return NULL;
5534 }
5535 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005536 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005537 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00005538 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005539 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005540 /* wrong return value */
5541 PyErr_Format(PyExc_TypeError,
5542 "character mapping must return integer, bytes or None, not %.400s",
5543 x->ob_type->tp_name);
5544 Py_DECREF(x);
5545 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005546 }
5547}
5548
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005549static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00005550charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005551{
Benjamin Peterson14339b62009-01-31 16:36:08 +00005552 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
5553 /* exponentially overallocate to minimize reallocations */
5554 if (requiredsize < 2*outsize)
5555 requiredsize = 2*outsize;
5556 if (_PyBytes_Resize(outobj, requiredsize))
5557 return -1;
5558 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005559}
5560
Benjamin Peterson14339b62009-01-31 16:36:08 +00005561typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00005562 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005563}charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005564/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00005565 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005566 space is available. Return a new reference to the object that
5567 was put in the output buffer, or Py_None, if the mapping was undefined
5568 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00005569 reallocation error occurred. The caller must decref the result */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005570static
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005571charmapencode_result charmapencode_output(Py_UNICODE c, PyObject *mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00005572 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005573{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005574 PyObject *rep;
5575 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00005576 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005577
Christian Heimes90aa7642007-12-19 02:45:37 +00005578 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005579 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00005580 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005581 if (res == -1)
5582 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00005583 if (outsize<requiredsize)
5584 if (charmapencode_resize(outobj, outpos, requiredsize))
5585 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00005586 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005587 outstart[(*outpos)++] = (char)res;
5588 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005589 }
5590
5591 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005592 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005593 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005594 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005595 Py_DECREF(rep);
5596 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005597 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005598 if (PyLong_Check(rep)) {
5599 Py_ssize_t requiredsize = *outpos+1;
5600 if (outsize<requiredsize)
5601 if (charmapencode_resize(outobj, outpos, requiredsize)) {
5602 Py_DECREF(rep);
5603 return enc_EXCEPTION;
5604 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005605 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005606 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005607 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005608 else {
5609 const char *repchars = PyBytes_AS_STRING(rep);
5610 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
5611 Py_ssize_t requiredsize = *outpos+repsize;
5612 if (outsize<requiredsize)
5613 if (charmapencode_resize(outobj, outpos, requiredsize)) {
5614 Py_DECREF(rep);
5615 return enc_EXCEPTION;
5616 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005617 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005618 memcpy(outstart + *outpos, repchars, repsize);
5619 *outpos += repsize;
5620 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005621 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005622 Py_DECREF(rep);
5623 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005624}
5625
5626/* handle an error in PyUnicode_EncodeCharmap
5627 Return 0 on success, -1 on error */
5628static
5629int charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00005630 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005631 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00005632 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00005633 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005634{
5635 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005636 Py_ssize_t repsize;
5637 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005638 Py_UNICODE *uni2;
5639 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005640 Py_ssize_t collstartpos = *inpos;
5641 Py_ssize_t collendpos = *inpos+1;
5642 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005643 char *encoding = "charmap";
5644 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005645 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005646
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005647 /* find all unencodable characters */
5648 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005649 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00005650 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005651 int res = encoding_map_lookup(p[collendpos], mapping);
5652 if (res != -1)
5653 break;
5654 ++collendpos;
5655 continue;
5656 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005657
Benjamin Peterson29060642009-01-31 22:14:21 +00005658 rep = charmapencode_lookup(p[collendpos], mapping);
5659 if (rep==NULL)
5660 return -1;
5661 else if (rep!=Py_None) {
5662 Py_DECREF(rep);
5663 break;
5664 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005665 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00005666 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005667 }
5668 /* cache callback name lookup
5669 * (if not done yet, i.e. it's the first error) */
5670 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005671 if ((errors==NULL) || (!strcmp(errors, "strict")))
5672 *known_errorHandler = 1;
5673 else if (!strcmp(errors, "replace"))
5674 *known_errorHandler = 2;
5675 else if (!strcmp(errors, "ignore"))
5676 *known_errorHandler = 3;
5677 else if (!strcmp(errors, "xmlcharrefreplace"))
5678 *known_errorHandler = 4;
5679 else
5680 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005681 }
5682 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005683 case 1: /* strict */
5684 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5685 return -1;
5686 case 2: /* replace */
5687 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005688 x = charmapencode_output('?', mapping, res, respos);
5689 if (x==enc_EXCEPTION) {
5690 return -1;
5691 }
5692 else if (x==enc_FAILED) {
5693 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5694 return -1;
5695 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005696 }
5697 /* fall through */
5698 case 3: /* ignore */
5699 *inpos = collendpos;
5700 break;
5701 case 4: /* xmlcharrefreplace */
5702 /* generate replacement (temporarily (mis)uses p) */
5703 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005704 char buffer[2+29+1+1];
5705 char *cp;
5706 sprintf(buffer, "&#%d;", (int)p[collpos]);
5707 for (cp = buffer; *cp; ++cp) {
5708 x = charmapencode_output(*cp, mapping, res, respos);
5709 if (x==enc_EXCEPTION)
5710 return -1;
5711 else if (x==enc_FAILED) {
5712 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5713 return -1;
5714 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005715 }
5716 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005717 *inpos = collendpos;
5718 break;
5719 default:
5720 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00005721 encoding, reason, p, size, exceptionObject,
5722 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005723 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005724 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005725 if (PyBytes_Check(repunicode)) {
5726 /* Directly copy bytes result to output. */
5727 Py_ssize_t outsize = PyBytes_Size(*res);
5728 Py_ssize_t requiredsize;
5729 repsize = PyBytes_Size(repunicode);
5730 requiredsize = *respos + repsize;
5731 if (requiredsize > outsize)
5732 /* Make room for all additional bytes. */
5733 if (charmapencode_resize(res, respos, requiredsize)) {
5734 Py_DECREF(repunicode);
5735 return -1;
5736 }
5737 memcpy(PyBytes_AsString(*res) + *respos,
5738 PyBytes_AsString(repunicode), repsize);
5739 *respos += repsize;
5740 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005741 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00005742 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005743 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005744 /* generate replacement */
5745 repsize = PyUnicode_GET_SIZE(repunicode);
5746 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005747 x = charmapencode_output(*uni2, mapping, res, respos);
5748 if (x==enc_EXCEPTION) {
5749 return -1;
5750 }
5751 else if (x==enc_FAILED) {
5752 Py_DECREF(repunicode);
5753 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5754 return -1;
5755 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005756 }
5757 *inpos = newpos;
5758 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005759 }
5760 return 0;
5761}
5762
Guido van Rossumd57fd912000-03-10 22:53:23 +00005763PyObject *PyUnicode_EncodeCharmap(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00005764 Py_ssize_t size,
5765 PyObject *mapping,
5766 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005767{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005768 /* output object */
5769 PyObject *res = NULL;
5770 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005771 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005772 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005773 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005774 PyObject *errorHandler = NULL;
5775 PyObject *exc = NULL;
5776 /* the following variable is used for caching string comparisons
5777 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
5778 * 3=ignore, 4=xmlcharrefreplace */
5779 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005780
5781 /* Default to Latin-1 */
5782 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005783 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005784
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005785 /* allocate enough for a simple encoding without
5786 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00005787 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005788 if (res == NULL)
5789 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00005790 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005791 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005792
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005793 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005794 /* try to encode it */
5795 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
5796 if (x==enc_EXCEPTION) /* error */
5797 goto onError;
5798 if (x==enc_FAILED) { /* unencodable character */
5799 if (charmap_encoding_error(p, size, &inpos, mapping,
5800 &exc,
5801 &known_errorHandler, &errorHandler, errors,
5802 &res, &respos)) {
5803 goto onError;
5804 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005805 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005806 else
5807 /* done with this character => adjust input position */
5808 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005809 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005810
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005811 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00005812 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005813 if (_PyBytes_Resize(&res, respos) < 0)
5814 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005815
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005816 Py_XDECREF(exc);
5817 Py_XDECREF(errorHandler);
5818 return res;
5819
Benjamin Peterson29060642009-01-31 22:14:21 +00005820 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005821 Py_XDECREF(res);
5822 Py_XDECREF(exc);
5823 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005824 return NULL;
5825}
5826
5827PyObject *PyUnicode_AsCharmapString(PyObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00005828 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005829{
5830 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005831 PyErr_BadArgument();
5832 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005833 }
5834 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005835 PyUnicode_GET_SIZE(unicode),
5836 mapping,
5837 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005838}
5839
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005840/* create or adjust a UnicodeTranslateError */
5841static void make_translate_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005842 const Py_UNICODE *unicode, Py_ssize_t size,
5843 Py_ssize_t startpos, Py_ssize_t endpos,
5844 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005845{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005846 if (*exceptionObject == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005847 *exceptionObject = PyUnicodeTranslateError_Create(
Benjamin Peterson29060642009-01-31 22:14:21 +00005848 unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005849 }
5850 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005851 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
5852 goto onError;
5853 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
5854 goto onError;
5855 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
5856 goto onError;
5857 return;
5858 onError:
5859 Py_DECREF(*exceptionObject);
5860 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005861 }
5862}
5863
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005864/* raises a UnicodeTranslateError */
5865static void raise_translate_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005866 const Py_UNICODE *unicode, Py_ssize_t size,
5867 Py_ssize_t startpos, Py_ssize_t endpos,
5868 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005869{
5870 make_translate_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005871 unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005872 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005873 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005874}
5875
5876/* error handling callback helper:
5877 build arguments, call the callback and check the arguments,
5878 put the result into newpos and return the replacement string, which
5879 has to be freed by the caller */
5880static PyObject *unicode_translate_call_errorhandler(const char *errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00005881 PyObject **errorHandler,
5882 const char *reason,
5883 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
5884 Py_ssize_t startpos, Py_ssize_t endpos,
5885 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005886{
Benjamin Peterson142957c2008-07-04 19:55:29 +00005887 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005888
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005889 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005890 PyObject *restuple;
5891 PyObject *resunicode;
5892
5893 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005894 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005895 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005896 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005897 }
5898
5899 make_translate_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005900 unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005901 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005902 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005903
5904 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00005905 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005906 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005907 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005908 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00005909 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00005910 Py_DECREF(restuple);
5911 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005912 }
5913 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00005914 &resunicode, &i_newpos)) {
5915 Py_DECREF(restuple);
5916 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005917 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00005918 if (i_newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005919 *newpos = size+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005920 else
5921 *newpos = i_newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005922 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005923 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
5924 Py_DECREF(restuple);
5925 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005926 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005927 Py_INCREF(resunicode);
5928 Py_DECREF(restuple);
5929 return resunicode;
5930}
5931
5932/* Lookup the character ch in the mapping and put the result in result,
5933 which must be decrefed by the caller.
5934 Return 0 on success, -1 on error */
5935static
5936int charmaptranslate_lookup(Py_UNICODE c, PyObject *mapping, PyObject **result)
5937{
Christian Heimes217cfd12007-12-02 14:31:20 +00005938 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005939 PyObject *x;
5940
5941 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005942 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005943 x = PyObject_GetItem(mapping, w);
5944 Py_DECREF(w);
5945 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005946 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5947 /* No mapping found means: use 1:1 mapping. */
5948 PyErr_Clear();
5949 *result = NULL;
5950 return 0;
5951 } else
5952 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005953 }
5954 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005955 *result = x;
5956 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005957 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005958 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005959 long value = PyLong_AS_LONG(x);
5960 long max = PyUnicode_GetMax();
5961 if (value < 0 || value > max) {
5962 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00005963 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00005964 Py_DECREF(x);
5965 return -1;
5966 }
5967 *result = x;
5968 return 0;
5969 }
5970 else if (PyUnicode_Check(x)) {
5971 *result = x;
5972 return 0;
5973 }
5974 else {
5975 /* wrong return value */
5976 PyErr_SetString(PyExc_TypeError,
5977 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00005978 Py_DECREF(x);
5979 return -1;
5980 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005981}
5982/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00005983 if not reallocate and adjust various state variables.
5984 Return 0 on success, -1 on error */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005985static
Walter Dörwald4894c302003-10-24 14:25:28 +00005986int charmaptranslate_makespace(PyObject **outobj, Py_UNICODE **outp,
Benjamin Peterson29060642009-01-31 22:14:21 +00005987 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005988{
Martin v. Löwis18e16552006-02-15 17:27:45 +00005989 Py_ssize_t oldsize = PyUnicode_GET_SIZE(*outobj);
Walter Dörwald4894c302003-10-24 14:25:28 +00005990 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005991 /* remember old output position */
5992 Py_ssize_t outpos = *outp-PyUnicode_AS_UNICODE(*outobj);
5993 /* exponentially overallocate to minimize reallocations */
5994 if (requiredsize < 2 * oldsize)
5995 requiredsize = 2 * oldsize;
5996 if (PyUnicode_Resize(outobj, requiredsize) < 0)
5997 return -1;
5998 *outp = PyUnicode_AS_UNICODE(*outobj) + outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005999 }
6000 return 0;
6001}
6002/* lookup the character, put the result in the output string and adjust
6003 various state variables. Return a new reference to the object that
6004 was put in the output buffer in *result, or Py_None, if the mapping was
6005 undefined (in which case no character was written).
6006 The called must decref result.
6007 Return 0 on success, -1 on error. */
6008static
Walter Dörwald4894c302003-10-24 14:25:28 +00006009int charmaptranslate_output(const Py_UNICODE *startinp, const Py_UNICODE *curinp,
Benjamin Peterson29060642009-01-31 22:14:21 +00006010 Py_ssize_t insize, PyObject *mapping, PyObject **outobj, Py_UNICODE **outp,
6011 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006012{
Walter Dörwald4894c302003-10-24 14:25:28 +00006013 if (charmaptranslate_lookup(*curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00006014 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006015 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006016 /* not found => default to 1:1 mapping */
6017 *(*outp)++ = *curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006018 }
6019 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00006020 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00006021 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006022 /* no overflow check, because we know that the space is enough */
6023 *(*outp)++ = (Py_UNICODE)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006024 }
6025 else if (PyUnicode_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006026 Py_ssize_t repsize = PyUnicode_GET_SIZE(*res);
6027 if (repsize==1) {
6028 /* no overflow check, because we know that the space is enough */
6029 *(*outp)++ = *PyUnicode_AS_UNICODE(*res);
6030 }
6031 else if (repsize!=0) {
6032 /* more than one character */
6033 Py_ssize_t requiredsize = (*outp-PyUnicode_AS_UNICODE(*outobj)) +
6034 (insize - (curinp-startinp)) +
6035 repsize - 1;
6036 if (charmaptranslate_makespace(outobj, outp, requiredsize))
6037 return -1;
6038 memcpy(*outp, PyUnicode_AS_UNICODE(*res), sizeof(Py_UNICODE)*repsize);
6039 *outp += repsize;
6040 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006041 }
6042 else
Benjamin Peterson29060642009-01-31 22:14:21 +00006043 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006044 return 0;
6045}
6046
6047PyObject *PyUnicode_TranslateCharmap(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00006048 Py_ssize_t size,
6049 PyObject *mapping,
6050 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006051{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006052 /* output object */
6053 PyObject *res = NULL;
6054 /* pointers to the beginning and end+1 of input */
6055 const Py_UNICODE *startp = p;
6056 const Py_UNICODE *endp = p + size;
6057 /* pointer into the output */
6058 Py_UNICODE *str;
6059 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006060 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006061 char *reason = "character maps to <undefined>";
6062 PyObject *errorHandler = NULL;
6063 PyObject *exc = NULL;
6064 /* the following variable is used for caching string comparisons
6065 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
6066 * 3=ignore, 4=xmlcharrefreplace */
6067 int known_errorHandler = -1;
6068
Guido van Rossumd57fd912000-03-10 22:53:23 +00006069 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006070 PyErr_BadArgument();
6071 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006072 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006073
6074 /* allocate enough for a simple 1:1 translation without
6075 replacements, if we need more, we'll resize */
6076 res = PyUnicode_FromUnicode(NULL, size);
6077 if (res == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006078 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006079 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006080 return res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006081 str = PyUnicode_AS_UNICODE(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006082
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006083 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006084 /* try to encode it */
6085 PyObject *x = NULL;
6086 if (charmaptranslate_output(startp, p, size, mapping, &res, &str, &x)) {
6087 Py_XDECREF(x);
6088 goto onError;
6089 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006090 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00006091 if (x!=Py_None) /* it worked => adjust input pointer */
6092 ++p;
6093 else { /* untranslatable character */
6094 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
6095 Py_ssize_t repsize;
6096 Py_ssize_t newpos;
6097 Py_UNICODE *uni2;
6098 /* startpos for collecting untranslatable chars */
6099 const Py_UNICODE *collstart = p;
6100 const Py_UNICODE *collend = p+1;
6101 const Py_UNICODE *coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006102
Benjamin Peterson29060642009-01-31 22:14:21 +00006103 /* find all untranslatable characters */
6104 while (collend < endp) {
6105 if (charmaptranslate_lookup(*collend, mapping, &x))
6106 goto onError;
6107 Py_XDECREF(x);
6108 if (x!=Py_None)
6109 break;
6110 ++collend;
6111 }
6112 /* cache callback name lookup
6113 * (if not done yet, i.e. it's the first error) */
6114 if (known_errorHandler==-1) {
6115 if ((errors==NULL) || (!strcmp(errors, "strict")))
6116 known_errorHandler = 1;
6117 else if (!strcmp(errors, "replace"))
6118 known_errorHandler = 2;
6119 else if (!strcmp(errors, "ignore"))
6120 known_errorHandler = 3;
6121 else if (!strcmp(errors, "xmlcharrefreplace"))
6122 known_errorHandler = 4;
6123 else
6124 known_errorHandler = 0;
6125 }
6126 switch (known_errorHandler) {
6127 case 1: /* strict */
6128 raise_translate_exception(&exc, startp, size, collstart-startp, collend-startp, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006129 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006130 case 2: /* replace */
6131 /* No need to check for space, this is a 1:1 replacement */
6132 for (coll = collstart; coll<collend; ++coll)
6133 *str++ = '?';
6134 /* fall through */
6135 case 3: /* ignore */
6136 p = collend;
6137 break;
6138 case 4: /* xmlcharrefreplace */
6139 /* generate replacement (temporarily (mis)uses p) */
6140 for (p = collstart; p < collend; ++p) {
6141 char buffer[2+29+1+1];
6142 char *cp;
6143 sprintf(buffer, "&#%d;", (int)*p);
6144 if (charmaptranslate_makespace(&res, &str,
6145 (str-PyUnicode_AS_UNICODE(res))+strlen(buffer)+(endp-collend)))
6146 goto onError;
6147 for (cp = buffer; *cp; ++cp)
6148 *str++ = *cp;
6149 }
6150 p = collend;
6151 break;
6152 default:
6153 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
6154 reason, startp, size, &exc,
6155 collstart-startp, collend-startp, &newpos);
6156 if (repunicode == NULL)
6157 goto onError;
6158 /* generate replacement */
6159 repsize = PyUnicode_GET_SIZE(repunicode);
6160 if (charmaptranslate_makespace(&res, &str,
6161 (str-PyUnicode_AS_UNICODE(res))+repsize+(endp-collend))) {
6162 Py_DECREF(repunicode);
6163 goto onError;
6164 }
6165 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2)
6166 *str++ = *uni2;
6167 p = startp + newpos;
6168 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006169 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006170 }
6171 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006172 /* Resize if we allocated to much */
6173 respos = str-PyUnicode_AS_UNICODE(res);
Walter Dörwald4894c302003-10-24 14:25:28 +00006174 if (respos<PyUnicode_GET_SIZE(res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006175 if (PyUnicode_Resize(&res, respos) < 0)
6176 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006177 }
6178 Py_XDECREF(exc);
6179 Py_XDECREF(errorHandler);
6180 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006181
Benjamin Peterson29060642009-01-31 22:14:21 +00006182 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006183 Py_XDECREF(res);
6184 Py_XDECREF(exc);
6185 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006186 return NULL;
6187}
6188
6189PyObject *PyUnicode_Translate(PyObject *str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006190 PyObject *mapping,
6191 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006192{
6193 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00006194
Guido van Rossumd57fd912000-03-10 22:53:23 +00006195 str = PyUnicode_FromObject(str);
6196 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006197 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006198 result = PyUnicode_TranslateCharmap(PyUnicode_AS_UNICODE(str),
Benjamin Peterson29060642009-01-31 22:14:21 +00006199 PyUnicode_GET_SIZE(str),
6200 mapping,
6201 errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006202 Py_DECREF(str);
6203 return result;
Tim Petersced69f82003-09-16 20:30:58 +00006204
Benjamin Peterson29060642009-01-31 22:14:21 +00006205 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006206 Py_XDECREF(str);
6207 return NULL;
6208}
Tim Petersced69f82003-09-16 20:30:58 +00006209
Guido van Rossum9e896b32000-04-05 20:11:21 +00006210/* --- Decimal Encoder ---------------------------------------------------- */
6211
6212int PyUnicode_EncodeDecimal(Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00006213 Py_ssize_t length,
6214 char *output,
6215 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00006216{
6217 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006218 PyObject *errorHandler = NULL;
6219 PyObject *exc = NULL;
6220 const char *encoding = "decimal";
6221 const char *reason = "invalid decimal Unicode string";
6222 /* the following variable is used for caching string comparisons
6223 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6224 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00006225
6226 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006227 PyErr_BadArgument();
6228 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00006229 }
6230
6231 p = s;
6232 end = s + length;
6233 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006234 register Py_UNICODE ch = *p;
6235 int decimal;
6236 PyObject *repunicode;
6237 Py_ssize_t repsize;
6238 Py_ssize_t newpos;
6239 Py_UNICODE *uni2;
6240 Py_UNICODE *collstart;
6241 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00006242
Benjamin Peterson29060642009-01-31 22:14:21 +00006243 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006244 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00006245 ++p;
6246 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006247 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006248 decimal = Py_UNICODE_TODECIMAL(ch);
6249 if (decimal >= 0) {
6250 *output++ = '0' + decimal;
6251 ++p;
6252 continue;
6253 }
6254 if (0 < ch && ch < 256) {
6255 *output++ = (char)ch;
6256 ++p;
6257 continue;
6258 }
6259 /* All other characters are considered unencodable */
6260 collstart = p;
6261 collend = p+1;
6262 while (collend < end) {
6263 if ((0 < *collend && *collend < 256) ||
6264 !Py_UNICODE_ISSPACE(*collend) ||
6265 Py_UNICODE_TODECIMAL(*collend))
6266 break;
6267 }
6268 /* cache callback name lookup
6269 * (if not done yet, i.e. it's the first error) */
6270 if (known_errorHandler==-1) {
6271 if ((errors==NULL) || (!strcmp(errors, "strict")))
6272 known_errorHandler = 1;
6273 else if (!strcmp(errors, "replace"))
6274 known_errorHandler = 2;
6275 else if (!strcmp(errors, "ignore"))
6276 known_errorHandler = 3;
6277 else if (!strcmp(errors, "xmlcharrefreplace"))
6278 known_errorHandler = 4;
6279 else
6280 known_errorHandler = 0;
6281 }
6282 switch (known_errorHandler) {
6283 case 1: /* strict */
6284 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
6285 goto onError;
6286 case 2: /* replace */
6287 for (p = collstart; p < collend; ++p)
6288 *output++ = '?';
6289 /* fall through */
6290 case 3: /* ignore */
6291 p = collend;
6292 break;
6293 case 4: /* xmlcharrefreplace */
6294 /* generate replacement (temporarily (mis)uses p) */
6295 for (p = collstart; p < collend; ++p)
6296 output += sprintf(output, "&#%d;", (int)*p);
6297 p = collend;
6298 break;
6299 default:
6300 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
6301 encoding, reason, s, length, &exc,
6302 collstart-s, collend-s, &newpos);
6303 if (repunicode == NULL)
6304 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006305 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006306 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006307 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
6308 Py_DECREF(repunicode);
6309 goto onError;
6310 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006311 /* generate replacement */
6312 repsize = PyUnicode_GET_SIZE(repunicode);
6313 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
6314 Py_UNICODE ch = *uni2;
6315 if (Py_UNICODE_ISSPACE(ch))
6316 *output++ = ' ';
6317 else {
6318 decimal = Py_UNICODE_TODECIMAL(ch);
6319 if (decimal >= 0)
6320 *output++ = '0' + decimal;
6321 else if (0 < ch && ch < 256)
6322 *output++ = (char)ch;
6323 else {
6324 Py_DECREF(repunicode);
6325 raise_encode_exception(&exc, encoding,
6326 s, length, collstart-s, collend-s, reason);
6327 goto onError;
6328 }
6329 }
6330 }
6331 p = s + newpos;
6332 Py_DECREF(repunicode);
6333 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00006334 }
6335 /* 0-terminate the output string */
6336 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006337 Py_XDECREF(exc);
6338 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00006339 return 0;
6340
Benjamin Peterson29060642009-01-31 22:14:21 +00006341 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006342 Py_XDECREF(exc);
6343 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00006344 return -1;
6345}
6346
Guido van Rossumd57fd912000-03-10 22:53:23 +00006347/* --- Helpers ------------------------------------------------------------ */
6348
Eric Smith8c663262007-08-25 02:26:07 +00006349#include "stringlib/unicodedefs.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00006350#include "stringlib/fastsearch.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006351
Thomas Wouters477c8d52006-05-27 19:21:47 +00006352#include "stringlib/count.h"
6353#include "stringlib/find.h"
6354#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006355#include "stringlib/split.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00006356
Eric Smith5807c412008-05-11 21:00:57 +00006357#define _Py_InsertThousandsGrouping _PyUnicode_InsertThousandsGrouping
Eric Smitha3b1ac82009-04-03 14:45:06 +00006358#define _Py_InsertThousandsGroupingLocale _PyUnicode_InsertThousandsGroupingLocale
Eric Smith5807c412008-05-11 21:00:57 +00006359#include "stringlib/localeutil.h"
6360
Thomas Wouters477c8d52006-05-27 19:21:47 +00006361/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006362#define ADJUST_INDICES(start, end, len) \
6363 if (end > len) \
6364 end = len; \
6365 else if (end < 0) { \
6366 end += len; \
6367 if (end < 0) \
6368 end = 0; \
6369 } \
6370 if (start < 0) { \
6371 start += len; \
6372 if (start < 0) \
6373 start = 0; \
6374 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00006375
Martin v. Löwis18e16552006-02-15 17:27:45 +00006376Py_ssize_t PyUnicode_Count(PyObject *str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00006377 PyObject *substr,
6378 Py_ssize_t start,
6379 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006380{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006381 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006382 PyUnicodeObject* str_obj;
6383 PyUnicodeObject* sub_obj;
Tim Petersced69f82003-09-16 20:30:58 +00006384
Thomas Wouters477c8d52006-05-27 19:21:47 +00006385 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
6386 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00006387 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006388 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
6389 if (!sub_obj) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006390 Py_DECREF(str_obj);
6391 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006392 }
Tim Petersced69f82003-09-16 20:30:58 +00006393
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006394 ADJUST_INDICES(start, end, str_obj->length);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006395 result = stringlib_count(
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006396 str_obj->str + start, end - start, sub_obj->str, sub_obj->length,
6397 PY_SSIZE_T_MAX
Thomas Wouters477c8d52006-05-27 19:21:47 +00006398 );
6399
6400 Py_DECREF(sub_obj);
6401 Py_DECREF(str_obj);
6402
Guido van Rossumd57fd912000-03-10 22:53:23 +00006403 return result;
6404}
6405
Martin v. Löwis18e16552006-02-15 17:27:45 +00006406Py_ssize_t PyUnicode_Find(PyObject *str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00006407 PyObject *sub,
6408 Py_ssize_t start,
6409 Py_ssize_t end,
6410 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006411{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006412 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00006413
Guido van Rossumd57fd912000-03-10 22:53:23 +00006414 str = PyUnicode_FromObject(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006415 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00006416 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006417 sub = PyUnicode_FromObject(sub);
6418 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006419 Py_DECREF(str);
6420 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006421 }
Tim Petersced69f82003-09-16 20:30:58 +00006422
Thomas Wouters477c8d52006-05-27 19:21:47 +00006423 if (direction > 0)
6424 result = stringlib_find_slice(
6425 PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
6426 PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
6427 start, end
6428 );
6429 else
6430 result = stringlib_rfind_slice(
6431 PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
6432 PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
6433 start, end
6434 );
6435
Guido van Rossumd57fd912000-03-10 22:53:23 +00006436 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006437 Py_DECREF(sub);
6438
Guido van Rossumd57fd912000-03-10 22:53:23 +00006439 return result;
6440}
6441
Tim Petersced69f82003-09-16 20:30:58 +00006442static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006443int tailmatch(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006444 PyUnicodeObject *substring,
6445 Py_ssize_t start,
6446 Py_ssize_t end,
6447 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006448{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006449 if (substring->length == 0)
6450 return 1;
6451
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006452 ADJUST_INDICES(start, end, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006453 end -= substring->length;
6454 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00006455 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006456
6457 if (direction > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006458 if (Py_UNICODE_MATCH(self, end, substring))
6459 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006460 } else {
6461 if (Py_UNICODE_MATCH(self, start, substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00006462 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006463 }
6464
6465 return 0;
6466}
6467
Martin v. Löwis18e16552006-02-15 17:27:45 +00006468Py_ssize_t PyUnicode_Tailmatch(PyObject *str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006469 PyObject *substr,
6470 Py_ssize_t start,
6471 Py_ssize_t end,
6472 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006473{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006474 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00006475
Guido van Rossumd57fd912000-03-10 22:53:23 +00006476 str = PyUnicode_FromObject(str);
6477 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006478 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006479 substr = PyUnicode_FromObject(substr);
6480 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006481 Py_DECREF(str);
6482 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006483 }
Tim Petersced69f82003-09-16 20:30:58 +00006484
Guido van Rossumd57fd912000-03-10 22:53:23 +00006485 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006486 (PyUnicodeObject *)substr,
6487 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006488 Py_DECREF(str);
6489 Py_DECREF(substr);
6490 return result;
6491}
6492
Guido van Rossumd57fd912000-03-10 22:53:23 +00006493/* Apply fixfct filter to the Unicode object self and return a
6494 reference to the modified object */
6495
Tim Petersced69f82003-09-16 20:30:58 +00006496static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006497PyObject *fixup(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006498 int (*fixfct)(PyUnicodeObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00006499{
6500
6501 PyUnicodeObject *u;
6502
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006503 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006504 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006505 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006506
6507 Py_UNICODE_COPY(u->str, self->str, self->length);
6508
Tim Peters7a29bd52001-09-12 03:03:31 +00006509 if (!fixfct(u) && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006510 /* fixfct should return TRUE if it modified the buffer. If
6511 FALSE, return a reference to the original buffer instead
6512 (to save space, not time) */
6513 Py_INCREF(self);
6514 Py_DECREF(u);
6515 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006516 }
6517 return (PyObject*) u;
6518}
6519
Tim Petersced69f82003-09-16 20:30:58 +00006520static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006521int fixupper(PyUnicodeObject *self)
6522{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006523 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006524 Py_UNICODE *s = self->str;
6525 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006526
Guido van Rossumd57fd912000-03-10 22:53:23 +00006527 while (len-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006528 register Py_UNICODE ch;
Tim Petersced69f82003-09-16 20:30:58 +00006529
Benjamin Peterson29060642009-01-31 22:14:21 +00006530 ch = Py_UNICODE_TOUPPER(*s);
6531 if (ch != *s) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006532 status = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006533 *s = ch;
6534 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006535 s++;
6536 }
6537
6538 return status;
6539}
6540
Tim Petersced69f82003-09-16 20:30:58 +00006541static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006542int fixlower(PyUnicodeObject *self)
6543{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006544 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006545 Py_UNICODE *s = self->str;
6546 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006547
Guido van Rossumd57fd912000-03-10 22:53:23 +00006548 while (len-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006549 register Py_UNICODE ch;
Tim Petersced69f82003-09-16 20:30:58 +00006550
Benjamin Peterson29060642009-01-31 22:14:21 +00006551 ch = Py_UNICODE_TOLOWER(*s);
6552 if (ch != *s) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006553 status = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006554 *s = ch;
6555 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006556 s++;
6557 }
6558
6559 return status;
6560}
6561
Tim Petersced69f82003-09-16 20:30:58 +00006562static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006563int fixswapcase(PyUnicodeObject *self)
6564{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006565 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006566 Py_UNICODE *s = self->str;
6567 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006568
Guido van Rossumd57fd912000-03-10 22:53:23 +00006569 while (len-- > 0) {
6570 if (Py_UNICODE_ISUPPER(*s)) {
6571 *s = Py_UNICODE_TOLOWER(*s);
6572 status = 1;
6573 } else if (Py_UNICODE_ISLOWER(*s)) {
6574 *s = Py_UNICODE_TOUPPER(*s);
6575 status = 1;
6576 }
6577 s++;
6578 }
6579
6580 return status;
6581}
6582
Tim Petersced69f82003-09-16 20:30:58 +00006583static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006584int fixcapitalize(PyUnicodeObject *self)
6585{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006586 Py_ssize_t len = self->length;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006587 Py_UNICODE *s = self->str;
6588 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006589
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006590 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006591 return 0;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006592 if (Py_UNICODE_ISLOWER(*s)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006593 *s = Py_UNICODE_TOUPPER(*s);
6594 status = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006595 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006596 s++;
6597 while (--len > 0) {
6598 if (Py_UNICODE_ISUPPER(*s)) {
6599 *s = Py_UNICODE_TOLOWER(*s);
6600 status = 1;
6601 }
6602 s++;
6603 }
6604 return status;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006605}
6606
6607static
6608int fixtitle(PyUnicodeObject *self)
6609{
6610 register Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
6611 register Py_UNICODE *e;
6612 int previous_is_cased;
6613
6614 /* Shortcut for single character strings */
6615 if (PyUnicode_GET_SIZE(self) == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006616 Py_UNICODE ch = Py_UNICODE_TOTITLE(*p);
6617 if (*p != ch) {
6618 *p = ch;
6619 return 1;
6620 }
6621 else
6622 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006623 }
Tim Petersced69f82003-09-16 20:30:58 +00006624
Guido van Rossumd57fd912000-03-10 22:53:23 +00006625 e = p + PyUnicode_GET_SIZE(self);
6626 previous_is_cased = 0;
6627 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006628 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00006629
Benjamin Peterson29060642009-01-31 22:14:21 +00006630 if (previous_is_cased)
6631 *p = Py_UNICODE_TOLOWER(ch);
6632 else
6633 *p = Py_UNICODE_TOTITLE(ch);
Tim Petersced69f82003-09-16 20:30:58 +00006634
Benjamin Peterson29060642009-01-31 22:14:21 +00006635 if (Py_UNICODE_ISLOWER(ch) ||
6636 Py_UNICODE_ISUPPER(ch) ||
6637 Py_UNICODE_ISTITLE(ch))
6638 previous_is_cased = 1;
6639 else
6640 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006641 }
6642 return 1;
6643}
6644
Tim Peters8ce9f162004-08-27 01:49:32 +00006645PyObject *
6646PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006647{
Skip Montanaro6543b452004-09-16 03:28:13 +00006648 const Py_UNICODE blank = ' ';
6649 const Py_UNICODE *sep = &blank;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006650 Py_ssize_t seplen = 1;
Tim Peters05eba1f2004-08-27 21:32:02 +00006651 PyUnicodeObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00006652 Py_UNICODE *res_p; /* pointer to free byte in res's string area */
6653 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006654 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
6655 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00006656 PyObject *item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006657 Py_ssize_t sz, i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006658
Tim Peters05eba1f2004-08-27 21:32:02 +00006659 fseq = PySequence_Fast(seq, "");
6660 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006661 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00006662 }
6663
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006664 /* NOTE: the following code can't call back into Python code,
6665 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00006666 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006667
Tim Peters05eba1f2004-08-27 21:32:02 +00006668 seqlen = PySequence_Fast_GET_SIZE(fseq);
6669 /* If empty sequence, return u"". */
6670 if (seqlen == 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006671 res = _PyUnicode_New(0); /* empty sequence; return u"" */
6672 goto Done;
Tim Peters05eba1f2004-08-27 21:32:02 +00006673 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006674 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00006675 /* If singleton sequence with an exact Unicode, return that. */
6676 if (seqlen == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006677 item = items[0];
6678 if (PyUnicode_CheckExact(item)) {
6679 Py_INCREF(item);
6680 res = (PyUnicodeObject *)item;
6681 goto Done;
6682 }
Tim Peters8ce9f162004-08-27 01:49:32 +00006683 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006684 else {
6685 /* Set up sep and seplen */
6686 if (separator == NULL) {
6687 sep = &blank;
6688 seplen = 1;
Tim Peters05eba1f2004-08-27 21:32:02 +00006689 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006690 else {
6691 if (!PyUnicode_Check(separator)) {
6692 PyErr_Format(PyExc_TypeError,
6693 "separator: expected str instance,"
6694 " %.80s found",
6695 Py_TYPE(separator)->tp_name);
6696 goto onError;
6697 }
6698 sep = PyUnicode_AS_UNICODE(separator);
6699 seplen = PyUnicode_GET_SIZE(separator);
Tim Peters05eba1f2004-08-27 21:32:02 +00006700 }
6701 }
6702
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006703 /* There are at least two things to join, or else we have a subclass
6704 * of str in the sequence.
6705 * Do a pre-pass to figure out the total amount of space we'll
6706 * need (sz), and see whether all argument are strings.
6707 */
6708 sz = 0;
6709 for (i = 0; i < seqlen; i++) {
6710 const Py_ssize_t old_sz = sz;
6711 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00006712 if (!PyUnicode_Check(item)) {
6713 PyErr_Format(PyExc_TypeError,
6714 "sequence item %zd: expected str instance,"
6715 " %.80s found",
6716 i, Py_TYPE(item)->tp_name);
6717 goto onError;
6718 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006719 sz += PyUnicode_GET_SIZE(item);
6720 if (i != 0)
6721 sz += seplen;
6722 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
6723 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00006724 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006725 goto onError;
6726 }
6727 }
Tim Petersced69f82003-09-16 20:30:58 +00006728
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006729 res = _PyUnicode_New(sz);
6730 if (res == NULL)
6731 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00006732
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006733 /* Catenate everything. */
6734 res_p = PyUnicode_AS_UNICODE(res);
6735 for (i = 0; i < seqlen; ++i) {
6736 Py_ssize_t itemlen;
6737 item = items[i];
6738 itemlen = PyUnicode_GET_SIZE(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00006739 /* Copy item, and maybe the separator. */
6740 if (i) {
6741 Py_UNICODE_COPY(res_p, sep, seplen);
6742 res_p += seplen;
6743 }
6744 Py_UNICODE_COPY(res_p, PyUnicode_AS_UNICODE(item), itemlen);
6745 res_p += itemlen;
Tim Peters05eba1f2004-08-27 21:32:02 +00006746 }
Tim Peters8ce9f162004-08-27 01:49:32 +00006747
Benjamin Peterson29060642009-01-31 22:14:21 +00006748 Done:
Tim Peters05eba1f2004-08-27 21:32:02 +00006749 Py_DECREF(fseq);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006750 return (PyObject *)res;
6751
Benjamin Peterson29060642009-01-31 22:14:21 +00006752 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00006753 Py_DECREF(fseq);
Tim Peters8ce9f162004-08-27 01:49:32 +00006754 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006755 return NULL;
6756}
6757
Tim Petersced69f82003-09-16 20:30:58 +00006758static
6759PyUnicodeObject *pad(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006760 Py_ssize_t left,
6761 Py_ssize_t right,
6762 Py_UNICODE fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006763{
6764 PyUnicodeObject *u;
6765
6766 if (left < 0)
6767 left = 0;
6768 if (right < 0)
6769 right = 0;
6770
Tim Peters7a29bd52001-09-12 03:03:31 +00006771 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006772 Py_INCREF(self);
6773 return self;
6774 }
6775
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006776 if (left > PY_SSIZE_T_MAX - self->length ||
6777 right > PY_SSIZE_T_MAX - (left + self->length)) {
6778 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
6779 return NULL;
6780 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006781 u = _PyUnicode_New(left + self->length + right);
6782 if (u) {
6783 if (left)
6784 Py_UNICODE_FILL(u->str, fill, left);
6785 Py_UNICODE_COPY(u->str + left, self->str, self->length);
6786 if (right)
6787 Py_UNICODE_FILL(u->str + left + self->length, fill, right);
6788 }
6789
6790 return u;
6791}
6792
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006793PyObject *PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006794{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006795 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006796
6797 string = PyUnicode_FromObject(string);
6798 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006799 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006800
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006801 list = stringlib_splitlines(
6802 (PyObject*) string, PyUnicode_AS_UNICODE(string),
6803 PyUnicode_GET_SIZE(string), keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006804
6805 Py_DECREF(string);
6806 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006807}
6808
Tim Petersced69f82003-09-16 20:30:58 +00006809static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006810PyObject *split(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006811 PyUnicodeObject *substring,
6812 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006813{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006814 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006815 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006816
Guido van Rossumd57fd912000-03-10 22:53:23 +00006817 if (substring == NULL)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006818 return stringlib_split_whitespace(
6819 (PyObject*) self, self->str, self->length, maxcount
6820 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00006821
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006822 return stringlib_split(
6823 (PyObject*) self, self->str, self->length,
6824 substring->str, substring->length,
6825 maxcount
6826 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00006827}
6828
Tim Petersced69f82003-09-16 20:30:58 +00006829static
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006830PyObject *rsplit(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006831 PyUnicodeObject *substring,
6832 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006833{
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006834 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006835 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006836
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006837 if (substring == NULL)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006838 return stringlib_rsplit_whitespace(
6839 (PyObject*) self, self->str, self->length, maxcount
6840 );
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006841
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006842 return stringlib_rsplit(
6843 (PyObject*) self, self->str, self->length,
6844 substring->str, substring->length,
6845 maxcount
6846 );
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006847}
6848
6849static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006850PyObject *replace(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006851 PyUnicodeObject *str1,
6852 PyUnicodeObject *str2,
6853 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006854{
6855 PyUnicodeObject *u;
6856
6857 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006858 maxcount = PY_SSIZE_T_MAX;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006859 else if (maxcount == 0 || self->length == 0)
6860 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006861
Thomas Wouters477c8d52006-05-27 19:21:47 +00006862 if (str1->length == str2->length) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +00006863 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006864 /* same length */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006865 if (str1->length == 0)
6866 goto nothing;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006867 if (str1->length == 1) {
6868 /* replace characters */
6869 Py_UNICODE u1, u2;
6870 if (!findchar(self->str, self->length, str1->str[0]))
6871 goto nothing;
6872 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
6873 if (!u)
6874 return NULL;
6875 Py_UNICODE_COPY(u->str, self->str, self->length);
6876 u1 = str1->str[0];
6877 u2 = str2->str[0];
6878 for (i = 0; i < u->length; i++)
6879 if (u->str[i] == u1) {
6880 if (--maxcount < 0)
6881 break;
6882 u->str[i] = u2;
6883 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006884 } else {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006885 i = stringlib_find(
6886 self->str, self->length, str1->str, str1->length, 0
Guido van Rossumd57fd912000-03-10 22:53:23 +00006887 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00006888 if (i < 0)
6889 goto nothing;
6890 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
6891 if (!u)
6892 return NULL;
6893 Py_UNICODE_COPY(u->str, self->str, self->length);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006894
6895 /* change everything in-place, starting with this one */
6896 Py_UNICODE_COPY(u->str+i, str2->str, str2->length);
6897 i += str1->length;
6898
6899 while ( --maxcount > 0) {
6900 i = stringlib_find(self->str+i, self->length-i,
6901 str1->str, str1->length,
6902 i);
6903 if (i == -1)
6904 break;
6905 Py_UNICODE_COPY(u->str+i, str2->str, str2->length);
6906 i += str1->length;
6907 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006908 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006909 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006910
6911 Py_ssize_t n, i, j, e;
6912 Py_ssize_t product, new_size, delta;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006913 Py_UNICODE *p;
6914
6915 /* replace strings */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006916 n = stringlib_count(self->str, self->length, str1->str, str1->length,
6917 maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006918 if (n == 0)
6919 goto nothing;
6920 /* new_size = self->length + n * (str2->length - str1->length)); */
6921 delta = (str2->length - str1->length);
6922 if (delta == 0) {
6923 new_size = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006924 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006925 product = n * (str2->length - str1->length);
6926 if ((product / (str2->length - str1->length)) != n) {
6927 PyErr_SetString(PyExc_OverflowError,
6928 "replace string is too long");
6929 return NULL;
6930 }
6931 new_size = self->length + product;
6932 if (new_size < 0) {
6933 PyErr_SetString(PyExc_OverflowError,
6934 "replace string is too long");
6935 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006936 }
6937 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00006938 u = _PyUnicode_New(new_size);
6939 if (!u)
6940 return NULL;
6941 i = 0;
6942 p = u->str;
6943 e = self->length - str1->length;
6944 if (str1->length > 0) {
6945 while (n-- > 0) {
6946 /* look for next match */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006947 j = stringlib_find(self->str+i, self->length-i,
6948 str1->str, str1->length,
6949 i);
6950 if (j == -1)
6951 break;
6952 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006953 /* copy unchanged part [i:j] */
6954 Py_UNICODE_COPY(p, self->str+i, j-i);
6955 p += j - i;
6956 }
6957 /* copy substitution string */
6958 if (str2->length > 0) {
6959 Py_UNICODE_COPY(p, str2->str, str2->length);
6960 p += str2->length;
6961 }
6962 i = j + str1->length;
6963 }
6964 if (i < self->length)
6965 /* copy tail [i:] */
6966 Py_UNICODE_COPY(p, self->str+i, self->length-i);
6967 } else {
6968 /* interleave */
6969 while (n > 0) {
6970 Py_UNICODE_COPY(p, str2->str, str2->length);
6971 p += str2->length;
6972 if (--n <= 0)
6973 break;
6974 *p++ = self->str[i++];
6975 }
6976 Py_UNICODE_COPY(p, self->str+i, self->length-i);
6977 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006978 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006979 return (PyObject *) u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006980
Benjamin Peterson29060642009-01-31 22:14:21 +00006981 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00006982 /* nothing to replace; return original string (when possible) */
6983 if (PyUnicode_CheckExact(self)) {
6984 Py_INCREF(self);
6985 return (PyObject *) self;
6986 }
6987 return PyUnicode_FromUnicode(self->str, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006988}
6989
6990/* --- Unicode Object Methods --------------------------------------------- */
6991
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006992PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00006993 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00006994\n\
6995Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006996characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00006997
6998static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00006999unicode_title(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007000{
Guido van Rossumd57fd912000-03-10 22:53:23 +00007001 return fixup(self, fixtitle);
7002}
7003
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007004PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007005 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007006\n\
7007Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +00007008have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007009
7010static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007011unicode_capitalize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007012{
Guido van Rossumd57fd912000-03-10 22:53:23 +00007013 return fixup(self, fixcapitalize);
7014}
7015
7016#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007017PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007018 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007019\n\
7020Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007021normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007022
7023static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007024unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007025{
7026 PyObject *list;
7027 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007028 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007029
Guido van Rossumd57fd912000-03-10 22:53:23 +00007030 /* Split into words */
7031 list = split(self, NULL, -1);
7032 if (!list)
7033 return NULL;
7034
7035 /* Capitalize each word */
7036 for (i = 0; i < PyList_GET_SIZE(list); i++) {
7037 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00007038 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007039 if (item == NULL)
7040 goto onError;
7041 Py_DECREF(PyList_GET_ITEM(list, i));
7042 PyList_SET_ITEM(list, i, item);
7043 }
7044
7045 /* Join the words to form a new string */
7046 item = PyUnicode_Join(NULL, list);
7047
Benjamin Peterson29060642009-01-31 22:14:21 +00007048 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007049 Py_DECREF(list);
7050 return (PyObject *)item;
7051}
7052#endif
7053
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007054/* Argument converter. Coerces to a single unicode character */
7055
7056static int
7057convert_uc(PyObject *obj, void *addr)
7058{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007059 Py_UNICODE *fillcharloc = (Py_UNICODE *)addr;
7060 PyObject *uniobj;
7061 Py_UNICODE *unistr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007062
Benjamin Peterson14339b62009-01-31 16:36:08 +00007063 uniobj = PyUnicode_FromObject(obj);
7064 if (uniobj == NULL) {
7065 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00007066 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007067 return 0;
7068 }
7069 if (PyUnicode_GET_SIZE(uniobj) != 1) {
7070 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00007071 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007072 Py_DECREF(uniobj);
7073 return 0;
7074 }
7075 unistr = PyUnicode_AS_UNICODE(uniobj);
7076 *fillcharloc = unistr[0];
7077 Py_DECREF(uniobj);
7078 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007079}
7080
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007081PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007082 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007083\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007084Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007085done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007086
7087static PyObject *
7088unicode_center(PyUnicodeObject *self, PyObject *args)
7089{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007090 Py_ssize_t marg, left;
7091 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007092 Py_UNICODE fillchar = ' ';
Guido van Rossumd57fd912000-03-10 22:53:23 +00007093
Thomas Woutersde017742006-02-16 19:34:37 +00007094 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007095 return NULL;
7096
Tim Peters7a29bd52001-09-12 03:03:31 +00007097 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00007098 Py_INCREF(self);
7099 return (PyObject*) self;
7100 }
7101
7102 marg = width - self->length;
7103 left = marg / 2 + (marg & width & 1);
7104
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007105 return (PyObject*) pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007106}
7107
Marc-André Lemburge5034372000-08-08 08:04:29 +00007108#if 0
7109
7110/* This code should go into some future Unicode collation support
7111 module. The basic comparison should compare ordinals on a naive
Georg Brandlc6c31782009-06-08 13:41:29 +00007112 basis (this is what Java does and thus Jython too). */
Marc-André Lemburge5034372000-08-08 08:04:29 +00007113
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007114/* speedy UTF-16 code point order comparison */
7115/* gleaned from: */
7116/* http://www-4.ibm.com/software/developer/library/utf16.html?dwzone=unicode */
7117
Marc-André Lemburge12896e2000-07-07 17:51:08 +00007118static short utf16Fixup[32] =
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007119{
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007120 0, 0, 0, 0, 0, 0, 0, 0,
Tim Petersced69f82003-09-16 20:30:58 +00007121 0, 0, 0, 0, 0, 0, 0, 0,
7122 0, 0, 0, 0, 0, 0, 0, 0,
Marc-André Lemburge12896e2000-07-07 17:51:08 +00007123 0, 0, 0, 0x2000, -0x800, -0x800, -0x800, -0x800
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007124};
7125
Guido van Rossumd57fd912000-03-10 22:53:23 +00007126static int
7127unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
7128{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007129 Py_ssize_t len1, len2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007130
Guido van Rossumd57fd912000-03-10 22:53:23 +00007131 Py_UNICODE *s1 = str1->str;
7132 Py_UNICODE *s2 = str2->str;
7133
7134 len1 = str1->length;
7135 len2 = str2->length;
Tim Petersced69f82003-09-16 20:30:58 +00007136
Guido van Rossumd57fd912000-03-10 22:53:23 +00007137 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00007138 Py_UNICODE c1, c2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007139
7140 c1 = *s1++;
7141 c2 = *s2++;
Fredrik Lundh45714e92001-06-26 16:39:36 +00007142
Benjamin Peterson29060642009-01-31 22:14:21 +00007143 if (c1 > (1<<11) * 26)
7144 c1 += utf16Fixup[c1>>11];
7145 if (c2 > (1<<11) * 26)
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007146 c2 += utf16Fixup[c2>>11];
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007147 /* now c1 and c2 are in UTF-32-compatible order */
Fredrik Lundh45714e92001-06-26 16:39:36 +00007148
7149 if (c1 != c2)
7150 return (c1 < c2) ? -1 : 1;
Tim Petersced69f82003-09-16 20:30:58 +00007151
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00007152 len1--; len2--;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007153 }
7154
7155 return (len1 < len2) ? -1 : (len1 != len2);
7156}
7157
Marc-André Lemburge5034372000-08-08 08:04:29 +00007158#else
7159
7160static int
7161unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
7162{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007163 register Py_ssize_t len1, len2;
Marc-André Lemburge5034372000-08-08 08:04:29 +00007164
7165 Py_UNICODE *s1 = str1->str;
7166 Py_UNICODE *s2 = str2->str;
7167
7168 len1 = str1->length;
7169 len2 = str2->length;
Tim Petersced69f82003-09-16 20:30:58 +00007170
Marc-André Lemburge5034372000-08-08 08:04:29 +00007171 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00007172 Py_UNICODE c1, c2;
Marc-André Lemburge5034372000-08-08 08:04:29 +00007173
Fredrik Lundh45714e92001-06-26 16:39:36 +00007174 c1 = *s1++;
7175 c2 = *s2++;
7176
7177 if (c1 != c2)
7178 return (c1 < c2) ? -1 : 1;
7179
Marc-André Lemburge5034372000-08-08 08:04:29 +00007180 len1--; len2--;
7181 }
7182
7183 return (len1 < len2) ? -1 : (len1 != len2);
7184}
7185
7186#endif
7187
Guido van Rossumd57fd912000-03-10 22:53:23 +00007188int PyUnicode_Compare(PyObject *left,
Benjamin Peterson29060642009-01-31 22:14:21 +00007189 PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007190{
Guido van Rossum09dc34f2007-05-04 04:17:33 +00007191 if (PyUnicode_Check(left) && PyUnicode_Check(right))
7192 return unicode_compare((PyUnicodeObject *)left,
7193 (PyUnicodeObject *)right);
Guido van Rossum09dc34f2007-05-04 04:17:33 +00007194 PyErr_Format(PyExc_TypeError,
7195 "Can't compare %.100s and %.100s",
7196 left->ob_type->tp_name,
7197 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007198 return -1;
7199}
7200
Martin v. Löwis5b222132007-06-10 09:51:05 +00007201int
7202PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
7203{
7204 int i;
7205 Py_UNICODE *id;
7206 assert(PyUnicode_Check(uni));
7207 id = PyUnicode_AS_UNICODE(uni);
7208 /* Compare Unicode string and source character set string */
7209 for (i = 0; id[i] && str[i]; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00007210 if (id[i] != str[i])
7211 return ((int)id[i] < (int)str[i]) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +00007212 /* This check keeps Python strings that end in '\0' from comparing equal
7213 to C strings identical up to that point. */
Benjamin Petersona23831f2010-04-25 21:54:00 +00007214 if (PyUnicode_GET_SIZE(uni) != i || id[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00007215 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00007216 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00007217 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00007218 return 0;
7219}
7220
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007221
Benjamin Peterson29060642009-01-31 22:14:21 +00007222#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +00007223 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007224
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007225PyObject *PyUnicode_RichCompare(PyObject *left,
7226 PyObject *right,
7227 int op)
7228{
7229 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007230
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007231 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
7232 PyObject *v;
7233 if (((PyUnicodeObject *) left)->length !=
7234 ((PyUnicodeObject *) right)->length) {
7235 if (op == Py_EQ) {
7236 Py_INCREF(Py_False);
7237 return Py_False;
7238 }
7239 if (op == Py_NE) {
7240 Py_INCREF(Py_True);
7241 return Py_True;
7242 }
7243 }
7244 if (left == right)
7245 result = 0;
7246 else
7247 result = unicode_compare((PyUnicodeObject *)left,
7248 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007249
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007250 /* Convert the return value to a Boolean */
7251 switch (op) {
7252 case Py_EQ:
7253 v = TEST_COND(result == 0);
7254 break;
7255 case Py_NE:
7256 v = TEST_COND(result != 0);
7257 break;
7258 case Py_LE:
7259 v = TEST_COND(result <= 0);
7260 break;
7261 case Py_GE:
7262 v = TEST_COND(result >= 0);
7263 break;
7264 case Py_LT:
7265 v = TEST_COND(result == -1);
7266 break;
7267 case Py_GT:
7268 v = TEST_COND(result == 1);
7269 break;
7270 default:
7271 PyErr_BadArgument();
7272 return NULL;
7273 }
7274 Py_INCREF(v);
7275 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007276 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007277
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007278 Py_INCREF(Py_NotImplemented);
7279 return Py_NotImplemented;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007280}
7281
Guido van Rossum403d68b2000-03-13 15:55:09 +00007282int PyUnicode_Contains(PyObject *container,
Benjamin Peterson29060642009-01-31 22:14:21 +00007283 PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +00007284{
Thomas Wouters477c8d52006-05-27 19:21:47 +00007285 PyObject *str, *sub;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007286 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007287
7288 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +00007289 sub = PyUnicode_FromObject(element);
7290 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007291 PyErr_Format(PyExc_TypeError,
7292 "'in <string>' requires string as left operand, not %s",
7293 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007294 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007295 }
7296
Thomas Wouters477c8d52006-05-27 19:21:47 +00007297 str = PyUnicode_FromObject(container);
7298 if (!str) {
7299 Py_DECREF(sub);
7300 return -1;
7301 }
7302
7303 result = stringlib_contains_obj(str, sub);
7304
7305 Py_DECREF(str);
7306 Py_DECREF(sub);
7307
Guido van Rossum403d68b2000-03-13 15:55:09 +00007308 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007309}
7310
Guido van Rossumd57fd912000-03-10 22:53:23 +00007311/* Concat to string or Unicode object giving a new Unicode object. */
7312
7313PyObject *PyUnicode_Concat(PyObject *left,
Benjamin Peterson29060642009-01-31 22:14:21 +00007314 PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007315{
7316 PyUnicodeObject *u = NULL, *v = NULL, *w;
7317
7318 /* Coerce the two arguments */
7319 u = (PyUnicodeObject *)PyUnicode_FromObject(left);
7320 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007321 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007322 v = (PyUnicodeObject *)PyUnicode_FromObject(right);
7323 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007324 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007325
7326 /* Shortcuts */
7327 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007328 Py_DECREF(v);
7329 return (PyObject *)u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007330 }
7331 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007332 Py_DECREF(u);
7333 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007334 }
7335
7336 /* Concat the two Unicode strings */
7337 w = _PyUnicode_New(u->length + v->length);
7338 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007339 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007340 Py_UNICODE_COPY(w->str, u->str, u->length);
7341 Py_UNICODE_COPY(w->str + u->length, v->str, v->length);
7342
7343 Py_DECREF(u);
7344 Py_DECREF(v);
7345 return (PyObject *)w;
7346
Benjamin Peterson29060642009-01-31 22:14:21 +00007347 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007348 Py_XDECREF(u);
7349 Py_XDECREF(v);
7350 return NULL;
7351}
7352
Walter Dörwald1ab83302007-05-18 17:15:44 +00007353void
7354PyUnicode_Append(PyObject **pleft, PyObject *right)
7355{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007356 PyObject *new;
7357 if (*pleft == NULL)
7358 return;
7359 if (right == NULL || !PyUnicode_Check(*pleft)) {
7360 Py_DECREF(*pleft);
7361 *pleft = NULL;
7362 return;
7363 }
7364 new = PyUnicode_Concat(*pleft, right);
7365 Py_DECREF(*pleft);
7366 *pleft = new;
Walter Dörwald1ab83302007-05-18 17:15:44 +00007367}
7368
7369void
7370PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
7371{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007372 PyUnicode_Append(pleft, right);
7373 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +00007374}
7375
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007376PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007377 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007378\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00007379Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007380string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007381interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007382
7383static PyObject *
7384unicode_count(PyUnicodeObject *self, PyObject *args)
7385{
7386 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007387 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007388 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007389 PyObject *result;
7390
Guido van Rossumb8872e62000-05-09 14:14:27 +00007391 if (!PyArg_ParseTuple(args, "O|O&O&:count", &substring,
Benjamin Peterson29060642009-01-31 22:14:21 +00007392 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007393 return NULL;
7394
7395 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Thomas Wouters477c8d52006-05-27 19:21:47 +00007396 (PyObject *)substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007397 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007398 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007399
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007400 ADJUST_INDICES(start, end, self->length);
Christian Heimes217cfd12007-12-02 14:31:20 +00007401 result = PyLong_FromSsize_t(
Thomas Wouters477c8d52006-05-27 19:21:47 +00007402 stringlib_count(self->str + start, end - start,
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007403 substring->str, substring->length,
7404 PY_SSIZE_T_MAX)
Thomas Wouters477c8d52006-05-27 19:21:47 +00007405 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007406
7407 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007408
Guido van Rossumd57fd912000-03-10 22:53:23 +00007409 return result;
7410}
7411
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007412PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +00007413 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007414\n\
Victor Stinnere14e2122010-11-07 18:41:46 +00007415Encode S using the codec registered for encoding. Default encoding\n\
7416is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +00007417handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007418a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
7419'xmlcharrefreplace' as well as any other name registered with\n\
7420codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007421
7422static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +00007423unicode_encode(PyUnicodeObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007424{
Benjamin Peterson308d6372009-09-18 21:42:35 +00007425 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +00007426 char *encoding = NULL;
7427 char *errors = NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007428 PyObject *v;
Guido van Rossum35d94282007-08-27 18:20:11 +00007429
Benjamin Peterson308d6372009-09-18 21:42:35 +00007430 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
7431 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007432 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00007433 v = PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00007434 if (v == NULL)
7435 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00007436 if (!PyBytes_Check(v)) {
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007437 PyErr_Format(PyExc_TypeError,
Guido van Rossumf15a29f2007-05-04 00:41:39 +00007438 "encoder did not return a bytes object "
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007439 "(type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00007440 Py_TYPE(v)->tp_name);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007441 Py_DECREF(v);
7442 return NULL;
7443 }
7444 return v;
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00007445
Benjamin Peterson29060642009-01-31 22:14:21 +00007446 onError:
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00007447 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007448}
7449
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007450PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007451 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007452\n\
7453Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007454If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007455
7456static PyObject*
7457unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
7458{
7459 Py_UNICODE *e;
7460 Py_UNICODE *p;
7461 Py_UNICODE *q;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007462 Py_UNICODE *qe;
7463 Py_ssize_t i, j, incr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007464 PyUnicodeObject *u;
7465 int tabsize = 8;
7466
7467 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00007468 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007469
Thomas Wouters7e474022000-07-16 12:04:32 +00007470 /* First pass: determine size of output string */
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007471 i = 0; /* chars up to and including most recent \n or \r */
7472 j = 0; /* chars since most recent \n or \r (use in tab calculations) */
7473 e = self->str + self->length; /* end of input */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007474 for (p = self->str; p < e; p++)
7475 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007476 if (tabsize > 0) {
7477 incr = tabsize - (j % tabsize); /* cannot overflow */
7478 if (j > PY_SSIZE_T_MAX - incr)
7479 goto overflow1;
7480 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007481 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007482 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007483 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007484 if (j > PY_SSIZE_T_MAX - 1)
7485 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007486 j++;
7487 if (*p == '\n' || *p == '\r') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007488 if (i > PY_SSIZE_T_MAX - j)
7489 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007490 i += j;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007491 j = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007492 }
7493 }
7494
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007495 if (i > PY_SSIZE_T_MAX - j)
Benjamin Peterson29060642009-01-31 22:14:21 +00007496 goto overflow1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007497
Guido van Rossumd57fd912000-03-10 22:53:23 +00007498 /* Second pass: create output string and fill it */
7499 u = _PyUnicode_New(i + j);
7500 if (!u)
7501 return NULL;
7502
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007503 j = 0; /* same as in first pass */
7504 q = u->str; /* next output char */
7505 qe = u->str + u->length; /* end of output */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007506
7507 for (p = self->str; p < e; p++)
7508 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007509 if (tabsize > 0) {
7510 i = tabsize - (j % tabsize);
7511 j += i;
7512 while (i--) {
7513 if (q >= qe)
7514 goto overflow2;
7515 *q++ = ' ';
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007516 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007517 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007518 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007519 else {
7520 if (q >= qe)
7521 goto overflow2;
7522 *q++ = *p;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007523 j++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007524 if (*p == '\n' || *p == '\r')
7525 j = 0;
7526 }
7527
7528 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007529
7530 overflow2:
7531 Py_DECREF(u);
7532 overflow1:
7533 PyErr_SetString(PyExc_OverflowError, "new string is too long");
7534 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007535}
7536
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007537PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007538 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007539\n\
7540Return the lowest index in S where substring sub is found,\n\
Guido van Rossum806c2462007-08-06 23:33:07 +00007541such that sub is contained within s[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007542arguments start and end are interpreted as in slice notation.\n\
7543\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007544Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007545
7546static PyObject *
7547unicode_find(PyUnicodeObject *self, PyObject *args)
7548{
Thomas Wouters477c8d52006-05-27 19:21:47 +00007549 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00007550 Py_ssize_t start;
7551 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007552 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007553
Christian Heimes9cd17752007-11-18 19:35:23 +00007554 if (!_ParseTupleFinds(args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007555 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007556
Thomas Wouters477c8d52006-05-27 19:21:47 +00007557 result = stringlib_find_slice(
7558 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
7559 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
7560 start, end
7561 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007562
7563 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007564
Christian Heimes217cfd12007-12-02 14:31:20 +00007565 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007566}
7567
7568static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00007569unicode_getitem(PyUnicodeObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007570{
7571 if (index < 0 || index >= self->length) {
7572 PyErr_SetString(PyExc_IndexError, "string index out of range");
7573 return NULL;
7574 }
7575
7576 return (PyObject*) PyUnicode_FromUnicode(&self->str[index], 1);
7577}
7578
Guido van Rossumc2504932007-09-18 19:42:40 +00007579/* Believe it or not, this produces the same value for ASCII strings
7580 as string_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00007581static Py_hash_t
Neil Schemenauerf8c37d12007-09-07 20:49:04 +00007582unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007583{
Guido van Rossumc2504932007-09-18 19:42:40 +00007584 Py_ssize_t len;
7585 Py_UNICODE *p;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00007586 Py_hash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +00007587
7588 if (self->hash != -1)
7589 return self->hash;
Christian Heimes90aa7642007-12-19 02:45:37 +00007590 len = Py_SIZE(self);
Guido van Rossumc2504932007-09-18 19:42:40 +00007591 p = self->str;
7592 x = *p << 7;
7593 while (--len >= 0)
7594 x = (1000003*x) ^ *p++;
Christian Heimes90aa7642007-12-19 02:45:37 +00007595 x ^= Py_SIZE(self);
Guido van Rossumc2504932007-09-18 19:42:40 +00007596 if (x == -1)
7597 x = -2;
7598 self->hash = x;
7599 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007600}
7601
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007602PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007603 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007604\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007605Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007606
7607static PyObject *
7608unicode_index(PyUnicodeObject *self, PyObject *args)
7609{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007610 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007611 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00007612 Py_ssize_t start;
7613 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007614
Christian Heimes9cd17752007-11-18 19:35:23 +00007615 if (!_ParseTupleFinds(args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007616 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007617
Thomas Wouters477c8d52006-05-27 19:21:47 +00007618 result = stringlib_find_slice(
7619 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
7620 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
7621 start, end
7622 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007623
7624 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007625
Guido van Rossumd57fd912000-03-10 22:53:23 +00007626 if (result < 0) {
7627 PyErr_SetString(PyExc_ValueError, "substring not found");
7628 return NULL;
7629 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00007630
Christian Heimes217cfd12007-12-02 14:31:20 +00007631 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007632}
7633
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007634PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007635 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007636\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007637Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007638at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007639
7640static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007641unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007642{
7643 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7644 register const Py_UNICODE *e;
7645 int cased;
7646
Guido van Rossumd57fd912000-03-10 22:53:23 +00007647 /* Shortcut for single character strings */
7648 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007649 return PyBool_FromLong(Py_UNICODE_ISLOWER(*p));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007650
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007651 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007652 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007653 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007654
Guido van Rossumd57fd912000-03-10 22:53:23 +00007655 e = p + PyUnicode_GET_SIZE(self);
7656 cased = 0;
7657 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007658 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007659
Benjamin Peterson29060642009-01-31 22:14:21 +00007660 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
7661 return PyBool_FromLong(0);
7662 else if (!cased && Py_UNICODE_ISLOWER(ch))
7663 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007664 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007665 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007666}
7667
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007668PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007669 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007670\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007671Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007672at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007673
7674static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007675unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007676{
7677 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7678 register const Py_UNICODE *e;
7679 int cased;
7680
Guido van Rossumd57fd912000-03-10 22:53:23 +00007681 /* Shortcut for single character strings */
7682 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007683 return PyBool_FromLong(Py_UNICODE_ISUPPER(*p) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007684
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007685 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007686 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007687 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007688
Guido van Rossumd57fd912000-03-10 22:53:23 +00007689 e = p + PyUnicode_GET_SIZE(self);
7690 cased = 0;
7691 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007692 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007693
Benjamin Peterson29060642009-01-31 22:14:21 +00007694 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
7695 return PyBool_FromLong(0);
7696 else if (!cased && Py_UNICODE_ISUPPER(ch))
7697 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007698 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007699 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007700}
7701
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007702PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007703 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007704\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007705Return True if S is a titlecased string and there is at least one\n\
7706character in S, i.e. upper- and titlecase characters may only\n\
7707follow uncased characters and lowercase characters only cased ones.\n\
7708Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007709
7710static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007711unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007712{
7713 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7714 register const Py_UNICODE *e;
7715 int cased, previous_is_cased;
7716
Guido van Rossumd57fd912000-03-10 22:53:23 +00007717 /* Shortcut for single character strings */
7718 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007719 return PyBool_FromLong((Py_UNICODE_ISTITLE(*p) != 0) ||
7720 (Py_UNICODE_ISUPPER(*p) != 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007721
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007722 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007723 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007724 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007725
Guido van Rossumd57fd912000-03-10 22:53:23 +00007726 e = p + PyUnicode_GET_SIZE(self);
7727 cased = 0;
7728 previous_is_cased = 0;
7729 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007730 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007731
Benjamin Peterson29060642009-01-31 22:14:21 +00007732 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
7733 if (previous_is_cased)
7734 return PyBool_FromLong(0);
7735 previous_is_cased = 1;
7736 cased = 1;
7737 }
7738 else if (Py_UNICODE_ISLOWER(ch)) {
7739 if (!previous_is_cased)
7740 return PyBool_FromLong(0);
7741 previous_is_cased = 1;
7742 cased = 1;
7743 }
7744 else
7745 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007746 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007747 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007748}
7749
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007750PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007751 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007752\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007753Return True if all characters in S are whitespace\n\
7754and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007755
7756static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007757unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007758{
7759 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7760 register const Py_UNICODE *e;
7761
Guido van Rossumd57fd912000-03-10 22:53:23 +00007762 /* Shortcut for single character strings */
7763 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007764 Py_UNICODE_ISSPACE(*p))
7765 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007766
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007767 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007768 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007769 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007770
Guido van Rossumd57fd912000-03-10 22:53:23 +00007771 e = p + PyUnicode_GET_SIZE(self);
7772 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007773 if (!Py_UNICODE_ISSPACE(*p))
7774 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007775 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007776 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007777}
7778
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007779PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007780 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007781\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007782Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007783and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007784
7785static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007786unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007787{
7788 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7789 register const Py_UNICODE *e;
7790
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007791 /* Shortcut for single character strings */
7792 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007793 Py_UNICODE_ISALPHA(*p))
7794 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007795
7796 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007797 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007798 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007799
7800 e = p + PyUnicode_GET_SIZE(self);
7801 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007802 if (!Py_UNICODE_ISALPHA(*p))
7803 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007804 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007805 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007806}
7807
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007808PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007809 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007810\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007811Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007812and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007813
7814static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007815unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007816{
7817 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7818 register const Py_UNICODE *e;
7819
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007820 /* Shortcut for single character strings */
7821 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007822 Py_UNICODE_ISALNUM(*p))
7823 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007824
7825 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007826 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007827 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007828
7829 e = p + PyUnicode_GET_SIZE(self);
7830 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007831 if (!Py_UNICODE_ISALNUM(*p))
7832 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007833 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007834 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007835}
7836
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007837PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007838 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007839\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007840Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007841False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007842
7843static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007844unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007845{
7846 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7847 register const Py_UNICODE *e;
7848
Guido van Rossumd57fd912000-03-10 22:53:23 +00007849 /* Shortcut for single character strings */
7850 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007851 Py_UNICODE_ISDECIMAL(*p))
7852 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007853
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007854 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007855 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007856 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007857
Guido van Rossumd57fd912000-03-10 22:53:23 +00007858 e = p + PyUnicode_GET_SIZE(self);
7859 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007860 if (!Py_UNICODE_ISDECIMAL(*p))
7861 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007862 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007863 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007864}
7865
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007866PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007867 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007868\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007869Return True if all characters in S are digits\n\
7870and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007871
7872static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007873unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007874{
7875 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7876 register const Py_UNICODE *e;
7877
Guido van Rossumd57fd912000-03-10 22:53:23 +00007878 /* Shortcut for single character strings */
7879 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007880 Py_UNICODE_ISDIGIT(*p))
7881 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007882
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007883 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007884 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007885 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007886
Guido van Rossumd57fd912000-03-10 22:53:23 +00007887 e = p + PyUnicode_GET_SIZE(self);
7888 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007889 if (!Py_UNICODE_ISDIGIT(*p))
7890 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007891 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007892 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007893}
7894
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007895PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007896 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007897\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007898Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007899False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007900
7901static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007902unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007903{
7904 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7905 register const Py_UNICODE *e;
7906
Guido van Rossumd57fd912000-03-10 22:53:23 +00007907 /* Shortcut for single character strings */
7908 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007909 Py_UNICODE_ISNUMERIC(*p))
7910 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007911
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007912 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007913 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007914 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007915
Guido van Rossumd57fd912000-03-10 22:53:23 +00007916 e = p + PyUnicode_GET_SIZE(self);
7917 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007918 if (!Py_UNICODE_ISNUMERIC(*p))
7919 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007920 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007921 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007922}
7923
Martin v. Löwis47383402007-08-15 07:32:56 +00007924int
7925PyUnicode_IsIdentifier(PyObject *self)
7926{
7927 register const Py_UNICODE *p = PyUnicode_AS_UNICODE((PyUnicodeObject*)self);
7928 register const Py_UNICODE *e;
7929
7930 /* Special case for empty strings */
7931 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007932 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +00007933
7934 /* PEP 3131 says that the first character must be in
7935 XID_Start and subsequent characters in XID_Continue,
7936 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +00007937 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +00007938 letters, digits, underscore). However, given the current
7939 definition of XID_Start and XID_Continue, it is sufficient
7940 to check just for these, except that _ must be allowed
7941 as starting an identifier. */
7942 if (!_PyUnicode_IsXidStart(*p) && *p != 0x5F /* LOW LINE */)
7943 return 0;
7944
7945 e = p + PyUnicode_GET_SIZE(self);
7946 for (p++; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007947 if (!_PyUnicode_IsXidContinue(*p))
7948 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +00007949 }
7950 return 1;
7951}
7952
7953PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007954 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +00007955\n\
7956Return True if S is a valid identifier according\n\
7957to the language definition.");
7958
7959static PyObject*
7960unicode_isidentifier(PyObject *self)
7961{
7962 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
7963}
7964
Georg Brandl559e5d72008-06-11 18:37:52 +00007965PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007966 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +00007967\n\
7968Return True if all characters in S are considered\n\
7969printable in repr() or S is empty, False otherwise.");
7970
7971static PyObject*
7972unicode_isprintable(PyObject *self)
7973{
7974 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7975 register const Py_UNICODE *e;
7976
7977 /* Shortcut for single character strings */
7978 if (PyUnicode_GET_SIZE(self) == 1 && Py_UNICODE_ISPRINTABLE(*p)) {
7979 Py_RETURN_TRUE;
7980 }
7981
7982 e = p + PyUnicode_GET_SIZE(self);
7983 for (; p < e; p++) {
7984 if (!Py_UNICODE_ISPRINTABLE(*p)) {
7985 Py_RETURN_FALSE;
7986 }
7987 }
7988 Py_RETURN_TRUE;
7989}
7990
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007991PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +00007992 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007993\n\
7994Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +00007995iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007996
7997static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007998unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007999{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008000 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008001}
8002
Martin v. Löwis18e16552006-02-15 17:27:45 +00008003static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +00008004unicode_length(PyUnicodeObject *self)
8005{
8006 return self->length;
8007}
8008
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008009PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008010 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008011\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008012Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008013done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008014
8015static PyObject *
8016unicode_ljust(PyUnicodeObject *self, PyObject *args)
8017{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008018 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008019 Py_UNICODE fillchar = ' ';
8020
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008021 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008022 return NULL;
8023
Tim Peters7a29bd52001-09-12 03:03:31 +00008024 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008025 Py_INCREF(self);
8026 return (PyObject*) self;
8027 }
8028
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008029 return (PyObject*) pad(self, 0, width - self->length, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008030}
8031
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008032PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008033 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008034\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008035Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008036
8037static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008038unicode_lower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008039{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008040 return fixup(self, fixlower);
8041}
8042
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008043#define LEFTSTRIP 0
8044#define RIGHTSTRIP 1
8045#define BOTHSTRIP 2
8046
8047/* Arrays indexed by above */
8048static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
8049
8050#define STRIPNAME(i) (stripformat[i]+3)
8051
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008052/* externally visible for str.strip(unicode) */
8053PyObject *
8054_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
8055{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008056 Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
8057 Py_ssize_t len = PyUnicode_GET_SIZE(self);
8058 Py_UNICODE *sep = PyUnicode_AS_UNICODE(sepobj);
8059 Py_ssize_t seplen = PyUnicode_GET_SIZE(sepobj);
8060 Py_ssize_t i, j;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008061
Benjamin Peterson29060642009-01-31 22:14:21 +00008062 BLOOM_MASK sepmask = make_bloom_mask(sep, seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008063
Benjamin Peterson14339b62009-01-31 16:36:08 +00008064 i = 0;
8065 if (striptype != RIGHTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008066 while (i < len && BLOOM_MEMBER(sepmask, s[i], sep, seplen)) {
8067 i++;
8068 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008069 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008070
Benjamin Peterson14339b62009-01-31 16:36:08 +00008071 j = len;
8072 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008073 do {
8074 j--;
8075 } while (j >= i && BLOOM_MEMBER(sepmask, s[j], sep, seplen));
8076 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008077 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008078
Benjamin Peterson14339b62009-01-31 16:36:08 +00008079 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008080 Py_INCREF(self);
8081 return (PyObject*)self;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008082 }
8083 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008084 return PyUnicode_FromUnicode(s+i, j-i);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008085}
8086
Guido van Rossumd57fd912000-03-10 22:53:23 +00008087
8088static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008089do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008090{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008091 Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
8092 Py_ssize_t len = PyUnicode_GET_SIZE(self), i, j;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008093
Benjamin Peterson14339b62009-01-31 16:36:08 +00008094 i = 0;
8095 if (striptype != RIGHTSTRIP) {
8096 while (i < len && Py_UNICODE_ISSPACE(s[i])) {
8097 i++;
8098 }
8099 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008100
Benjamin Peterson14339b62009-01-31 16:36:08 +00008101 j = len;
8102 if (striptype != LEFTSTRIP) {
8103 do {
8104 j--;
8105 } while (j >= i && Py_UNICODE_ISSPACE(s[j]));
8106 j++;
8107 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008108
Benjamin Peterson14339b62009-01-31 16:36:08 +00008109 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
8110 Py_INCREF(self);
8111 return (PyObject*)self;
8112 }
8113 else
8114 return PyUnicode_FromUnicode(s+i, j-i);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008115}
8116
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008117
8118static PyObject *
8119do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
8120{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008121 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008122
Benjamin Peterson14339b62009-01-31 16:36:08 +00008123 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
8124 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008125
Benjamin Peterson14339b62009-01-31 16:36:08 +00008126 if (sep != NULL && sep != Py_None) {
8127 if (PyUnicode_Check(sep))
8128 return _PyUnicode_XStrip(self, striptype, sep);
8129 else {
8130 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00008131 "%s arg must be None or str",
8132 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +00008133 return NULL;
8134 }
8135 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008136
Benjamin Peterson14339b62009-01-31 16:36:08 +00008137 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008138}
8139
8140
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008141PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008142 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008143\n\
8144Return a copy of the string S with leading and trailing\n\
8145whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008146If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008147
8148static PyObject *
8149unicode_strip(PyUnicodeObject *self, PyObject *args)
8150{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008151 if (PyTuple_GET_SIZE(args) == 0)
8152 return do_strip(self, BOTHSTRIP); /* Common case */
8153 else
8154 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008155}
8156
8157
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008158PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008159 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008160\n\
8161Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008162If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008163
8164static PyObject *
8165unicode_lstrip(PyUnicodeObject *self, PyObject *args)
8166{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008167 if (PyTuple_GET_SIZE(args) == 0)
8168 return do_strip(self, LEFTSTRIP); /* Common case */
8169 else
8170 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008171}
8172
8173
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008174PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008175 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008176\n\
8177Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008178If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008179
8180static PyObject *
8181unicode_rstrip(PyUnicodeObject *self, PyObject *args)
8182{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008183 if (PyTuple_GET_SIZE(args) == 0)
8184 return do_strip(self, RIGHTSTRIP); /* Common case */
8185 else
8186 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008187}
8188
8189
Guido van Rossumd57fd912000-03-10 22:53:23 +00008190static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +00008191unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008192{
8193 PyUnicodeObject *u;
8194 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008195 Py_ssize_t nchars;
Tim Peters8f422462000-09-09 06:13:41 +00008196 size_t nbytes;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008197
Georg Brandl222de0f2009-04-12 12:01:50 +00008198 if (len < 1) {
8199 Py_INCREF(unicode_empty);
8200 return (PyObject *)unicode_empty;
8201 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008202
Tim Peters7a29bd52001-09-12 03:03:31 +00008203 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008204 /* no repeat, return original string */
8205 Py_INCREF(str);
8206 return (PyObject*) str;
8207 }
Tim Peters8f422462000-09-09 06:13:41 +00008208
8209 /* ensure # of chars needed doesn't overflow int and # of bytes
8210 * needed doesn't overflow size_t
8211 */
8212 nchars = len * str->length;
Georg Brandl222de0f2009-04-12 12:01:50 +00008213 if (nchars / len != str->length) {
Tim Peters8f422462000-09-09 06:13:41 +00008214 PyErr_SetString(PyExc_OverflowError,
8215 "repeated string is too long");
8216 return NULL;
8217 }
8218 nbytes = (nchars + 1) * sizeof(Py_UNICODE);
8219 if (nbytes / sizeof(Py_UNICODE) != (size_t)(nchars + 1)) {
8220 PyErr_SetString(PyExc_OverflowError,
8221 "repeated string is too long");
8222 return NULL;
8223 }
8224 u = _PyUnicode_New(nchars);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008225 if (!u)
8226 return NULL;
8227
8228 p = u->str;
8229
Georg Brandl222de0f2009-04-12 12:01:50 +00008230 if (str->length == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00008231 Py_UNICODE_FILL(p, str->str[0], len);
8232 } else {
Georg Brandl222de0f2009-04-12 12:01:50 +00008233 Py_ssize_t done = str->length; /* number of characters copied this far */
8234 Py_UNICODE_COPY(p, str->str, str->length);
Benjamin Peterson29060642009-01-31 22:14:21 +00008235 while (done < nchars) {
Christian Heimescc47b052008-03-25 14:56:36 +00008236 Py_ssize_t n = (done <= nchars-done) ? done : nchars-done;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008237 Py_UNICODE_COPY(p+done, p, n);
8238 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00008239 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008240 }
8241
8242 return (PyObject*) u;
8243}
8244
8245PyObject *PyUnicode_Replace(PyObject *obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00008246 PyObject *subobj,
8247 PyObject *replobj,
8248 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008249{
8250 PyObject *self;
8251 PyObject *str1;
8252 PyObject *str2;
8253 PyObject *result;
8254
8255 self = PyUnicode_FromObject(obj);
8256 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008257 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008258 str1 = PyUnicode_FromObject(subobj);
8259 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008260 Py_DECREF(self);
8261 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008262 }
8263 str2 = PyUnicode_FromObject(replobj);
8264 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008265 Py_DECREF(self);
8266 Py_DECREF(str1);
8267 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008268 }
Tim Petersced69f82003-09-16 20:30:58 +00008269 result = replace((PyUnicodeObject *)self,
Benjamin Peterson29060642009-01-31 22:14:21 +00008270 (PyUnicodeObject *)str1,
8271 (PyUnicodeObject *)str2,
8272 maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008273 Py_DECREF(self);
8274 Py_DECREF(str1);
8275 Py_DECREF(str2);
8276 return result;
8277}
8278
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008279PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +00008280 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008281\n\
8282Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +00008283old replaced by new. If the optional argument count is\n\
8284given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008285
8286static PyObject*
8287unicode_replace(PyUnicodeObject *self, PyObject *args)
8288{
8289 PyUnicodeObject *str1;
8290 PyUnicodeObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008291 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008292 PyObject *result;
8293
Martin v. Löwis18e16552006-02-15 17:27:45 +00008294 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008295 return NULL;
8296 str1 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str1);
8297 if (str1 == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008298 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008299 str2 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str2);
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +00008300 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008301 Py_DECREF(str1);
8302 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +00008303 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008304
8305 result = replace(self, str1, str2, maxcount);
8306
8307 Py_DECREF(str1);
8308 Py_DECREF(str2);
8309 return result;
8310}
8311
8312static
8313PyObject *unicode_repr(PyObject *unicode)
8314{
Walter Dörwald79e913e2007-05-12 11:08:06 +00008315 PyObject *repr;
Walter Dörwald1ab83302007-05-18 17:15:44 +00008316 Py_UNICODE *p;
Walter Dörwald79e913e2007-05-12 11:08:06 +00008317 Py_UNICODE *s = PyUnicode_AS_UNICODE(unicode);
8318 Py_ssize_t size = PyUnicode_GET_SIZE(unicode);
8319
8320 /* XXX(nnorwitz): rather than over-allocating, it would be
8321 better to choose a different scheme. Perhaps scan the
8322 first N-chars of the string and allocate based on that size.
8323 */
8324 /* Initial allocation is based on the longest-possible unichr
8325 escape.
8326
8327 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
8328 unichr, so in this case it's the longest unichr escape. In
8329 narrow (UTF-16) builds this is five chars per source unichr
8330 since there are two unichrs in the surrogate pair, so in narrow
8331 (UTF-16) builds it's not the longest unichr escape.
8332
8333 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
8334 so in the narrow (UTF-16) build case it's the longest unichr
8335 escape.
8336 */
8337
Walter Dörwald1ab83302007-05-18 17:15:44 +00008338 repr = PyUnicode_FromUnicode(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00008339 2 /* quotes */
Walter Dörwald79e913e2007-05-12 11:08:06 +00008340#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00008341 + 10*size
Walter Dörwald79e913e2007-05-12 11:08:06 +00008342#else
Benjamin Peterson29060642009-01-31 22:14:21 +00008343 + 6*size
Walter Dörwald79e913e2007-05-12 11:08:06 +00008344#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00008345 + 1);
Walter Dörwald79e913e2007-05-12 11:08:06 +00008346 if (repr == NULL)
8347 return NULL;
8348
Walter Dörwald1ab83302007-05-18 17:15:44 +00008349 p = PyUnicode_AS_UNICODE(repr);
Walter Dörwald79e913e2007-05-12 11:08:06 +00008350
8351 /* Add quote */
8352 *p++ = (findchar(s, size, '\'') &&
8353 !findchar(s, size, '"')) ? '"' : '\'';
8354 while (size-- > 0) {
8355 Py_UNICODE ch = *s++;
8356
8357 /* Escape quotes and backslashes */
Walter Dörwald1ab83302007-05-18 17:15:44 +00008358 if ((ch == PyUnicode_AS_UNICODE(repr)[0]) || (ch == '\\')) {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008359 *p++ = '\\';
Walter Dörwald1ab83302007-05-18 17:15:44 +00008360 *p++ = ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00008361 continue;
8362 }
8363
Benjamin Peterson29060642009-01-31 22:14:21 +00008364 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +00008365 if (ch == '\t') {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008366 *p++ = '\\';
8367 *p++ = 't';
8368 }
8369 else if (ch == '\n') {
8370 *p++ = '\\';
8371 *p++ = 'n';
8372 }
8373 else if (ch == '\r') {
8374 *p++ = '\\';
8375 *p++ = 'r';
8376 }
8377
8378 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +00008379 else if (ch < ' ' || ch == 0x7F) {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008380 *p++ = '\\';
8381 *p++ = 'x';
8382 *p++ = hexdigits[(ch >> 4) & 0x000F];
8383 *p++ = hexdigits[ch & 0x000F];
8384 }
8385
Georg Brandl559e5d72008-06-11 18:37:52 +00008386 /* Copy ASCII characters as-is */
8387 else if (ch < 0x7F) {
8388 *p++ = ch;
8389 }
8390
Benjamin Peterson29060642009-01-31 22:14:21 +00008391 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +00008392 else {
8393 Py_UCS4 ucs = ch;
8394
8395#ifndef Py_UNICODE_WIDE
8396 Py_UNICODE ch2 = 0;
8397 /* Get code point from surrogate pair */
8398 if (size > 0) {
8399 ch2 = *s;
8400 if (ch >= 0xD800 && ch < 0xDC00 && ch2 >= 0xDC00
Benjamin Peterson29060642009-01-31 22:14:21 +00008401 && ch2 <= 0xDFFF) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008402 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF))
Benjamin Peterson29060642009-01-31 22:14:21 +00008403 + 0x00010000;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008404 s++;
Georg Brandl559e5d72008-06-11 18:37:52 +00008405 size--;
8406 }
8407 }
8408#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00008409 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +00008410 (categories Z* and C* except ASCII space)
8411 */
8412 if (!Py_UNICODE_ISPRINTABLE(ucs)) {
8413 /* Map 8-bit characters to '\xhh' */
8414 if (ucs <= 0xff) {
8415 *p++ = '\\';
8416 *p++ = 'x';
8417 *p++ = hexdigits[(ch >> 4) & 0x000F];
8418 *p++ = hexdigits[ch & 0x000F];
8419 }
8420 /* Map 21-bit characters to '\U00xxxxxx' */
8421 else if (ucs >= 0x10000) {
8422 *p++ = '\\';
8423 *p++ = 'U';
8424 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
8425 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
8426 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
8427 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
8428 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
8429 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
8430 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
8431 *p++ = hexdigits[ucs & 0x0000000F];
8432 }
8433 /* Map 16-bit characters to '\uxxxx' */
8434 else {
8435 *p++ = '\\';
8436 *p++ = 'u';
8437 *p++ = hexdigits[(ucs >> 12) & 0x000F];
8438 *p++ = hexdigits[(ucs >> 8) & 0x000F];
8439 *p++ = hexdigits[(ucs >> 4) & 0x000F];
8440 *p++ = hexdigits[ucs & 0x000F];
8441 }
8442 }
8443 /* Copy characters as-is */
8444 else {
8445 *p++ = ch;
8446#ifndef Py_UNICODE_WIDE
8447 if (ucs >= 0x10000)
8448 *p++ = ch2;
8449#endif
8450 }
8451 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00008452 }
8453 /* Add quote */
Walter Dörwald1ab83302007-05-18 17:15:44 +00008454 *p++ = PyUnicode_AS_UNICODE(repr)[0];
Walter Dörwald79e913e2007-05-12 11:08:06 +00008455
8456 *p = '\0';
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00008457 PyUnicode_Resize(&repr, p - PyUnicode_AS_UNICODE(repr));
Walter Dörwald79e913e2007-05-12 11:08:06 +00008458 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008459}
8460
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008461PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008462 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008463\n\
8464Return the highest index in S where substring sub is found,\n\
Guido van Rossum806c2462007-08-06 23:33:07 +00008465such that sub is contained within s[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008466arguments start and end are interpreted as in slice notation.\n\
8467\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008468Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008469
8470static PyObject *
8471unicode_rfind(PyUnicodeObject *self, PyObject *args)
8472{
Thomas Wouters477c8d52006-05-27 19:21:47 +00008473 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00008474 Py_ssize_t start;
8475 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008476 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008477
Christian Heimes9cd17752007-11-18 19:35:23 +00008478 if (!_ParseTupleFinds(args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008479 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008480
Thomas Wouters477c8d52006-05-27 19:21:47 +00008481 result = stringlib_rfind_slice(
8482 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
8483 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
8484 start, end
8485 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008486
8487 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008488
Christian Heimes217cfd12007-12-02 14:31:20 +00008489 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008490}
8491
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008492PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008493 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008494\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008495Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008496
8497static PyObject *
8498unicode_rindex(PyUnicodeObject *self, PyObject *args)
8499{
Thomas Wouters477c8d52006-05-27 19:21:47 +00008500 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00008501 Py_ssize_t start;
8502 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008503 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008504
Christian Heimes9cd17752007-11-18 19:35:23 +00008505 if (!_ParseTupleFinds(args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008506 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008507
Thomas Wouters477c8d52006-05-27 19:21:47 +00008508 result = stringlib_rfind_slice(
8509 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
8510 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
8511 start, end
8512 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008513
8514 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008515
Guido van Rossumd57fd912000-03-10 22:53:23 +00008516 if (result < 0) {
8517 PyErr_SetString(PyExc_ValueError, "substring not found");
8518 return NULL;
8519 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008520 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008521}
8522
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008523PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008524 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008525\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008526Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008527done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008528
8529static PyObject *
8530unicode_rjust(PyUnicodeObject *self, PyObject *args)
8531{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008532 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008533 Py_UNICODE fillchar = ' ';
8534
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008535 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008536 return NULL;
8537
Tim Peters7a29bd52001-09-12 03:03:31 +00008538 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008539 Py_INCREF(self);
8540 return (PyObject*) self;
8541 }
8542
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008543 return (PyObject*) pad(self, width - self->length, 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008544}
8545
Guido van Rossumd57fd912000-03-10 22:53:23 +00008546PyObject *PyUnicode_Split(PyObject *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00008547 PyObject *sep,
8548 Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008549{
8550 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008551
Guido van Rossumd57fd912000-03-10 22:53:23 +00008552 s = PyUnicode_FromObject(s);
8553 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008554 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00008555 if (sep != NULL) {
8556 sep = PyUnicode_FromObject(sep);
8557 if (sep == NULL) {
8558 Py_DECREF(s);
8559 return NULL;
8560 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008561 }
8562
8563 result = split((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
8564
8565 Py_DECREF(s);
8566 Py_XDECREF(sep);
8567 return result;
8568}
8569
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008570PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008571 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008572\n\
8573Return a list of the words in S, using sep as the\n\
8574delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00008575splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00008576whitespace string is a separator and empty strings are\n\
8577removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008578
8579static PyObject*
8580unicode_split(PyUnicodeObject *self, PyObject *args)
8581{
8582 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008583 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008584
Martin v. Löwis18e16552006-02-15 17:27:45 +00008585 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008586 return NULL;
8587
8588 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008589 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008590 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00008591 return split(self, (PyUnicodeObject *)substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008592 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008593 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008594}
8595
Thomas Wouters477c8d52006-05-27 19:21:47 +00008596PyObject *
8597PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
8598{
8599 PyObject* str_obj;
8600 PyObject* sep_obj;
8601 PyObject* out;
8602
8603 str_obj = PyUnicode_FromObject(str_in);
8604 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008605 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008606 sep_obj = PyUnicode_FromObject(sep_in);
8607 if (!sep_obj) {
8608 Py_DECREF(str_obj);
8609 return NULL;
8610 }
8611
8612 out = stringlib_partition(
8613 str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
8614 sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
8615 );
8616
8617 Py_DECREF(sep_obj);
8618 Py_DECREF(str_obj);
8619
8620 return out;
8621}
8622
8623
8624PyObject *
8625PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
8626{
8627 PyObject* str_obj;
8628 PyObject* sep_obj;
8629 PyObject* out;
8630
8631 str_obj = PyUnicode_FromObject(str_in);
8632 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008633 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008634 sep_obj = PyUnicode_FromObject(sep_in);
8635 if (!sep_obj) {
8636 Py_DECREF(str_obj);
8637 return NULL;
8638 }
8639
8640 out = stringlib_rpartition(
8641 str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
8642 sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
8643 );
8644
8645 Py_DECREF(sep_obj);
8646 Py_DECREF(str_obj);
8647
8648 return out;
8649}
8650
8651PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008652 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008653\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00008654Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008655the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008656found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00008657
8658static PyObject*
8659unicode_partition(PyUnicodeObject *self, PyObject *separator)
8660{
8661 return PyUnicode_Partition((PyObject *)self, separator);
8662}
8663
8664PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +00008665 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008666\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00008667Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008668the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008669separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00008670
8671static PyObject*
8672unicode_rpartition(PyUnicodeObject *self, PyObject *separator)
8673{
8674 return PyUnicode_RPartition((PyObject *)self, separator);
8675}
8676
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008677PyObject *PyUnicode_RSplit(PyObject *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00008678 PyObject *sep,
8679 Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008680{
8681 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008682
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008683 s = PyUnicode_FromObject(s);
8684 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008685 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00008686 if (sep != NULL) {
8687 sep = PyUnicode_FromObject(sep);
8688 if (sep == NULL) {
8689 Py_DECREF(s);
8690 return NULL;
8691 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008692 }
8693
8694 result = rsplit((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
8695
8696 Py_DECREF(s);
8697 Py_XDECREF(sep);
8698 return result;
8699}
8700
8701PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008702 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008703\n\
8704Return a list of the words in S, using sep as the\n\
8705delimiter string, starting at the end of the string and\n\
8706working to the front. If maxsplit is given, at most maxsplit\n\
8707splits are done. If sep is not specified, any whitespace string\n\
8708is a separator.");
8709
8710static PyObject*
8711unicode_rsplit(PyUnicodeObject *self, PyObject *args)
8712{
8713 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008714 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008715
Martin v. Löwis18e16552006-02-15 17:27:45 +00008716 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008717 return NULL;
8718
8719 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008720 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008721 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00008722 return rsplit(self, (PyUnicodeObject *)substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008723 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008724 return PyUnicode_RSplit((PyObject *)self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008725}
8726
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008727PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008728 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008729\n\
8730Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +00008731Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008732is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008733
8734static PyObject*
8735unicode_splitlines(PyUnicodeObject *self, PyObject *args)
8736{
Guido van Rossum86662912000-04-11 15:38:46 +00008737 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008738
Guido van Rossum86662912000-04-11 15:38:46 +00008739 if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008740 return NULL;
8741
Guido van Rossum86662912000-04-11 15:38:46 +00008742 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008743}
8744
8745static
Guido van Rossumf15a29f2007-05-04 00:41:39 +00008746PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008747{
Walter Dörwald346737f2007-05-31 10:44:43 +00008748 if (PyUnicode_CheckExact(self)) {
8749 Py_INCREF(self);
8750 return self;
8751 } else
8752 /* Subtype -- return genuine unicode string with the same value. */
8753 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(self),
8754 PyUnicode_GET_SIZE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +00008755}
8756
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008757PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008758 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008759\n\
8760Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008761and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008762
8763static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008764unicode_swapcase(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008765{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008766 return fixup(self, fixswapcase);
8767}
8768
Georg Brandlceee0772007-11-27 23:48:05 +00008769PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008770 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +00008771\n\
8772Return a translation table usable for str.translate().\n\
8773If there is only one argument, it must be a dictionary mapping Unicode\n\
8774ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008775Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +00008776If there are two arguments, they must be strings of equal length, and\n\
8777in the resulting dictionary, each character in x will be mapped to the\n\
8778character at the same position in y. If there is a third argument, it\n\
8779must be a string, whose characters will be mapped to None in the result.");
8780
8781static PyObject*
8782unicode_maketrans(PyUnicodeObject *null, PyObject *args)
8783{
8784 PyObject *x, *y = NULL, *z = NULL;
8785 PyObject *new = NULL, *key, *value;
8786 Py_ssize_t i = 0;
8787 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008788
Georg Brandlceee0772007-11-27 23:48:05 +00008789 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
8790 return NULL;
8791 new = PyDict_New();
8792 if (!new)
8793 return NULL;
8794 if (y != NULL) {
8795 /* x must be a string too, of equal length */
8796 Py_ssize_t ylen = PyUnicode_GET_SIZE(y);
8797 if (!PyUnicode_Check(x)) {
8798 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
8799 "be a string if there is a second argument");
8800 goto err;
8801 }
8802 if (PyUnicode_GET_SIZE(x) != ylen) {
8803 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
8804 "arguments must have equal length");
8805 goto err;
8806 }
8807 /* create entries for translating chars in x to those in y */
8808 for (i = 0; i < PyUnicode_GET_SIZE(x); i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +00008809 key = PyLong_FromLong(PyUnicode_AS_UNICODE(x)[i]);
8810 value = PyLong_FromLong(PyUnicode_AS_UNICODE(y)[i]);
Georg Brandlceee0772007-11-27 23:48:05 +00008811 if (!key || !value)
8812 goto err;
8813 res = PyDict_SetItem(new, key, value);
8814 Py_DECREF(key);
8815 Py_DECREF(value);
8816 if (res < 0)
8817 goto err;
8818 }
8819 /* create entries for deleting chars in z */
8820 if (z != NULL) {
8821 for (i = 0; i < PyUnicode_GET_SIZE(z); i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +00008822 key = PyLong_FromLong(PyUnicode_AS_UNICODE(z)[i]);
Georg Brandlceee0772007-11-27 23:48:05 +00008823 if (!key)
8824 goto err;
8825 res = PyDict_SetItem(new, key, Py_None);
8826 Py_DECREF(key);
8827 if (res < 0)
8828 goto err;
8829 }
8830 }
8831 } else {
8832 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +00008833 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +00008834 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
8835 "to maketrans it must be a dict");
8836 goto err;
8837 }
8838 /* copy entries into the new dict, converting string keys to int keys */
8839 while (PyDict_Next(x, &i, &key, &value)) {
8840 if (PyUnicode_Check(key)) {
8841 /* convert string keys to integer keys */
8842 PyObject *newkey;
8843 if (PyUnicode_GET_SIZE(key) != 1) {
8844 PyErr_SetString(PyExc_ValueError, "string keys in translate "
8845 "table must be of length 1");
8846 goto err;
8847 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008848 newkey = PyLong_FromLong(PyUnicode_AS_UNICODE(key)[0]);
Georg Brandlceee0772007-11-27 23:48:05 +00008849 if (!newkey)
8850 goto err;
8851 res = PyDict_SetItem(new, newkey, value);
8852 Py_DECREF(newkey);
8853 if (res < 0)
8854 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +00008855 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +00008856 /* just keep integer keys */
8857 if (PyDict_SetItem(new, key, value) < 0)
8858 goto err;
8859 } else {
8860 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
8861 "be strings or integers");
8862 goto err;
8863 }
8864 }
8865 }
8866 return new;
8867 err:
8868 Py_DECREF(new);
8869 return NULL;
8870}
8871
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008872PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008873 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008874\n\
8875Return a copy of the string S, where all characters have been mapped\n\
8876through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008877Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +00008878Unmapped characters are left untouched. Characters mapped to None\n\
8879are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008880
8881static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008882unicode_translate(PyUnicodeObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008883{
Georg Brandlceee0772007-11-27 23:48:05 +00008884 return PyUnicode_TranslateCharmap(self->str, self->length, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008885}
8886
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008887PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008888 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008889\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008890Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008891
8892static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008893unicode_upper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008894{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008895 return fixup(self, fixupper);
8896}
8897
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008898PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008899 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008900\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +00008901Pad a numeric string S with zeros on the left, to fill a field\n\
8902of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008903
8904static PyObject *
8905unicode_zfill(PyUnicodeObject *self, PyObject *args)
8906{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008907 Py_ssize_t fill;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008908 PyUnicodeObject *u;
8909
Martin v. Löwis18e16552006-02-15 17:27:45 +00008910 Py_ssize_t width;
8911 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008912 return NULL;
8913
8914 if (self->length >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +00008915 if (PyUnicode_CheckExact(self)) {
8916 Py_INCREF(self);
8917 return (PyObject*) self;
8918 }
8919 else
8920 return PyUnicode_FromUnicode(
8921 PyUnicode_AS_UNICODE(self),
8922 PyUnicode_GET_SIZE(self)
Benjamin Peterson29060642009-01-31 22:14:21 +00008923 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008924 }
8925
8926 fill = width - self->length;
8927
8928 u = pad(self, fill, 0, '0');
8929
Walter Dörwald068325e2002-04-15 13:36:47 +00008930 if (u == NULL)
8931 return NULL;
8932
Guido van Rossumd57fd912000-03-10 22:53:23 +00008933 if (u->str[fill] == '+' || u->str[fill] == '-') {
8934 /* move sign to beginning of string */
8935 u->str[0] = u->str[fill];
8936 u->str[fill] = '0';
8937 }
8938
8939 return (PyObject*) u;
8940}
Guido van Rossumd57fd912000-03-10 22:53:23 +00008941
8942#if 0
8943static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008944unicode_freelistsize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008945{
Christian Heimes2202f872008-02-06 14:31:34 +00008946 return PyLong_FromLong(numfree);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008947}
8948#endif
8949
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008950PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008951 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008952\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00008953Return True if S starts with the specified prefix, False otherwise.\n\
8954With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008955With optional end, stop comparing S at that position.\n\
8956prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008957
8958static PyObject *
8959unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00008960 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008961{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008962 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008963 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008964 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008965 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008966 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008967
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008968 if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
Benjamin Peterson29060642009-01-31 22:14:21 +00008969 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
8970 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008971 if (PyTuple_Check(subobj)) {
8972 Py_ssize_t i;
8973 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
8974 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +00008975 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008976 if (substring == NULL)
8977 return NULL;
8978 result = tailmatch(self, substring, start, end, -1);
8979 Py_DECREF(substring);
8980 if (result) {
8981 Py_RETURN_TRUE;
8982 }
8983 }
8984 /* nothing matched */
8985 Py_RETURN_FALSE;
8986 }
8987 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008988 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008989 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008990 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008991 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008992 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008993}
8994
8995
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008996PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008997 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008998\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00008999Return True if S ends with the specified suffix, False otherwise.\n\
9000With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009001With optional end, stop comparing S at that position.\n\
9002suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009003
9004static PyObject *
9005unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00009006 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009007{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009008 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009009 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009010 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009011 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009012 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009013
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009014 if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
Benjamin Peterson29060642009-01-31 22:14:21 +00009015 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
9016 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009017 if (PyTuple_Check(subobj)) {
9018 Py_ssize_t i;
9019 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
9020 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +00009021 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009022 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009023 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009024 result = tailmatch(self, substring, start, end, +1);
9025 Py_DECREF(substring);
9026 if (result) {
9027 Py_RETURN_TRUE;
9028 }
9029 }
9030 Py_RETURN_FALSE;
9031 }
9032 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009033 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009034 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009035
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009036 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009037 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009038 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009039}
9040
Eric Smith8c663262007-08-25 02:26:07 +00009041#include "stringlib/string_format.h"
9042
9043PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009044 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +00009045\n\
Eric Smith51d2fd92010-11-06 19:27:37 +00009046Return a formatted version of S, using substitutions from args and kwargs.\n\
9047The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +00009048
Eric Smith27bbca62010-11-04 17:06:58 +00009049PyDoc_STRVAR(format_map__doc__,
9050 "S.format_map(mapping) -> str\n\
9051\n\
Eric Smith51d2fd92010-11-06 19:27:37 +00009052Return a formatted version of S, using substitutions from mapping.\n\
9053The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +00009054
Eric Smith4a7d76d2008-05-30 18:10:19 +00009055static PyObject *
9056unicode__format__(PyObject* self, PyObject* args)
9057{
9058 PyObject *format_spec;
9059
9060 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
9061 return NULL;
9062
9063 return _PyUnicode_FormatAdvanced(self,
9064 PyUnicode_AS_UNICODE(format_spec),
9065 PyUnicode_GET_SIZE(format_spec));
9066}
9067
Eric Smith8c663262007-08-25 02:26:07 +00009068PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009069 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +00009070\n\
Eric Smith51d2fd92010-11-06 19:27:37 +00009071Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +00009072
9073static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009074unicode__sizeof__(PyUnicodeObject *v)
9075{
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00009076 return PyLong_FromSsize_t(sizeof(PyUnicodeObject) +
9077 sizeof(Py_UNICODE) * (v->length + 1));
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009078}
9079
9080PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009081 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009082
9083static PyObject *
Guido van Rossum5d9113d2003-01-29 17:58:45 +00009084unicode_getnewargs(PyUnicodeObject *v)
9085{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009086 return Py_BuildValue("(u#)", v->str, v->length);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00009087}
9088
9089
Guido van Rossumd57fd912000-03-10 22:53:23 +00009090static PyMethodDef unicode_methods[] = {
9091
9092 /* Order is according to common usage: often used methods should
9093 appear first, since lookup is done sequentially. */
9094
Benjamin Peterson308d6372009-09-18 21:42:35 +00009095 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009096 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
9097 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009098 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009099 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
9100 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
9101 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
9102 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
9103 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
9104 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
9105 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00009106 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009107 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
9108 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
9109 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00009110 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009111 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
9112 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
9113 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00009114 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00009115 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009116 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00009117 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009118 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
9119 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
9120 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
9121 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
9122 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
9123 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
9124 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
9125 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
9126 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
9127 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
9128 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
9129 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
9130 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
9131 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +00009132 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +00009133 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009134 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +00009135 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +00009136 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +00009137 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +00009138 {"maketrans", (PyCFunction) unicode_maketrans,
9139 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009140 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +00009141#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009142 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +00009143#endif
9144
9145#if 0
9146 /* This one is just used for debugging the implementation. */
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009147 {"freelistsize", (PyCFunction) unicode_freelistsize, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +00009148#endif
9149
Benjamin Peterson14339b62009-01-31 16:36:08 +00009150 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +00009151 {NULL, NULL}
9152};
9153
Neil Schemenauerce30bc92002-11-18 16:10:18 +00009154static PyObject *
9155unicode_mod(PyObject *v, PyObject *w)
9156{
Benjamin Peterson29060642009-01-31 22:14:21 +00009157 if (!PyUnicode_Check(v)) {
9158 Py_INCREF(Py_NotImplemented);
9159 return Py_NotImplemented;
9160 }
9161 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +00009162}
9163
9164static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009165 0, /*nb_add*/
9166 0, /*nb_subtract*/
9167 0, /*nb_multiply*/
9168 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +00009169};
9170
Guido van Rossumd57fd912000-03-10 22:53:23 +00009171static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009172 (lenfunc) unicode_length, /* sq_length */
9173 PyUnicode_Concat, /* sq_concat */
9174 (ssizeargfunc) unicode_repeat, /* sq_repeat */
9175 (ssizeargfunc) unicode_getitem, /* sq_item */
9176 0, /* sq_slice */
9177 0, /* sq_ass_item */
9178 0, /* sq_ass_slice */
9179 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009180};
9181
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009182static PyObject*
9183unicode_subscript(PyUnicodeObject* self, PyObject* item)
9184{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009185 if (PyIndex_Check(item)) {
9186 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009187 if (i == -1 && PyErr_Occurred())
9188 return NULL;
9189 if (i < 0)
Martin v. Löwisdea59e52006-01-05 10:00:36 +00009190 i += PyUnicode_GET_SIZE(self);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009191 return unicode_getitem(self, i);
9192 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00009193 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009194 Py_UNICODE* source_buf;
9195 Py_UNICODE* result_buf;
9196 PyObject* result;
9197
Martin v. Löwisdea59e52006-01-05 10:00:36 +00009198 if (PySlice_GetIndicesEx((PySliceObject*)item, PyUnicode_GET_SIZE(self),
Benjamin Peterson29060642009-01-31 22:14:21 +00009199 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009200 return NULL;
9201 }
9202
9203 if (slicelength <= 0) {
9204 return PyUnicode_FromUnicode(NULL, 0);
Thomas Woutersed03b412007-08-28 21:37:11 +00009205 } else if (start == 0 && step == 1 && slicelength == self->length &&
9206 PyUnicode_CheckExact(self)) {
9207 Py_INCREF(self);
9208 return (PyObject *)self;
9209 } else if (step == 1) {
9210 return PyUnicode_FromUnicode(self->str + start, slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009211 } else {
9212 source_buf = PyUnicode_AS_UNICODE((PyObject*)self);
Christian Heimesb186d002008-03-18 15:15:01 +00009213 result_buf = (Py_UNICODE *)PyObject_MALLOC(slicelength*
9214 sizeof(Py_UNICODE));
Benjamin Peterson14339b62009-01-31 16:36:08 +00009215
Benjamin Peterson29060642009-01-31 22:14:21 +00009216 if (result_buf == NULL)
9217 return PyErr_NoMemory();
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009218
9219 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
9220 result_buf[i] = source_buf[cur];
9221 }
Tim Petersced69f82003-09-16 20:30:58 +00009222
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009223 result = PyUnicode_FromUnicode(result_buf, slicelength);
Christian Heimesb186d002008-03-18 15:15:01 +00009224 PyObject_FREE(result_buf);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009225 return result;
9226 }
9227 } else {
9228 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
9229 return NULL;
9230 }
9231}
9232
9233static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009234 (lenfunc)unicode_length, /* mp_length */
9235 (binaryfunc)unicode_subscript, /* mp_subscript */
9236 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009237};
9238
Guido van Rossumd57fd912000-03-10 22:53:23 +00009239
Guido van Rossumd57fd912000-03-10 22:53:23 +00009240/* Helpers for PyUnicode_Format() */
9241
9242static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00009243getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009244{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009245 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009246 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009247 (*p_argidx)++;
9248 if (arglen < 0)
9249 return args;
9250 else
9251 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009252 }
9253 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009254 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009255 return NULL;
9256}
9257
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009258/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009259
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009260static PyObject *
9261formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009262{
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009263 char *p;
9264 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009265 double x;
Tim Petersced69f82003-09-16 20:30:58 +00009266
Guido van Rossumd57fd912000-03-10 22:53:23 +00009267 x = PyFloat_AsDouble(v);
9268 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009269 return NULL;
9270
Guido van Rossumd57fd912000-03-10 22:53:23 +00009271 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009272 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +00009273
Eric Smith0923d1d2009-04-16 20:16:10 +00009274 p = PyOS_double_to_string(x, type, prec,
9275 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009276 if (p == NULL)
9277 return NULL;
9278 result = PyUnicode_FromStringAndSize(p, strlen(p));
Eric Smith0923d1d2009-04-16 20:16:10 +00009279 PyMem_Free(p);
9280 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009281}
9282
Tim Peters38fd5b62000-09-21 05:43:11 +00009283static PyObject*
9284formatlong(PyObject *val, int flags, int prec, int type)
9285{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009286 char *buf;
9287 int len;
9288 PyObject *str; /* temporary string object. */
9289 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +00009290
Benjamin Peterson14339b62009-01-31 16:36:08 +00009291 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
9292 if (!str)
9293 return NULL;
9294 result = PyUnicode_FromStringAndSize(buf, len);
9295 Py_DECREF(str);
9296 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +00009297}
9298
Guido van Rossumd57fd912000-03-10 22:53:23 +00009299static int
9300formatchar(Py_UNICODE *buf,
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009301 size_t buflen,
9302 PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009303{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00009304 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009305 if (PyUnicode_Check(v)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009306 if (PyUnicode_GET_SIZE(v) == 1) {
9307 buf[0] = PyUnicode_AS_UNICODE(v)[0];
9308 buf[1] = '\0';
9309 return 1;
9310 }
9311#ifndef Py_UNICODE_WIDE
9312 if (PyUnicode_GET_SIZE(v) == 2) {
9313 /* Decode a valid surrogate pair */
9314 int c0 = PyUnicode_AS_UNICODE(v)[0];
9315 int c1 = PyUnicode_AS_UNICODE(v)[1];
9316 if (0xD800 <= c0 && c0 <= 0xDBFF &&
9317 0xDC00 <= c1 && c1 <= 0xDFFF) {
9318 buf[0] = c0;
9319 buf[1] = c1;
9320 buf[2] = '\0';
9321 return 2;
9322 }
9323 }
9324#endif
9325 goto onError;
9326 }
9327 else {
9328 /* Integer input truncated to a character */
9329 long x;
9330 x = PyLong_AsLong(v);
9331 if (x == -1 && PyErr_Occurred())
9332 goto onError;
9333
9334 if (x < 0 || x > 0x10ffff) {
9335 PyErr_SetString(PyExc_OverflowError,
9336 "%c arg not in range(0x110000)");
9337 return -1;
9338 }
9339
9340#ifndef Py_UNICODE_WIDE
9341 if (x > 0xffff) {
9342 x -= 0x10000;
9343 buf[0] = (Py_UNICODE)(0xD800 | (x >> 10));
9344 buf[1] = (Py_UNICODE)(0xDC00 | (x & 0x3FF));
9345 return 2;
9346 }
9347#endif
9348 buf[0] = (Py_UNICODE) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009349 buf[1] = '\0';
9350 return 1;
9351 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00009352
Benjamin Peterson29060642009-01-31 22:14:21 +00009353 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009354 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009355 "%c requires int or char");
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009356 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009357}
9358
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009359/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009360 FORMATBUFLEN is the length of the buffer in which chars are formatted.
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009361*/
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009362#define FORMATBUFLEN (size_t)10
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009363
Guido van Rossumd57fd912000-03-10 22:53:23 +00009364PyObject *PyUnicode_Format(PyObject *format,
Benjamin Peterson29060642009-01-31 22:14:21 +00009365 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009366{
9367 Py_UNICODE *fmt, *res;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009368 Py_ssize_t fmtcnt, rescnt, reslen, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009369 int args_owned = 0;
9370 PyUnicodeObject *result = NULL;
9371 PyObject *dict = NULL;
9372 PyObject *uformat;
Tim Petersced69f82003-09-16 20:30:58 +00009373
Guido van Rossumd57fd912000-03-10 22:53:23 +00009374 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009375 PyErr_BadInternalCall();
9376 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009377 }
9378 uformat = PyUnicode_FromObject(format);
Fred Drakee4315f52000-05-09 19:53:39 +00009379 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009380 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009381 fmt = PyUnicode_AS_UNICODE(uformat);
9382 fmtcnt = PyUnicode_GET_SIZE(uformat);
9383
9384 reslen = rescnt = fmtcnt + 100;
9385 result = _PyUnicode_New(reslen);
9386 if (result == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009387 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009388 res = PyUnicode_AS_UNICODE(result);
9389
9390 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009391 arglen = PyTuple_Size(args);
9392 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009393 }
9394 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009395 arglen = -1;
9396 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009397 }
Christian Heimes90aa7642007-12-19 02:45:37 +00009398 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +00009399 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +00009400 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009401
9402 while (--fmtcnt >= 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009403 if (*fmt != '%') {
9404 if (--rescnt < 0) {
9405 rescnt = fmtcnt + 100;
9406 reslen += rescnt;
9407 if (_PyUnicode_Resize(&result, reslen) < 0)
9408 goto onError;
9409 res = PyUnicode_AS_UNICODE(result) + reslen - rescnt;
9410 --rescnt;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009411 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009412 *res++ = *fmt++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009413 }
9414 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009415 /* Got a format specifier */
9416 int flags = 0;
9417 Py_ssize_t width = -1;
9418 int prec = -1;
9419 Py_UNICODE c = '\0';
9420 Py_UNICODE fill;
9421 int isnumok;
9422 PyObject *v = NULL;
9423 PyObject *temp = NULL;
9424 Py_UNICODE *pbuf;
9425 Py_UNICODE sign;
9426 Py_ssize_t len;
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009427 Py_UNICODE formatbuf[FORMATBUFLEN]; /* For formatchar() */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009428
Benjamin Peterson29060642009-01-31 22:14:21 +00009429 fmt++;
9430 if (*fmt == '(') {
9431 Py_UNICODE *keystart;
9432 Py_ssize_t keylen;
9433 PyObject *key;
9434 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +00009435
Benjamin Peterson29060642009-01-31 22:14:21 +00009436 if (dict == NULL) {
9437 PyErr_SetString(PyExc_TypeError,
9438 "format requires a mapping");
9439 goto onError;
9440 }
9441 ++fmt;
9442 --fmtcnt;
9443 keystart = fmt;
9444 /* Skip over balanced parentheses */
9445 while (pcount > 0 && --fmtcnt >= 0) {
9446 if (*fmt == ')')
9447 --pcount;
9448 else if (*fmt == '(')
9449 ++pcount;
9450 fmt++;
9451 }
9452 keylen = fmt - keystart - 1;
9453 if (fmtcnt < 0 || pcount > 0) {
9454 PyErr_SetString(PyExc_ValueError,
9455 "incomplete format key");
9456 goto onError;
9457 }
9458#if 0
9459 /* keys are converted to strings using UTF-8 and
9460 then looked up since Python uses strings to hold
9461 variables names etc. in its namespaces and we
9462 wouldn't want to break common idioms. */
9463 key = PyUnicode_EncodeUTF8(keystart,
9464 keylen,
9465 NULL);
9466#else
9467 key = PyUnicode_FromUnicode(keystart, keylen);
9468#endif
9469 if (key == NULL)
9470 goto onError;
9471 if (args_owned) {
9472 Py_DECREF(args);
9473 args_owned = 0;
9474 }
9475 args = PyObject_GetItem(dict, key);
9476 Py_DECREF(key);
9477 if (args == NULL) {
9478 goto onError;
9479 }
9480 args_owned = 1;
9481 arglen = -1;
9482 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009483 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009484 while (--fmtcnt >= 0) {
9485 switch (c = *fmt++) {
9486 case '-': flags |= F_LJUST; continue;
9487 case '+': flags |= F_SIGN; continue;
9488 case ' ': flags |= F_BLANK; continue;
9489 case '#': flags |= F_ALT; continue;
9490 case '0': flags |= F_ZERO; continue;
9491 }
9492 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009493 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009494 if (c == '*') {
9495 v = getnextarg(args, arglen, &argidx);
9496 if (v == NULL)
9497 goto onError;
9498 if (!PyLong_Check(v)) {
9499 PyErr_SetString(PyExc_TypeError,
9500 "* wants int");
9501 goto onError;
9502 }
9503 width = PyLong_AsLong(v);
9504 if (width == -1 && PyErr_Occurred())
9505 goto onError;
9506 if (width < 0) {
9507 flags |= F_LJUST;
9508 width = -width;
9509 }
9510 if (--fmtcnt >= 0)
9511 c = *fmt++;
9512 }
9513 else if (c >= '0' && c <= '9') {
9514 width = c - '0';
9515 while (--fmtcnt >= 0) {
9516 c = *fmt++;
9517 if (c < '0' || c > '9')
9518 break;
9519 if ((width*10) / 10 != width) {
9520 PyErr_SetString(PyExc_ValueError,
9521 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009522 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00009523 }
9524 width = width*10 + (c - '0');
9525 }
9526 }
9527 if (c == '.') {
9528 prec = 0;
9529 if (--fmtcnt >= 0)
9530 c = *fmt++;
9531 if (c == '*') {
9532 v = getnextarg(args, arglen, &argidx);
9533 if (v == NULL)
9534 goto onError;
9535 if (!PyLong_Check(v)) {
9536 PyErr_SetString(PyExc_TypeError,
9537 "* wants int");
9538 goto onError;
9539 }
9540 prec = PyLong_AsLong(v);
9541 if (prec == -1 && PyErr_Occurred())
9542 goto onError;
9543 if (prec < 0)
9544 prec = 0;
9545 if (--fmtcnt >= 0)
9546 c = *fmt++;
9547 }
9548 else if (c >= '0' && c <= '9') {
9549 prec = c - '0';
9550 while (--fmtcnt >= 0) {
Stefan Krah99212f62010-07-19 17:58:26 +00009551 c = *fmt++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009552 if (c < '0' || c > '9')
9553 break;
9554 if ((prec*10) / 10 != prec) {
9555 PyErr_SetString(PyExc_ValueError,
9556 "prec too big");
9557 goto onError;
9558 }
9559 prec = prec*10 + (c - '0');
9560 }
9561 }
9562 } /* prec */
9563 if (fmtcnt >= 0) {
9564 if (c == 'h' || c == 'l' || c == 'L') {
9565 if (--fmtcnt >= 0)
9566 c = *fmt++;
9567 }
9568 }
9569 if (fmtcnt < 0) {
9570 PyErr_SetString(PyExc_ValueError,
9571 "incomplete format");
9572 goto onError;
9573 }
9574 if (c != '%') {
9575 v = getnextarg(args, arglen, &argidx);
9576 if (v == NULL)
9577 goto onError;
9578 }
9579 sign = 0;
9580 fill = ' ';
9581 switch (c) {
9582
9583 case '%':
9584 pbuf = formatbuf;
9585 /* presume that buffer length is at least 1 */
9586 pbuf[0] = '%';
9587 len = 1;
9588 break;
9589
9590 case 's':
9591 case 'r':
9592 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +00009593 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +00009594 temp = v;
9595 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009596 }
9597 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009598 if (c == 's')
9599 temp = PyObject_Str(v);
9600 else if (c == 'r')
9601 temp = PyObject_Repr(v);
9602 else
9603 temp = PyObject_ASCII(v);
9604 if (temp == NULL)
9605 goto onError;
9606 if (PyUnicode_Check(temp))
9607 /* nothing to do */;
9608 else {
9609 Py_DECREF(temp);
9610 PyErr_SetString(PyExc_TypeError,
9611 "%s argument has non-string str()");
9612 goto onError;
9613 }
9614 }
9615 pbuf = PyUnicode_AS_UNICODE(temp);
9616 len = PyUnicode_GET_SIZE(temp);
9617 if (prec >= 0 && len > prec)
9618 len = prec;
9619 break;
9620
9621 case 'i':
9622 case 'd':
9623 case 'u':
9624 case 'o':
9625 case 'x':
9626 case 'X':
9627 if (c == 'i')
9628 c = 'd';
9629 isnumok = 0;
9630 if (PyNumber_Check(v)) {
9631 PyObject *iobj=NULL;
9632
9633 if (PyLong_Check(v)) {
9634 iobj = v;
9635 Py_INCREF(iobj);
9636 }
9637 else {
9638 iobj = PyNumber_Long(v);
9639 }
9640 if (iobj!=NULL) {
9641 if (PyLong_Check(iobj)) {
9642 isnumok = 1;
9643 temp = formatlong(iobj, flags, prec, c);
9644 Py_DECREF(iobj);
9645 if (!temp)
9646 goto onError;
9647 pbuf = PyUnicode_AS_UNICODE(temp);
9648 len = PyUnicode_GET_SIZE(temp);
9649 sign = 1;
9650 }
9651 else {
9652 Py_DECREF(iobj);
9653 }
9654 }
9655 }
9656 if (!isnumok) {
9657 PyErr_Format(PyExc_TypeError,
9658 "%%%c format: a number is required, "
9659 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
9660 goto onError;
9661 }
9662 if (flags & F_ZERO)
9663 fill = '0';
9664 break;
9665
9666 case 'e':
9667 case 'E':
9668 case 'f':
9669 case 'F':
9670 case 'g':
9671 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009672 temp = formatfloat(v, flags, prec, c);
9673 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +00009674 goto onError;
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009675 pbuf = PyUnicode_AS_UNICODE(temp);
9676 len = PyUnicode_GET_SIZE(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +00009677 sign = 1;
9678 if (flags & F_ZERO)
9679 fill = '0';
9680 break;
9681
9682 case 'c':
9683 pbuf = formatbuf;
9684 len = formatchar(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), v);
9685 if (len < 0)
9686 goto onError;
9687 break;
9688
9689 default:
9690 PyErr_Format(PyExc_ValueError,
9691 "unsupported format character '%c' (0x%x) "
9692 "at index %zd",
9693 (31<=c && c<=126) ? (char)c : '?',
9694 (int)c,
9695 (Py_ssize_t)(fmt - 1 -
9696 PyUnicode_AS_UNICODE(uformat)));
9697 goto onError;
9698 }
9699 if (sign) {
9700 if (*pbuf == '-' || *pbuf == '+') {
9701 sign = *pbuf++;
9702 len--;
9703 }
9704 else if (flags & F_SIGN)
9705 sign = '+';
9706 else if (flags & F_BLANK)
9707 sign = ' ';
9708 else
9709 sign = 0;
9710 }
9711 if (width < len)
9712 width = len;
9713 if (rescnt - (sign != 0) < width) {
9714 reslen -= rescnt;
9715 rescnt = width + fmtcnt + 100;
9716 reslen += rescnt;
9717 if (reslen < 0) {
9718 Py_XDECREF(temp);
9719 PyErr_NoMemory();
9720 goto onError;
9721 }
9722 if (_PyUnicode_Resize(&result, reslen) < 0) {
9723 Py_XDECREF(temp);
9724 goto onError;
9725 }
9726 res = PyUnicode_AS_UNICODE(result)
9727 + reslen - rescnt;
9728 }
9729 if (sign) {
9730 if (fill != ' ')
9731 *res++ = sign;
9732 rescnt--;
9733 if (width > len)
9734 width--;
9735 }
9736 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
9737 assert(pbuf[0] == '0');
9738 assert(pbuf[1] == c);
9739 if (fill != ' ') {
9740 *res++ = *pbuf++;
9741 *res++ = *pbuf++;
9742 }
9743 rescnt -= 2;
9744 width -= 2;
9745 if (width < 0)
9746 width = 0;
9747 len -= 2;
9748 }
9749 if (width > len && !(flags & F_LJUST)) {
9750 do {
9751 --rescnt;
9752 *res++ = fill;
9753 } while (--width > len);
9754 }
9755 if (fill == ' ') {
9756 if (sign)
9757 *res++ = sign;
9758 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
9759 assert(pbuf[0] == '0');
9760 assert(pbuf[1] == c);
9761 *res++ = *pbuf++;
9762 *res++ = *pbuf++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009763 }
9764 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009765 Py_UNICODE_COPY(res, pbuf, len);
9766 res += len;
9767 rescnt -= len;
9768 while (--width >= len) {
9769 --rescnt;
9770 *res++ = ' ';
9771 }
9772 if (dict && (argidx < arglen) && c != '%') {
9773 PyErr_SetString(PyExc_TypeError,
9774 "not all arguments converted during string formatting");
Thomas Woutersa96affe2006-03-12 00:29:36 +00009775 Py_XDECREF(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +00009776 goto onError;
9777 }
9778 Py_XDECREF(temp);
9779 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009780 } /* until end */
9781 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009782 PyErr_SetString(PyExc_TypeError,
9783 "not all arguments converted during string formatting");
9784 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009785 }
9786
Thomas Woutersa96affe2006-03-12 00:29:36 +00009787 if (_PyUnicode_Resize(&result, reslen - rescnt) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009788 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009789 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009790 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009791 }
9792 Py_DECREF(uformat);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009793 return (PyObject *)result;
9794
Benjamin Peterson29060642009-01-31 22:14:21 +00009795 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009796 Py_XDECREF(result);
9797 Py_DECREF(uformat);
9798 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009799 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009800 }
9801 return NULL;
9802}
9803
Jeremy Hylton938ace62002-07-17 16:30:39 +00009804static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +00009805unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
9806
Tim Peters6d6c1a32001-08-02 04:15:00 +00009807static PyObject *
9808unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9809{
Benjamin Peterson29060642009-01-31 22:14:21 +00009810 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009811 static char *kwlist[] = {"object", "encoding", "errors", 0};
9812 char *encoding = NULL;
9813 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00009814
Benjamin Peterson14339b62009-01-31 16:36:08 +00009815 if (type != &PyUnicode_Type)
9816 return unicode_subtype_new(type, args, kwds);
9817 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +00009818 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009819 return NULL;
9820 if (x == NULL)
9821 return (PyObject *)_PyUnicode_New(0);
9822 if (encoding == NULL && errors == NULL)
9823 return PyObject_Str(x);
9824 else
Benjamin Peterson29060642009-01-31 22:14:21 +00009825 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +00009826}
9827
Guido van Rossume023fe02001-08-30 03:12:59 +00009828static PyObject *
9829unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9830{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009831 PyUnicodeObject *tmp, *pnew;
9832 Py_ssize_t n;
Guido van Rossume023fe02001-08-30 03:12:59 +00009833
Benjamin Peterson14339b62009-01-31 16:36:08 +00009834 assert(PyType_IsSubtype(type, &PyUnicode_Type));
9835 tmp = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
9836 if (tmp == NULL)
9837 return NULL;
9838 assert(PyUnicode_Check(tmp));
9839 pnew = (PyUnicodeObject *) type->tp_alloc(type, n = tmp->length);
9840 if (pnew == NULL) {
9841 Py_DECREF(tmp);
9842 return NULL;
9843 }
9844 pnew->str = (Py_UNICODE*) PyObject_MALLOC(sizeof(Py_UNICODE) * (n+1));
9845 if (pnew->str == NULL) {
9846 _Py_ForgetReference((PyObject *)pnew);
9847 PyObject_Del(pnew);
9848 Py_DECREF(tmp);
9849 return PyErr_NoMemory();
9850 }
9851 Py_UNICODE_COPY(pnew->str, tmp->str, n+1);
9852 pnew->length = n;
9853 pnew->hash = tmp->hash;
9854 Py_DECREF(tmp);
9855 return (PyObject *)pnew;
Guido van Rossume023fe02001-08-30 03:12:59 +00009856}
9857
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009858PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +00009859 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00009860\n\
Collin Winterd474ce82007-08-07 19:42:11 +00009861Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +00009862encoding defaults to the current default string encoding.\n\
9863errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00009864
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009865static PyObject *unicode_iter(PyObject *seq);
9866
Guido van Rossumd57fd912000-03-10 22:53:23 +00009867PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00009868 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +00009869 "str", /* tp_name */
9870 sizeof(PyUnicodeObject), /* tp_size */
9871 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009872 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009873 (destructor)unicode_dealloc, /* tp_dealloc */
9874 0, /* tp_print */
9875 0, /* tp_getattr */
9876 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00009877 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009878 unicode_repr, /* tp_repr */
9879 &unicode_as_number, /* tp_as_number */
9880 &unicode_as_sequence, /* tp_as_sequence */
9881 &unicode_as_mapping, /* tp_as_mapping */
9882 (hashfunc) unicode_hash, /* tp_hash*/
9883 0, /* tp_call*/
9884 (reprfunc) unicode_str, /* tp_str */
9885 PyObject_GenericGetAttr, /* tp_getattro */
9886 0, /* tp_setattro */
9887 0, /* tp_as_buffer */
9888 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +00009889 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009890 unicode_doc, /* tp_doc */
9891 0, /* tp_traverse */
9892 0, /* tp_clear */
9893 PyUnicode_RichCompare, /* tp_richcompare */
9894 0, /* tp_weaklistoffset */
9895 unicode_iter, /* tp_iter */
9896 0, /* tp_iternext */
9897 unicode_methods, /* tp_methods */
9898 0, /* tp_members */
9899 0, /* tp_getset */
9900 &PyBaseObject_Type, /* tp_base */
9901 0, /* tp_dict */
9902 0, /* tp_descr_get */
9903 0, /* tp_descr_set */
9904 0, /* tp_dictoffset */
9905 0, /* tp_init */
9906 0, /* tp_alloc */
9907 unicode_new, /* tp_new */
9908 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009909};
9910
9911/* Initialize the Unicode implementation */
9912
Thomas Wouters78890102000-07-22 19:25:51 +00009913void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009914{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009915 int i;
9916
Thomas Wouters477c8d52006-05-27 19:21:47 +00009917 /* XXX - move this array to unicodectype.c ? */
9918 Py_UNICODE linebreak[] = {
9919 0x000A, /* LINE FEED */
9920 0x000D, /* CARRIAGE RETURN */
9921 0x001C, /* FILE SEPARATOR */
9922 0x001D, /* GROUP SEPARATOR */
9923 0x001E, /* RECORD SEPARATOR */
9924 0x0085, /* NEXT LINE */
9925 0x2028, /* LINE SEPARATOR */
9926 0x2029, /* PARAGRAPH SEPARATOR */
9927 };
9928
Fred Drakee4315f52000-05-09 19:53:39 +00009929 /* Init the implementation */
Christian Heimes2202f872008-02-06 14:31:34 +00009930 free_list = NULL;
9931 numfree = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009932 unicode_empty = _PyUnicode_New(0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009933 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00009934 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009935
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009936 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00009937 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +00009938 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009939 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +00009940
9941 /* initialize the linebreak bloom filter */
9942 bloom_linebreak = make_bloom_mask(
9943 linebreak, sizeof(linebreak) / sizeof(linebreak[0])
9944 );
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009945
9946 PyType_Ready(&EncodingMapType);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009947}
9948
9949/* Finalize the Unicode implementation */
9950
Christian Heimesa156e092008-02-16 07:38:31 +00009951int
9952PyUnicode_ClearFreeList(void)
9953{
9954 int freelist_size = numfree;
9955 PyUnicodeObject *u;
9956
9957 for (u = free_list; u != NULL;) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009958 PyUnicodeObject *v = u;
9959 u = *(PyUnicodeObject **)u;
9960 if (v->str)
9961 PyObject_DEL(v->str);
9962 Py_XDECREF(v->defenc);
9963 PyObject_Del(v);
9964 numfree--;
Christian Heimesa156e092008-02-16 07:38:31 +00009965 }
9966 free_list = NULL;
9967 assert(numfree == 0);
9968 return freelist_size;
9969}
9970
Guido van Rossumd57fd912000-03-10 22:53:23 +00009971void
Thomas Wouters78890102000-07-22 19:25:51 +00009972_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009973{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009974 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009975
Guido van Rossum4ae8ef82000-10-03 18:09:04 +00009976 Py_XDECREF(unicode_empty);
9977 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +00009978
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009979 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009980 if (unicode_latin1[i]) {
9981 Py_DECREF(unicode_latin1[i]);
9982 unicode_latin1[i] = NULL;
9983 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009984 }
Christian Heimesa156e092008-02-16 07:38:31 +00009985 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +00009986}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00009987
Walter Dörwald16807132007-05-25 13:52:07 +00009988void
9989PyUnicode_InternInPlace(PyObject **p)
9990{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009991 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
9992 PyObject *t;
9993 if (s == NULL || !PyUnicode_Check(s))
9994 Py_FatalError(
9995 "PyUnicode_InternInPlace: unicode strings only please!");
9996 /* If it's a subclass, we don't really know what putting
9997 it in the interned dict might do. */
9998 if (!PyUnicode_CheckExact(s))
9999 return;
10000 if (PyUnicode_CHECK_INTERNED(s))
10001 return;
10002 if (interned == NULL) {
10003 interned = PyDict_New();
10004 if (interned == NULL) {
10005 PyErr_Clear(); /* Don't leave an exception */
10006 return;
10007 }
10008 }
10009 /* It might be that the GetItem call fails even
10010 though the key is present in the dictionary,
10011 namely when this happens during a stack overflow. */
10012 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000010013 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010014 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000010015
Benjamin Peterson29060642009-01-31 22:14:21 +000010016 if (t) {
10017 Py_INCREF(t);
10018 Py_DECREF(*p);
10019 *p = t;
10020 return;
10021 }
Walter Dörwald16807132007-05-25 13:52:07 +000010022
Benjamin Peterson14339b62009-01-31 16:36:08 +000010023 PyThreadState_GET()->recursion_critical = 1;
10024 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
10025 PyErr_Clear();
10026 PyThreadState_GET()->recursion_critical = 0;
10027 return;
10028 }
10029 PyThreadState_GET()->recursion_critical = 0;
10030 /* The two references in interned are not counted by refcnt.
10031 The deallocator will take care of this */
10032 Py_REFCNT(s) -= 2;
10033 PyUnicode_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000010034}
10035
10036void
10037PyUnicode_InternImmortal(PyObject **p)
10038{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010039 PyUnicode_InternInPlace(p);
10040 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
10041 PyUnicode_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
10042 Py_INCREF(*p);
10043 }
Walter Dörwald16807132007-05-25 13:52:07 +000010044}
10045
10046PyObject *
10047PyUnicode_InternFromString(const char *cp)
10048{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010049 PyObject *s = PyUnicode_FromString(cp);
10050 if (s == NULL)
10051 return NULL;
10052 PyUnicode_InternInPlace(&s);
10053 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000010054}
10055
10056void _Py_ReleaseInternedUnicodeStrings(void)
10057{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010058 PyObject *keys;
10059 PyUnicodeObject *s;
10060 Py_ssize_t i, n;
10061 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000010062
Benjamin Peterson14339b62009-01-31 16:36:08 +000010063 if (interned == NULL || !PyDict_Check(interned))
10064 return;
10065 keys = PyDict_Keys(interned);
10066 if (keys == NULL || !PyList_Check(keys)) {
10067 PyErr_Clear();
10068 return;
10069 }
Walter Dörwald16807132007-05-25 13:52:07 +000010070
Benjamin Peterson14339b62009-01-31 16:36:08 +000010071 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
10072 detector, interned unicode strings are not forcibly deallocated;
10073 rather, we give them their stolen references back, and then clear
10074 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000010075
Benjamin Peterson14339b62009-01-31 16:36:08 +000010076 n = PyList_GET_SIZE(keys);
10077 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000010078 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010079 for (i = 0; i < n; i++) {
10080 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
10081 switch (s->state) {
10082 case SSTATE_NOT_INTERNED:
10083 /* XXX Shouldn't happen */
10084 break;
10085 case SSTATE_INTERNED_IMMORTAL:
10086 Py_REFCNT(s) += 1;
10087 immortal_size += s->length;
10088 break;
10089 case SSTATE_INTERNED_MORTAL:
10090 Py_REFCNT(s) += 2;
10091 mortal_size += s->length;
10092 break;
10093 default:
10094 Py_FatalError("Inconsistent interned string state.");
10095 }
10096 s->state = SSTATE_NOT_INTERNED;
10097 }
10098 fprintf(stderr, "total size of all interned strings: "
10099 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
10100 "mortal/immortal\n", mortal_size, immortal_size);
10101 Py_DECREF(keys);
10102 PyDict_Clear(interned);
10103 Py_DECREF(interned);
10104 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000010105}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010106
10107
10108/********************* Unicode Iterator **************************/
10109
10110typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010111 PyObject_HEAD
10112 Py_ssize_t it_index;
10113 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010114} unicodeiterobject;
10115
10116static void
10117unicodeiter_dealloc(unicodeiterobject *it)
10118{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010119 _PyObject_GC_UNTRACK(it);
10120 Py_XDECREF(it->it_seq);
10121 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010122}
10123
10124static int
10125unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
10126{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010127 Py_VISIT(it->it_seq);
10128 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010129}
10130
10131static PyObject *
10132unicodeiter_next(unicodeiterobject *it)
10133{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010134 PyUnicodeObject *seq;
10135 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010136
Benjamin Peterson14339b62009-01-31 16:36:08 +000010137 assert(it != NULL);
10138 seq = it->it_seq;
10139 if (seq == NULL)
10140 return NULL;
10141 assert(PyUnicode_Check(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010142
Benjamin Peterson14339b62009-01-31 16:36:08 +000010143 if (it->it_index < PyUnicode_GET_SIZE(seq)) {
10144 item = PyUnicode_FromUnicode(
Benjamin Peterson29060642009-01-31 22:14:21 +000010145 PyUnicode_AS_UNICODE(seq)+it->it_index, 1);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010146 if (item != NULL)
10147 ++it->it_index;
10148 return item;
10149 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010150
Benjamin Peterson14339b62009-01-31 16:36:08 +000010151 Py_DECREF(seq);
10152 it->it_seq = NULL;
10153 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010154}
10155
10156static PyObject *
10157unicodeiter_len(unicodeiterobject *it)
10158{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010159 Py_ssize_t len = 0;
10160 if (it->it_seq)
10161 len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index;
10162 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010163}
10164
10165PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
10166
10167static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010168 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000010169 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000010170 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010171};
10172
10173PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010174 PyVarObject_HEAD_INIT(&PyType_Type, 0)
10175 "str_iterator", /* tp_name */
10176 sizeof(unicodeiterobject), /* tp_basicsize */
10177 0, /* tp_itemsize */
10178 /* methods */
10179 (destructor)unicodeiter_dealloc, /* tp_dealloc */
10180 0, /* tp_print */
10181 0, /* tp_getattr */
10182 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000010183 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000010184 0, /* tp_repr */
10185 0, /* tp_as_number */
10186 0, /* tp_as_sequence */
10187 0, /* tp_as_mapping */
10188 0, /* tp_hash */
10189 0, /* tp_call */
10190 0, /* tp_str */
10191 PyObject_GenericGetAttr, /* tp_getattro */
10192 0, /* tp_setattro */
10193 0, /* tp_as_buffer */
10194 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
10195 0, /* tp_doc */
10196 (traverseproc)unicodeiter_traverse, /* tp_traverse */
10197 0, /* tp_clear */
10198 0, /* tp_richcompare */
10199 0, /* tp_weaklistoffset */
10200 PyObject_SelfIter, /* tp_iter */
10201 (iternextfunc)unicodeiter_next, /* tp_iternext */
10202 unicodeiter_methods, /* tp_methods */
10203 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010204};
10205
10206static PyObject *
10207unicode_iter(PyObject *seq)
10208{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010209 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010210
Benjamin Peterson14339b62009-01-31 16:36:08 +000010211 if (!PyUnicode_Check(seq)) {
10212 PyErr_BadInternalCall();
10213 return NULL;
10214 }
10215 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
10216 if (it == NULL)
10217 return NULL;
10218 it->it_index = 0;
10219 Py_INCREF(seq);
10220 it->it_seq = (PyUnicodeObject *)seq;
10221 _PyObject_GC_TRACK(it);
10222 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010223}
10224
Martin v. Löwis5b222132007-06-10 09:51:05 +000010225size_t
10226Py_UNICODE_strlen(const Py_UNICODE *u)
10227{
10228 int res = 0;
10229 while(*u++)
10230 res++;
10231 return res;
10232}
10233
10234Py_UNICODE*
10235Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
10236{
10237 Py_UNICODE *u = s1;
10238 while ((*u++ = *s2++));
10239 return s1;
10240}
10241
10242Py_UNICODE*
10243Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
10244{
10245 Py_UNICODE *u = s1;
10246 while ((*u++ = *s2++))
10247 if (n-- == 0)
10248 break;
10249 return s1;
10250}
10251
Victor Stinnerc4eb7652010-09-01 23:43:50 +000010252Py_UNICODE*
10253Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
10254{
10255 Py_UNICODE *u1 = s1;
10256 u1 += Py_UNICODE_strlen(u1);
10257 Py_UNICODE_strcpy(u1, s2);
10258 return s1;
10259}
10260
Martin v. Löwis5b222132007-06-10 09:51:05 +000010261int
10262Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
10263{
10264 while (*s1 && *s2 && *s1 == *s2)
10265 s1++, s2++;
10266 if (*s1 && *s2)
10267 return (*s1 < *s2) ? -1 : +1;
10268 if (*s1)
10269 return 1;
10270 if (*s2)
10271 return -1;
10272 return 0;
10273}
10274
Victor Stinneref8d95c2010-08-16 22:03:11 +000010275int
10276Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
10277{
10278 register Py_UNICODE u1, u2;
10279 for (; n != 0; n--) {
10280 u1 = *s1;
10281 u2 = *s2;
10282 if (u1 != u2)
10283 return (u1 < u2) ? -1 : +1;
10284 if (u1 == '\0')
10285 return 0;
10286 s1++;
10287 s2++;
10288 }
10289 return 0;
10290}
10291
Martin v. Löwis5b222132007-06-10 09:51:05 +000010292Py_UNICODE*
10293Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
10294{
10295 const Py_UNICODE *p;
10296 for (p = s; *p; p++)
10297 if (*p == c)
10298 return (Py_UNICODE*)p;
10299 return NULL;
10300}
10301
Victor Stinner331ea922010-08-10 16:37:20 +000010302Py_UNICODE*
10303Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
10304{
10305 const Py_UNICODE *p;
10306 p = s + Py_UNICODE_strlen(s);
10307 while (p != s) {
10308 p--;
10309 if (*p == c)
10310 return (Py_UNICODE*)p;
10311 }
10312 return NULL;
10313}
10314
Victor Stinner71133ff2010-09-01 23:43:53 +000010315Py_UNICODE*
Victor Stinner46408602010-09-03 16:18:00 +000010316PyUnicode_AsUnicodeCopy(PyObject *object)
Victor Stinner71133ff2010-09-01 23:43:53 +000010317{
10318 PyUnicodeObject *unicode = (PyUnicodeObject *)object;
10319 Py_UNICODE *copy;
10320 Py_ssize_t size;
10321
10322 /* Ensure we won't overflow the size. */
10323 if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
10324 PyErr_NoMemory();
10325 return NULL;
10326 }
10327 size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
10328 size *= sizeof(Py_UNICODE);
10329 copy = PyMem_Malloc(size);
10330 if (copy == NULL) {
10331 PyErr_NoMemory();
10332 return NULL;
10333 }
10334 memcpy(copy, PyUnicode_AS_UNICODE(unicode), size);
10335 return copy;
10336}
Martin v. Löwis5b222132007-06-10 09:51:05 +000010337
Georg Brandl66c221e2010-10-14 07:04:07 +000010338/* A _string module, to export formatter_parser and formatter_field_name_split
10339 to the string.Formatter class implemented in Python. */
10340
10341static PyMethodDef _string_methods[] = {
10342 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
10343 METH_O, PyDoc_STR("split the argument as a field name")},
10344 {"formatter_parser", (PyCFunction) formatter_parser,
10345 METH_O, PyDoc_STR("parse the argument as a format string")},
10346 {NULL, NULL}
10347};
10348
10349static struct PyModuleDef _string_module = {
10350 PyModuleDef_HEAD_INIT,
10351 "_string",
10352 PyDoc_STR("string helper module"),
10353 0,
10354 _string_methods,
10355 NULL,
10356 NULL,
10357 NULL,
10358 NULL
10359};
10360
10361PyMODINIT_FUNC
10362PyInit__string(void)
10363{
10364 return PyModule_Create(&_string_module);
10365}
10366
10367
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010368#ifdef __cplusplus
10369}
10370#endif