blob: a18eeef57ac5370c57d0f708c74413c9a98f1b11 [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;
760 while (ISDIGIT((unsigned)*f))
761 width = (width*10) + *f++ - '0';
762 while (*++f && *f != '%' && !ISALPHA((unsigned)*f))
763 ;
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;
793 while (ISDIGIT((unsigned)*f))
794 width = (width*10) + *f++ - '0';
795 while (*++f && *f != '%' && !ISALPHA((unsigned)*f))
796 ;
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;
968 while (ISDIGIT((unsigned)*f))
969 width = (width*10) + *f++ - '0';
970 precision = 0;
971 if (*f == '.') {
972 f++;
973 while (ISDIGIT((unsigned)*f))
974 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':
1077 {
1078 Py_UNICODE *ucopy;
1079 Py_ssize_t usize;
1080 Py_ssize_t upos;
1081 /* unused, since we already have the result */
1082 (void) va_arg(vargs, PyObject *);
1083 ucopy = PyUnicode_AS_UNICODE(*callresult);
1084 usize = PyUnicode_GET_SIZE(*callresult);
1085 for (upos = 0; upos<usize;)
1086 *s++ = ucopy[upos++];
1087 /* We're done with the unicode()/repr() => forget it */
1088 Py_DECREF(*callresult);
1089 /* switch to next unicode()/repr() result */
1090 ++callresult;
1091 break;
1092 }
1093 case 'p':
1094 sprintf(buffer, "%p", va_arg(vargs, void*));
1095 /* %p is ill-defined: ensure leading 0x. */
1096 if (buffer[1] == 'X')
1097 buffer[1] = 'x';
1098 else if (buffer[1] != 'x') {
1099 memmove(buffer+2, buffer, strlen(buffer)+1);
1100 buffer[0] = '0';
1101 buffer[1] = 'x';
1102 }
1103 appendstring(buffer);
1104 break;
1105 case '%':
1106 *s++ = '%';
1107 break;
1108 default:
1109 appendstring(p);
1110 goto end;
1111 }
Victor Stinner1205f272010-09-11 00:54:47 +00001112 }
Victor Stinner1205f272010-09-11 00:54:47 +00001113 else
Benjamin Peterson14339b62009-01-31 16:36:08 +00001114 *s++ = *f;
1115 }
Walter Dörwaldd2034312007-05-18 16:29:38 +00001116
Benjamin Peterson29060642009-01-31 22:14:21 +00001117 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001118 if (callresults)
1119 PyObject_Free(callresults);
1120 if (abuffer)
1121 PyObject_Free(abuffer);
1122 PyUnicode_Resize(&string, s - PyUnicode_AS_UNICODE(string));
1123 return string;
Benjamin Peterson29060642009-01-31 22:14:21 +00001124 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001125 if (callresults) {
1126 PyObject **callresult2 = callresults;
1127 while (callresult2 < callresult) {
1128 Py_DECREF(*callresult2);
1129 ++callresult2;
1130 }
1131 PyObject_Free(callresults);
1132 }
1133 if (abuffer)
1134 PyObject_Free(abuffer);
1135 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001136}
1137
1138#undef appendstring
1139
1140PyObject *
1141PyUnicode_FromFormat(const char *format, ...)
1142{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001143 PyObject* ret;
1144 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001145
1146#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00001147 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001148#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00001149 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001150#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001151 ret = PyUnicode_FromFormatV(format, vargs);
1152 va_end(vargs);
1153 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001154}
1155
Victor Stinner5593d8a2010-10-02 11:11:27 +00001156/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
1157 convert a Unicode object to a wide character string.
1158
1159 - If w is NULL: return the number of wide characters (including the nul
1160 character) required to convert the unicode object. Ignore size argument.
1161
1162 - Otherwise: return the number of wide characters (excluding the nul
1163 character) written into w. Write at most size wide characters (including
1164 the nul character). */
1165static Py_ssize_t
Victor Stinner137c34c2010-09-29 10:25:54 +00001166unicode_aswidechar(PyUnicodeObject *unicode,
1167 wchar_t *w,
1168 Py_ssize_t size)
1169{
1170#if Py_UNICODE_SIZE == SIZEOF_WCHAR_T
Victor Stinner5593d8a2010-10-02 11:11:27 +00001171 Py_ssize_t res;
1172 if (w != NULL) {
1173 res = PyUnicode_GET_SIZE(unicode);
1174 if (size > res)
1175 size = res + 1;
1176 else
1177 res = size;
1178 memcpy(w, unicode->str, size * sizeof(wchar_t));
1179 return res;
1180 }
1181 else
1182 return PyUnicode_GET_SIZE(unicode) + 1;
1183#elif Py_UNICODE_SIZE == 2 && SIZEOF_WCHAR_T == 4
1184 register const Py_UNICODE *u;
1185 const Py_UNICODE *uend;
1186 const wchar_t *worig, *wend;
1187 Py_ssize_t nchar;
1188
Victor Stinner137c34c2010-09-29 10:25:54 +00001189 u = PyUnicode_AS_UNICODE(unicode);
Victor Stinner5593d8a2010-10-02 11:11:27 +00001190 uend = u + PyUnicode_GET_SIZE(unicode);
1191 if (w != NULL) {
1192 worig = w;
1193 wend = w + size;
1194 while (u != uend && w != wend) {
1195 if (0xD800 <= u[0] && u[0] <= 0xDBFF
1196 && 0xDC00 <= u[1] && u[1] <= 0xDFFF)
1197 {
1198 *w = (((u[0] & 0x3FF) << 10) | (u[1] & 0x3FF)) + 0x10000;
1199 u += 2;
1200 }
1201 else {
1202 *w = *u;
1203 u++;
1204 }
1205 w++;
1206 }
1207 if (w != wend)
1208 *w = L'\0';
1209 return w - worig;
1210 }
1211 else {
1212 nchar = 1; /* nul character at the end */
1213 while (u != uend) {
1214 if (0xD800 <= u[0] && u[0] <= 0xDBFF
1215 && 0xDC00 <= u[1] && u[1] <= 0xDFFF)
1216 u += 2;
1217 else
1218 u++;
1219 nchar++;
1220 }
1221 }
1222 return nchar;
1223#elif Py_UNICODE_SIZE == 4 && SIZEOF_WCHAR_T == 2
1224 register Py_UNICODE *u, *uend, ordinal;
1225 register Py_ssize_t i;
1226 wchar_t *worig, *wend;
1227 Py_ssize_t nchar;
1228
1229 u = PyUnicode_AS_UNICODE(unicode);
1230 uend = u + PyUnicode_GET_SIZE(u);
1231 if (w != NULL) {
1232 worig = w;
1233 wend = w + size;
1234 while (u != uend && w != wend) {
1235 ordinal = *u;
1236 if (ordinal > 0xffff) {
1237 ordinal -= 0x10000;
1238 *w++ = 0xD800 | (ordinal >> 10);
1239 *w++ = 0xDC00 | (ordinal & 0x3FF);
1240 }
1241 else
1242 *w++ = ordinal;
1243 u++;
1244 }
1245 if (w != wend)
1246 *w = 0;
1247 return w - worig;
1248 }
1249 else {
1250 nchar = 1; /* nul character */
1251 while (u != uend) {
1252 if (*u > 0xffff)
1253 nchar += 2;
1254 else
1255 nchar++;
1256 u++;
1257 }
1258 return nchar;
1259 }
1260#else
1261# error "unsupported wchar_t and Py_UNICODE sizes, see issue #8670"
Victor Stinner137c34c2010-09-29 10:25:54 +00001262#endif
1263}
1264
1265Py_ssize_t
1266PyUnicode_AsWideChar(PyUnicodeObject *unicode,
1267 wchar_t *w,
1268 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001269{
1270 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001271 PyErr_BadInternalCall();
1272 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001273 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00001274 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001275}
1276
Victor Stinner137c34c2010-09-29 10:25:54 +00001277wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00001278PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00001279 Py_ssize_t *size)
1280{
1281 wchar_t* buffer;
1282 Py_ssize_t buflen;
1283
1284 if (unicode == NULL) {
1285 PyErr_BadInternalCall();
1286 return NULL;
1287 }
1288
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00001289 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, NULL, 0);
Victor Stinner5593d8a2010-10-02 11:11:27 +00001290 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00001291 PyErr_NoMemory();
1292 return NULL;
1293 }
1294
Victor Stinner137c34c2010-09-29 10:25:54 +00001295 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
1296 if (buffer == NULL) {
1297 PyErr_NoMemory();
1298 return NULL;
1299 }
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00001300 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, buffer, buflen);
Victor Stinner5593d8a2010-10-02 11:11:27 +00001301 if (size != NULL)
1302 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00001303 return buffer;
1304}
1305
Guido van Rossumd57fd912000-03-10 22:53:23 +00001306#endif
1307
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001308PyObject *PyUnicode_FromOrdinal(int ordinal)
1309{
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001310 Py_UNICODE s[2];
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001311
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001312 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001313 PyErr_SetString(PyExc_ValueError,
1314 "chr() arg not in range(0x110000)");
1315 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001316 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001317
1318#ifndef Py_UNICODE_WIDE
1319 if (ordinal > 0xffff) {
1320 ordinal -= 0x10000;
1321 s[0] = 0xD800 | (ordinal >> 10);
1322 s[1] = 0xDC00 | (ordinal & 0x3FF);
1323 return PyUnicode_FromUnicode(s, 2);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001324 }
1325#endif
1326
Hye-Shik Chang40574832004-04-06 07:24:51 +00001327 s[0] = (Py_UNICODE)ordinal;
1328 return PyUnicode_FromUnicode(s, 1);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001329}
1330
Guido van Rossumd57fd912000-03-10 22:53:23 +00001331PyObject *PyUnicode_FromObject(register PyObject *obj)
1332{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001333 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00001334 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001335 if (PyUnicode_CheckExact(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001336 Py_INCREF(obj);
1337 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001338 }
1339 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001340 /* For a Unicode subtype that's not a Unicode object,
1341 return a true Unicode object with the same data. */
1342 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(obj),
1343 PyUnicode_GET_SIZE(obj));
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001344 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001345 PyErr_Format(PyExc_TypeError,
1346 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00001347 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001348 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001349}
1350
1351PyObject *PyUnicode_FromEncodedObject(register PyObject *obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00001352 const char *encoding,
1353 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001354{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001355 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001356 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00001357
Guido van Rossumd57fd912000-03-10 22:53:23 +00001358 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001359 PyErr_BadInternalCall();
1360 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001361 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001362
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001363 /* Decoding bytes objects is the most common case and should be fast */
1364 if (PyBytes_Check(obj)) {
1365 if (PyBytes_GET_SIZE(obj) == 0) {
1366 Py_INCREF(unicode_empty);
1367 v = (PyObject *) unicode_empty;
1368 }
1369 else {
1370 v = PyUnicode_Decode(
1371 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
1372 encoding, errors);
1373 }
1374 return v;
1375 }
1376
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001377 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001378 PyErr_SetString(PyExc_TypeError,
1379 "decoding str is not supported");
1380 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001381 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001382
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001383 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
1384 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
1385 PyErr_Format(PyExc_TypeError,
1386 "coercing to str: need bytes, bytearray "
1387 "or buffer-like object, %.80s found",
1388 Py_TYPE(obj)->tp_name);
1389 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00001390 }
Tim Petersced69f82003-09-16 20:30:58 +00001391
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001392 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001393 Py_INCREF(unicode_empty);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001394 v = (PyObject *) unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001395 }
Tim Petersced69f82003-09-16 20:30:58 +00001396 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001397 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00001398
Antoine Pitroub0fa8312010-09-01 15:10:12 +00001399 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001400 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001401}
1402
Victor Stinner600d3be2010-06-10 12:00:55 +00001403/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00001404 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
1405 1 on success. */
1406static int
1407normalize_encoding(const char *encoding,
1408 char *lower,
1409 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001410{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001411 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00001412 char *l;
1413 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001414
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001415 e = encoding;
1416 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00001417 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00001418 while (*e) {
1419 if (l == l_end)
1420 return 0;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001421 if (ISUPPER(*e)) {
1422 *l++ = TOLOWER(*e++);
1423 }
1424 else if (*e == '_') {
1425 *l++ = '-';
1426 e++;
1427 }
1428 else {
1429 *l++ = *e++;
1430 }
1431 }
1432 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00001433 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00001434}
1435
1436PyObject *PyUnicode_Decode(const char *s,
1437 Py_ssize_t size,
1438 const char *encoding,
1439 const char *errors)
1440{
1441 PyObject *buffer = NULL, *unicode;
1442 Py_buffer info;
1443 char lower[11]; /* Enough for any encoding shortcut */
1444
1445 if (encoding == NULL)
1446 encoding = PyUnicode_GetDefaultEncoding();
Fred Drakee4315f52000-05-09 19:53:39 +00001447
1448 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00001449 if (normalize_encoding(encoding, lower, sizeof(lower))) {
1450 if (strcmp(lower, "utf-8") == 0)
1451 return PyUnicode_DecodeUTF8(s, size, errors);
1452 else if ((strcmp(lower, "latin-1") == 0) ||
1453 (strcmp(lower, "iso-8859-1") == 0))
1454 return PyUnicode_DecodeLatin1(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001455#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Victor Stinner37296e82010-06-10 13:36:23 +00001456 else if (strcmp(lower, "mbcs") == 0)
1457 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001458#endif
Victor Stinner37296e82010-06-10 13:36:23 +00001459 else if (strcmp(lower, "ascii") == 0)
1460 return PyUnicode_DecodeASCII(s, size, errors);
1461 else if (strcmp(lower, "utf-16") == 0)
1462 return PyUnicode_DecodeUTF16(s, size, errors, 0);
1463 else if (strcmp(lower, "utf-32") == 0)
1464 return PyUnicode_DecodeUTF32(s, size, errors, 0);
1465 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001466
1467 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00001468 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00001469 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00001470 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00001471 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001472 if (buffer == NULL)
1473 goto onError;
1474 unicode = PyCodec_Decode(buffer, encoding, errors);
1475 if (unicode == NULL)
1476 goto onError;
1477 if (!PyUnicode_Check(unicode)) {
1478 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001479 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00001480 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001481 Py_DECREF(unicode);
1482 goto onError;
1483 }
1484 Py_DECREF(buffer);
1485 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00001486
Benjamin Peterson29060642009-01-31 22:14:21 +00001487 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001488 Py_XDECREF(buffer);
1489 return NULL;
1490}
1491
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001492PyObject *PyUnicode_AsDecodedObject(PyObject *unicode,
1493 const char *encoding,
1494 const char *errors)
1495{
1496 PyObject *v;
1497
1498 if (!PyUnicode_Check(unicode)) {
1499 PyErr_BadArgument();
1500 goto onError;
1501 }
1502
1503 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001504 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001505
1506 /* Decode via the codec registry */
1507 v = PyCodec_Decode(unicode, encoding, errors);
1508 if (v == NULL)
1509 goto onError;
1510 return v;
1511
Benjamin Peterson29060642009-01-31 22:14:21 +00001512 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001513 return NULL;
1514}
1515
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001516PyObject *PyUnicode_AsDecodedUnicode(PyObject *unicode,
1517 const char *encoding,
1518 const char *errors)
1519{
1520 PyObject *v;
1521
1522 if (!PyUnicode_Check(unicode)) {
1523 PyErr_BadArgument();
1524 goto onError;
1525 }
1526
1527 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001528 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001529
1530 /* Decode via the codec registry */
1531 v = PyCodec_Decode(unicode, encoding, errors);
1532 if (v == NULL)
1533 goto onError;
1534 if (!PyUnicode_Check(v)) {
1535 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001536 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001537 Py_TYPE(v)->tp_name);
1538 Py_DECREF(v);
1539 goto onError;
1540 }
1541 return v;
1542
Benjamin Peterson29060642009-01-31 22:14:21 +00001543 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001544 return NULL;
1545}
1546
Guido van Rossumd57fd912000-03-10 22:53:23 +00001547PyObject *PyUnicode_Encode(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00001548 Py_ssize_t size,
1549 const char *encoding,
1550 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001551{
1552 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00001553
Guido van Rossumd57fd912000-03-10 22:53:23 +00001554 unicode = PyUnicode_FromUnicode(s, size);
1555 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001556 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001557 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
1558 Py_DECREF(unicode);
1559 return v;
1560}
1561
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001562PyObject *PyUnicode_AsEncodedObject(PyObject *unicode,
1563 const char *encoding,
1564 const char *errors)
1565{
1566 PyObject *v;
1567
1568 if (!PyUnicode_Check(unicode)) {
1569 PyErr_BadArgument();
1570 goto onError;
1571 }
1572
1573 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001574 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001575
1576 /* Encode via the codec registry */
1577 v = PyCodec_Encode(unicode, encoding, errors);
1578 if (v == NULL)
1579 goto onError;
1580 return v;
1581
Benjamin Peterson29060642009-01-31 22:14:21 +00001582 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001583 return NULL;
1584}
1585
Victor Stinnerae6265f2010-05-15 16:27:27 +00001586PyObject *PyUnicode_EncodeFSDefault(PyObject *unicode)
1587{
Victor Stinner313a1202010-06-11 23:56:51 +00001588 if (Py_FileSystemDefaultEncoding) {
1589#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
1590 if (strcmp(Py_FileSystemDefaultEncoding, "mbcs") == 0)
1591 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
1592 PyUnicode_GET_SIZE(unicode),
1593 NULL);
1594#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00001595 return PyUnicode_AsEncodedString(unicode,
1596 Py_FileSystemDefaultEncoding,
1597 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00001598 }
1599 else {
1600 /* if you change the default encoding, update also
1601 PyUnicode_DecodeFSDefaultAndSize() and redecode_filenames() */
Victor Stinnerae6265f2010-05-15 16:27:27 +00001602 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
Victor Stinner3119ed72010-08-18 22:26:50 +00001603 PyUnicode_GET_SIZE(unicode),
1604 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00001605 }
Victor Stinnerae6265f2010-05-15 16:27:27 +00001606}
1607
Guido van Rossumd57fd912000-03-10 22:53:23 +00001608PyObject *PyUnicode_AsEncodedString(PyObject *unicode,
1609 const char *encoding,
1610 const char *errors)
1611{
1612 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00001613 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00001614
Guido van Rossumd57fd912000-03-10 22:53:23 +00001615 if (!PyUnicode_Check(unicode)) {
1616 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001617 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001618 }
Fred Drakee4315f52000-05-09 19:53:39 +00001619
Tim Petersced69f82003-09-16 20:30:58 +00001620 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001621 encoding = PyUnicode_GetDefaultEncoding();
Fred Drakee4315f52000-05-09 19:53:39 +00001622
1623 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00001624 if (normalize_encoding(encoding, lower, sizeof(lower))) {
1625 if (strcmp(lower, "utf-8") == 0)
1626 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
1627 PyUnicode_GET_SIZE(unicode),
1628 errors);
1629 else if ((strcmp(lower, "latin-1") == 0) ||
1630 (strcmp(lower, "iso-8859-1") == 0))
1631 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
1632 PyUnicode_GET_SIZE(unicode),
1633 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001634#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Victor Stinner37296e82010-06-10 13:36:23 +00001635 else if (strcmp(lower, "mbcs") == 0)
1636 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
1637 PyUnicode_GET_SIZE(unicode),
1638 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001639#endif
Victor Stinner37296e82010-06-10 13:36:23 +00001640 else if (strcmp(lower, "ascii") == 0)
1641 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
1642 PyUnicode_GET_SIZE(unicode),
1643 errors);
1644 }
Victor Stinner59e62db2010-05-15 13:14:32 +00001645 /* During bootstrap, we may need to find the encodings
1646 package, to load the file system encoding, and require the
1647 file system encoding in order to load the encodings
1648 package.
Christian Heimes6a27efa2008-10-30 21:48:26 +00001649
Victor Stinner59e62db2010-05-15 13:14:32 +00001650 Break out of this dependency by assuming that the path to
1651 the encodings module is ASCII-only. XXX could try wcstombs
1652 instead, if the file system encoding is the locale's
1653 encoding. */
Victor Stinner37296e82010-06-10 13:36:23 +00001654 if (Py_FileSystemDefaultEncoding &&
Victor Stinner59e62db2010-05-15 13:14:32 +00001655 strcmp(encoding, Py_FileSystemDefaultEncoding) == 0 &&
1656 !PyThreadState_GET()->interp->codecs_initialized)
1657 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
1658 PyUnicode_GET_SIZE(unicode),
1659 errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001660
1661 /* Encode via the codec registry */
1662 v = PyCodec_Encode(unicode, encoding, errors);
1663 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001664 return NULL;
1665
1666 /* The normal path */
1667 if (PyBytes_Check(v))
1668 return v;
1669
1670 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001671 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001672 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001673 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001674
1675 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1676 "encoder %s returned bytearray instead of bytes",
1677 encoding);
1678 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001679 Py_DECREF(v);
1680 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001681 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001682
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001683 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
1684 Py_DECREF(v);
1685 return b;
1686 }
1687
1688 PyErr_Format(PyExc_TypeError,
1689 "encoder did not return a bytes object (type=%.400s)",
1690 Py_TYPE(v)->tp_name);
1691 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001692 return NULL;
1693}
1694
1695PyObject *PyUnicode_AsEncodedUnicode(PyObject *unicode,
1696 const char *encoding,
1697 const char *errors)
1698{
1699 PyObject *v;
1700
1701 if (!PyUnicode_Check(unicode)) {
1702 PyErr_BadArgument();
1703 goto onError;
1704 }
1705
1706 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001707 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001708
1709 /* Encode via the codec registry */
1710 v = PyCodec_Encode(unicode, encoding, errors);
1711 if (v == NULL)
1712 goto onError;
1713 if (!PyUnicode_Check(v)) {
1714 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001715 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001716 Py_TYPE(v)->tp_name);
1717 Py_DECREF(v);
1718 goto onError;
1719 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001720 return v;
Tim Petersced69f82003-09-16 20:30:58 +00001721
Benjamin Peterson29060642009-01-31 22:14:21 +00001722 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001723 return NULL;
1724}
1725
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001726PyObject *_PyUnicode_AsDefaultEncodedString(PyObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00001727 const char *errors)
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001728{
1729 PyObject *v = ((PyUnicodeObject *)unicode)->defenc;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001730 if (v)
1731 return v;
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001732 if (errors != NULL)
1733 Py_FatalError("non-NULL encoding in _PyUnicode_AsDefaultEncodedString");
Guido van Rossum98297ee2007-11-06 21:34:58 +00001734 v = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
Guido van Rossum06610092007-08-16 21:02:22 +00001735 PyUnicode_GET_SIZE(unicode),
1736 NULL);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001737 if (!v)
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001738 return NULL;
Guido van Rossume7a0d392007-07-12 07:53:00 +00001739 ((PyUnicodeObject *)unicode)->defenc = v;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001740 return v;
1741}
1742
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001743PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00001744PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001745 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00001746 return PyUnicode_DecodeFSDefaultAndSize(s, size);
1747}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001748
Christian Heimes5894ba72007-11-04 11:43:14 +00001749PyObject*
1750PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
1751{
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001752 /* During the early bootstrapping process, Py_FileSystemDefaultEncoding
1753 can be undefined. If it is case, decode using UTF-8. The following assumes
1754 that Py_FileSystemDefaultEncoding is set to a built-in encoding during the
1755 bootstrapping process where the codecs aren't ready yet.
1756 */
1757 if (Py_FileSystemDefaultEncoding) {
1758#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Christian Heimes5894ba72007-11-04 11:43:14 +00001759 if (strcmp(Py_FileSystemDefaultEncoding, "mbcs") == 0) {
Victor Stinner313a1202010-06-11 23:56:51 +00001760 return PyUnicode_DecodeMBCS(s, size, NULL);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001761 }
1762#elif defined(__APPLE__)
Christian Heimes5894ba72007-11-04 11:43:14 +00001763 if (strcmp(Py_FileSystemDefaultEncoding, "utf-8") == 0) {
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00001764 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001765 }
1766#endif
1767 return PyUnicode_Decode(s, size,
1768 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00001769 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001770 }
1771 else {
Victor Stinnerc39211f2010-09-29 16:35:47 +00001772 /* if you change the default encoding, update also
1773 PyUnicode_EncodeFSDefault() and redecode_filenames() */
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00001774 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001775 }
1776}
1777
Martin v. Löwis011e8422009-05-05 04:43:17 +00001778
1779int
1780PyUnicode_FSConverter(PyObject* arg, void* addr)
1781{
1782 PyObject *output = NULL;
1783 Py_ssize_t size;
1784 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00001785 if (arg == NULL) {
1786 Py_DECREF(*(PyObject**)addr);
1787 return 1;
1788 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00001789 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00001790 output = arg;
1791 Py_INCREF(output);
1792 }
1793 else {
1794 arg = PyUnicode_FromObject(arg);
1795 if (!arg)
1796 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00001797 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00001798 Py_DECREF(arg);
1799 if (!output)
1800 return 0;
1801 if (!PyBytes_Check(output)) {
1802 Py_DECREF(output);
1803 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
1804 return 0;
1805 }
1806 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00001807 size = PyBytes_GET_SIZE(output);
1808 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00001809 if (size != strlen(data)) {
1810 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
1811 Py_DECREF(output);
1812 return 0;
1813 }
1814 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00001815 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00001816}
1817
1818
Victor Stinner47fcb5b2010-08-13 23:59:58 +00001819int
1820PyUnicode_FSDecoder(PyObject* arg, void* addr)
1821{
1822 PyObject *output = NULL;
1823 Py_ssize_t size;
1824 void *data;
1825 if (arg == NULL) {
1826 Py_DECREF(*(PyObject**)addr);
1827 return 1;
1828 }
1829 if (PyUnicode_Check(arg)) {
1830 output = arg;
1831 Py_INCREF(output);
1832 }
1833 else {
1834 arg = PyBytes_FromObject(arg);
1835 if (!arg)
1836 return 0;
1837 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
1838 PyBytes_GET_SIZE(arg));
1839 Py_DECREF(arg);
1840 if (!output)
1841 return 0;
1842 if (!PyUnicode_Check(output)) {
1843 Py_DECREF(output);
1844 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
1845 return 0;
1846 }
1847 }
1848 size = PyUnicode_GET_SIZE(output);
1849 data = PyUnicode_AS_UNICODE(output);
1850 if (size != Py_UNICODE_strlen(data)) {
1851 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
1852 Py_DECREF(output);
1853 return 0;
1854 }
1855 *(PyObject**)addr = output;
1856 return Py_CLEANUP_SUPPORTED;
1857}
1858
1859
Martin v. Löwis5b222132007-06-10 09:51:05 +00001860char*
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001861_PyUnicode_AsStringAndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00001862{
Christian Heimesf3863112007-11-22 07:46:41 +00001863 PyObject *bytes;
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00001864 if (!PyUnicode_Check(unicode)) {
1865 PyErr_BadArgument();
1866 return NULL;
1867 }
Christian Heimesf3863112007-11-22 07:46:41 +00001868 bytes = _PyUnicode_AsDefaultEncodedString(unicode, NULL);
1869 if (bytes == NULL)
Martin v. Löwis5b222132007-06-10 09:51:05 +00001870 return NULL;
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001871 if (psize != NULL)
Christian Heimes72b710a2008-05-26 13:28:38 +00001872 *psize = PyBytes_GET_SIZE(bytes);
1873 return PyBytes_AS_STRING(bytes);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001874}
1875
1876char*
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001877_PyUnicode_AsString(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001878{
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001879 return _PyUnicode_AsStringAndSize(unicode, NULL);
Martin v. Löwis5b222132007-06-10 09:51:05 +00001880}
1881
Guido van Rossumd57fd912000-03-10 22:53:23 +00001882Py_UNICODE *PyUnicode_AsUnicode(PyObject *unicode)
1883{
1884 if (!PyUnicode_Check(unicode)) {
1885 PyErr_BadArgument();
1886 goto onError;
1887 }
1888 return PyUnicode_AS_UNICODE(unicode);
1889
Benjamin Peterson29060642009-01-31 22:14:21 +00001890 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001891 return NULL;
1892}
1893
Martin v. Löwis18e16552006-02-15 17:27:45 +00001894Py_ssize_t PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001895{
1896 if (!PyUnicode_Check(unicode)) {
1897 PyErr_BadArgument();
1898 goto onError;
1899 }
1900 return PyUnicode_GET_SIZE(unicode);
1901
Benjamin Peterson29060642009-01-31 22:14:21 +00001902 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001903 return -1;
1904}
1905
Thomas Wouters78890102000-07-22 19:25:51 +00001906const char *PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00001907{
Victor Stinner42cb4622010-09-01 19:39:01 +00001908 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00001909}
1910
Victor Stinner554f3f02010-06-16 23:33:54 +00001911/* create or adjust a UnicodeDecodeError */
1912static void
1913make_decode_exception(PyObject **exceptionObject,
1914 const char *encoding,
1915 const char *input, Py_ssize_t length,
1916 Py_ssize_t startpos, Py_ssize_t endpos,
1917 const char *reason)
1918{
1919 if (*exceptionObject == NULL) {
1920 *exceptionObject = PyUnicodeDecodeError_Create(
1921 encoding, input, length, startpos, endpos, reason);
1922 }
1923 else {
1924 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
1925 goto onError;
1926 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
1927 goto onError;
1928 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
1929 goto onError;
1930 }
1931 return;
1932
1933onError:
1934 Py_DECREF(*exceptionObject);
1935 *exceptionObject = NULL;
1936}
1937
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001938/* error handling callback helper:
1939 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00001940 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001941 and adjust various state variables.
1942 return 0 on success, -1 on error
1943*/
1944
1945static
1946int unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00001947 const char *encoding, const char *reason,
1948 const char **input, const char **inend, Py_ssize_t *startinpos,
1949 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
1950 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001951{
Benjamin Peterson142957c2008-07-04 19:55:29 +00001952 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001953
1954 PyObject *restuple = NULL;
1955 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001956 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00001957 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001958 Py_ssize_t requiredsize;
1959 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001960 Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00001961 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001962 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001963 int res = -1;
1964
1965 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001966 *errorHandler = PyCodec_LookupError(errors);
1967 if (*errorHandler == NULL)
1968 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001969 }
1970
Victor Stinner554f3f02010-06-16 23:33:54 +00001971 make_decode_exception(exceptionObject,
1972 encoding,
1973 *input, *inend - *input,
1974 *startinpos, *endinpos,
1975 reason);
1976 if (*exceptionObject == NULL)
1977 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001978
1979 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
1980 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001981 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001982 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001983 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00001984 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001985 }
1986 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00001987 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00001988
1989 /* Copy back the bytes variables, which might have been modified by the
1990 callback */
1991 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
1992 if (!inputobj)
1993 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00001994 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001995 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00001996 }
Christian Heimes72b710a2008-05-26 13:28:38 +00001997 *input = PyBytes_AS_STRING(inputobj);
1998 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00001999 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00002000 /* we can DECREF safely, as the exception has another reference,
2001 so the object won't go away. */
2002 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002003
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002004 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00002005 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00002006 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002007 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
2008 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00002009 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002010
2011 /* need more space? (at least enough for what we
2012 have+the replacement+the rest of the string (starting
2013 at the new input position), so we won't have to check space
2014 when there are no errors in the rest of the string) */
2015 repptr = PyUnicode_AS_UNICODE(repunicode);
2016 repsize = PyUnicode_GET_SIZE(repunicode);
2017 requiredsize = *outpos + repsize + insize-newpos;
2018 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002019 if (requiredsize<2*outsize)
2020 requiredsize = 2*outsize;
2021 if (_PyUnicode_Resize(output, requiredsize) < 0)
2022 goto onError;
2023 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002024 }
2025 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002026 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002027 Py_UNICODE_COPY(*outptr, repptr, repsize);
2028 *outptr += repsize;
2029 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002030
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002031 /* we made it! */
2032 res = 0;
2033
Benjamin Peterson29060642009-01-31 22:14:21 +00002034 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002035 Py_XDECREF(restuple);
2036 return res;
2037}
2038
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002039/* --- UTF-7 Codec -------------------------------------------------------- */
2040
Antoine Pitrou244651a2009-05-04 18:56:13 +00002041/* See RFC2152 for details. We encode conservatively and decode liberally. */
2042
2043/* Three simple macros defining base-64. */
2044
2045/* Is c a base-64 character? */
2046
2047#define IS_BASE64(c) \
2048 (((c) >= 'A' && (c) <= 'Z') || \
2049 ((c) >= 'a' && (c) <= 'z') || \
2050 ((c) >= '0' && (c) <= '9') || \
2051 (c) == '+' || (c) == '/')
2052
2053/* given that c is a base-64 character, what is its base-64 value? */
2054
2055#define FROM_BASE64(c) \
2056 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
2057 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
2058 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
2059 (c) == '+' ? 62 : 63)
2060
2061/* What is the base-64 character of the bottom 6 bits of n? */
2062
2063#define TO_BASE64(n) \
2064 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
2065
2066/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
2067 * decoded as itself. We are permissive on decoding; the only ASCII
2068 * byte not decoding to itself is the + which begins a base64
2069 * string. */
2070
2071#define DECODE_DIRECT(c) \
2072 ((c) <= 127 && (c) != '+')
2073
2074/* The UTF-7 encoder treats ASCII characters differently according to
2075 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
2076 * the above). See RFC2152. This array identifies these different
2077 * sets:
2078 * 0 : "Set D"
2079 * alphanumeric and '(),-./:?
2080 * 1 : "Set O"
2081 * !"#$%&*;<=>@[]^_`{|}
2082 * 2 : "whitespace"
2083 * ht nl cr sp
2084 * 3 : special (must be base64 encoded)
2085 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
2086 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002087
Tim Petersced69f82003-09-16 20:30:58 +00002088static
Antoine Pitrou244651a2009-05-04 18:56:13 +00002089char utf7_category[128] = {
2090/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
2091 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
2092/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
2093 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2094/* sp ! " # $ % & ' ( ) * + , - . / */
2095 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
2096/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
2097 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
2098/* @ A B C D E F G H I J K L M N O */
2099 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2100/* P Q R S T U V W X Y Z [ \ ] ^ _ */
2101 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
2102/* ` a b c d e f g h i j k l m n o */
2103 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2104/* p q r s t u v w x y z { | } ~ del */
2105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002106};
2107
Antoine Pitrou244651a2009-05-04 18:56:13 +00002108/* ENCODE_DIRECT: this character should be encoded as itself. The
2109 * answer depends on whether we are encoding set O as itself, and also
2110 * on whether we are encoding whitespace as itself. RFC2152 makes it
2111 * clear that the answers to these questions vary between
2112 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00002113
Antoine Pitrou244651a2009-05-04 18:56:13 +00002114#define ENCODE_DIRECT(c, directO, directWS) \
2115 ((c) < 128 && (c) > 0 && \
2116 ((utf7_category[(c)] == 0) || \
2117 (directWS && (utf7_category[(c)] == 2)) || \
2118 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002119
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002120PyObject *PyUnicode_DecodeUTF7(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002121 Py_ssize_t size,
2122 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002123{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002124 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
2125}
2126
Antoine Pitrou244651a2009-05-04 18:56:13 +00002127/* The decoder. The only state we preserve is our read position,
2128 * i.e. how many characters we have consumed. So if we end in the
2129 * middle of a shift sequence we have to back off the read position
2130 * and the output to the beginning of the sequence, otherwise we lose
2131 * all the shift state (seen bits, number of bits seen, high
2132 * surrogate). */
2133
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002134PyObject *PyUnicode_DecodeUTF7Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002135 Py_ssize_t size,
2136 const char *errors,
2137 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002138{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002139 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002140 Py_ssize_t startinpos;
2141 Py_ssize_t endinpos;
2142 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002143 const char *e;
2144 PyUnicodeObject *unicode;
2145 Py_UNICODE *p;
2146 const char *errmsg = "";
2147 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002148 Py_UNICODE *shiftOutStart;
2149 unsigned int base64bits = 0;
2150 unsigned long base64buffer = 0;
2151 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002152 PyObject *errorHandler = NULL;
2153 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002154
2155 unicode = _PyUnicode_New(size);
2156 if (!unicode)
2157 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002158 if (size == 0) {
2159 if (consumed)
2160 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002161 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002162 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002163
2164 p = unicode->str;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002165 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002166 e = s + size;
2167
2168 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002169 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00002170 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00002171 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002172
Antoine Pitrou244651a2009-05-04 18:56:13 +00002173 if (inShift) { /* in a base-64 section */
2174 if (IS_BASE64(ch)) { /* consume a base-64 character */
2175 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
2176 base64bits += 6;
2177 s++;
2178 if (base64bits >= 16) {
2179 /* we have enough bits for a UTF-16 value */
2180 Py_UNICODE outCh = (Py_UNICODE)
2181 (base64buffer >> (base64bits-16));
2182 base64bits -= 16;
2183 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
2184 if (surrogate) {
2185 /* expecting a second surrogate */
2186 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
2187#ifdef Py_UNICODE_WIDE
2188 *p++ = (((surrogate & 0x3FF)<<10)
2189 | (outCh & 0x3FF)) + 0x10000;
2190#else
2191 *p++ = surrogate;
2192 *p++ = outCh;
2193#endif
2194 surrogate = 0;
2195 }
2196 else {
2197 surrogate = 0;
2198 errmsg = "second surrogate missing";
2199 goto utf7Error;
2200 }
2201 }
2202 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
2203 /* first surrogate */
2204 surrogate = outCh;
2205 }
2206 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
2207 errmsg = "unexpected second surrogate";
2208 goto utf7Error;
2209 }
2210 else {
2211 *p++ = outCh;
2212 }
2213 }
2214 }
2215 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002216 inShift = 0;
2217 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002218 if (surrogate) {
2219 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00002220 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002221 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002222 if (base64bits > 0) { /* left-over bits */
2223 if (base64bits >= 6) {
2224 /* We've seen at least one base-64 character */
2225 errmsg = "partial character in shift sequence";
2226 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002227 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002228 else {
2229 /* Some bits remain; they should be zero */
2230 if (base64buffer != 0) {
2231 errmsg = "non-zero padding bits in shift sequence";
2232 goto utf7Error;
2233 }
2234 }
2235 }
2236 if (ch != '-') {
2237 /* '-' is absorbed; other terminating
2238 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002239 *p++ = ch;
2240 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002241 }
2242 }
2243 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002244 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002245 s++; /* consume '+' */
2246 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002247 s++;
2248 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00002249 }
2250 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002251 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002252 shiftOutStart = p;
2253 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002254 }
2255 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002256 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002257 *p++ = ch;
2258 s++;
2259 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002260 else {
2261 startinpos = s-starts;
2262 s++;
2263 errmsg = "unexpected special character";
2264 goto utf7Error;
2265 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002266 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002267utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002268 outpos = p-PyUnicode_AS_UNICODE(unicode);
2269 endinpos = s-starts;
2270 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00002271 errors, &errorHandler,
2272 "utf7", errmsg,
2273 &starts, &e, &startinpos, &endinpos, &exc, &s,
2274 &unicode, &outpos, &p))
2275 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002276 }
2277
Antoine Pitrou244651a2009-05-04 18:56:13 +00002278 /* end of string */
2279
2280 if (inShift && !consumed) { /* in shift sequence, no more to follow */
2281 /* if we're in an inconsistent state, that's an error */
2282 if (surrogate ||
2283 (base64bits >= 6) ||
2284 (base64bits > 0 && base64buffer != 0)) {
2285 outpos = p-PyUnicode_AS_UNICODE(unicode);
2286 endinpos = size;
2287 if (unicode_decode_call_errorhandler(
2288 errors, &errorHandler,
2289 "utf7", "unterminated shift sequence",
2290 &starts, &e, &startinpos, &endinpos, &exc, &s,
2291 &unicode, &outpos, &p))
2292 goto onError;
2293 if (s < e)
2294 goto restart;
2295 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002296 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002297
2298 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002299 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00002300 if (inShift) {
2301 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002302 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002303 }
2304 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002305 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002306 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002307 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002308
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00002309 if (_PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002310 goto onError;
2311
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002312 Py_XDECREF(errorHandler);
2313 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002314 return (PyObject *)unicode;
2315
Benjamin Peterson29060642009-01-31 22:14:21 +00002316 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002317 Py_XDECREF(errorHandler);
2318 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002319 Py_DECREF(unicode);
2320 return NULL;
2321}
2322
2323
2324PyObject *PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002325 Py_ssize_t size,
Antoine Pitrou244651a2009-05-04 18:56:13 +00002326 int base64SetO,
2327 int base64WhiteSpace,
Benjamin Peterson29060642009-01-31 22:14:21 +00002328 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002329{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002330 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002331 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00002332 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002333 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002334 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002335 unsigned int base64bits = 0;
2336 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002337 char * out;
2338 char * start;
2339
2340 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00002341 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002342
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00002343 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00002344 return PyErr_NoMemory();
2345
Antoine Pitrou244651a2009-05-04 18:56:13 +00002346 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002347 if (v == NULL)
2348 return NULL;
2349
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002350 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002351 for (;i < size; ++i) {
2352 Py_UNICODE ch = s[i];
2353
Antoine Pitrou244651a2009-05-04 18:56:13 +00002354 if (inShift) {
2355 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
2356 /* shifting out */
2357 if (base64bits) { /* output remaining bits */
2358 *out++ = TO_BASE64(base64buffer << (6-base64bits));
2359 base64buffer = 0;
2360 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002361 }
2362 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002363 /* Characters not in the BASE64 set implicitly unshift the sequence
2364 so no '-' is required, except if the character is itself a '-' */
2365 if (IS_BASE64(ch) || ch == '-') {
2366 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002367 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002368 *out++ = (char) ch;
2369 }
2370 else {
2371 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00002372 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002373 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002374 else { /* not in a shift sequence */
2375 if (ch == '+') {
2376 *out++ = '+';
2377 *out++ = '-';
2378 }
2379 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
2380 *out++ = (char) ch;
2381 }
2382 else {
2383 *out++ = '+';
2384 inShift = 1;
2385 goto encode_char;
2386 }
2387 }
2388 continue;
2389encode_char:
2390#ifdef Py_UNICODE_WIDE
2391 if (ch >= 0x10000) {
2392 /* code first surrogate */
2393 base64bits += 16;
2394 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
2395 while (base64bits >= 6) {
2396 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
2397 base64bits -= 6;
2398 }
2399 /* prepare second surrogate */
2400 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
2401 }
2402#endif
2403 base64bits += 16;
2404 base64buffer = (base64buffer << 16) | ch;
2405 while (base64bits >= 6) {
2406 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
2407 base64bits -= 6;
2408 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00002409 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002410 if (base64bits)
2411 *out++= TO_BASE64(base64buffer << (6-base64bits) );
2412 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002413 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002414 if (_PyBytes_Resize(&v, out - start) < 0)
2415 return NULL;
2416 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002417}
2418
Antoine Pitrou244651a2009-05-04 18:56:13 +00002419#undef IS_BASE64
2420#undef FROM_BASE64
2421#undef TO_BASE64
2422#undef DECODE_DIRECT
2423#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002424
Guido van Rossumd57fd912000-03-10 22:53:23 +00002425/* --- UTF-8 Codec -------------------------------------------------------- */
2426
Tim Petersced69f82003-09-16 20:30:58 +00002427static
Guido van Rossumd57fd912000-03-10 22:53:23 +00002428char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00002429 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
2430 illegal prefix. See RFC 3629 for details */
2431 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
2432 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002433 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00002434 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2435 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2436 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2437 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00002438 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
2439 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 +00002440 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2441 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00002442 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
2443 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
2444 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
2445 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
2446 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 +00002447};
2448
Guido van Rossumd57fd912000-03-10 22:53:23 +00002449PyObject *PyUnicode_DecodeUTF8(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002450 Py_ssize_t size,
2451 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002452{
Walter Dörwald69652032004-09-07 20:24:22 +00002453 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
2454}
2455
Antoine Pitrouab868312009-01-10 15:40:25 +00002456/* Mask to check or force alignment of a pointer to C 'long' boundaries */
2457#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
2458
2459/* Mask to quickly check whether a C 'long' contains a
2460 non-ASCII, UTF8-encoded char. */
2461#if (SIZEOF_LONG == 8)
2462# define ASCII_CHAR_MASK 0x8080808080808080L
2463#elif (SIZEOF_LONG == 4)
2464# define ASCII_CHAR_MASK 0x80808080L
2465#else
2466# error C 'long' size should be either 4 or 8!
2467#endif
2468
Walter Dörwald69652032004-09-07 20:24:22 +00002469PyObject *PyUnicode_DecodeUTF8Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002470 Py_ssize_t size,
2471 const char *errors,
2472 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00002473{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002474 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002475 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00002476 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002477 Py_ssize_t startinpos;
2478 Py_ssize_t endinpos;
2479 Py_ssize_t outpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00002480 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002481 PyUnicodeObject *unicode;
2482 Py_UNICODE *p;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002483 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002484 PyObject *errorHandler = NULL;
2485 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002486
2487 /* Note: size will always be longer than the resulting Unicode
2488 character count */
2489 unicode = _PyUnicode_New(size);
2490 if (!unicode)
2491 return NULL;
Walter Dörwald69652032004-09-07 20:24:22 +00002492 if (size == 0) {
2493 if (consumed)
2494 *consumed = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002495 return (PyObject *)unicode;
Walter Dörwald69652032004-09-07 20:24:22 +00002496 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002497
2498 /* Unpack UTF-8 encoded data */
2499 p = unicode->str;
2500 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00002501 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002502
2503 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002504 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002505
2506 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00002507 /* Fast path for runs of ASCII characters. Given that common UTF-8
2508 input will consist of an overwhelming majority of ASCII
2509 characters, we try to optimize for this case by checking
2510 as many characters as a C 'long' can contain.
2511 First, check if we can do an aligned read, as most CPUs have
2512 a penalty for unaligned reads.
2513 */
2514 if (!((size_t) s & LONG_PTR_MASK)) {
2515 /* Help register allocation */
2516 register const char *_s = s;
2517 register Py_UNICODE *_p = p;
2518 while (_s < aligned_end) {
2519 /* Read a whole long at a time (either 4 or 8 bytes),
2520 and do a fast unrolled copy if it only contains ASCII
2521 characters. */
2522 unsigned long data = *(unsigned long *) _s;
2523 if (data & ASCII_CHAR_MASK)
2524 break;
2525 _p[0] = (unsigned char) _s[0];
2526 _p[1] = (unsigned char) _s[1];
2527 _p[2] = (unsigned char) _s[2];
2528 _p[3] = (unsigned char) _s[3];
2529#if (SIZEOF_LONG == 8)
2530 _p[4] = (unsigned char) _s[4];
2531 _p[5] = (unsigned char) _s[5];
2532 _p[6] = (unsigned char) _s[6];
2533 _p[7] = (unsigned char) _s[7];
2534#endif
2535 _s += SIZEOF_LONG;
2536 _p += SIZEOF_LONG;
2537 }
2538 s = _s;
2539 p = _p;
2540 if (s == e)
2541 break;
2542 ch = (unsigned char)*s;
2543 }
2544 }
2545
2546 if (ch < 0x80) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002547 *p++ = (Py_UNICODE)ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002548 s++;
2549 continue;
2550 }
2551
2552 n = utf8_code_length[ch];
2553
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002554 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002555 if (consumed)
2556 break;
2557 else {
2558 errmsg = "unexpected end of data";
2559 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002560 endinpos = startinpos+1;
2561 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
2562 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00002563 goto utf8Error;
2564 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002565 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002566
2567 switch (n) {
2568
2569 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00002570 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002571 startinpos = s-starts;
2572 endinpos = startinpos+1;
2573 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002574
2575 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002576 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00002577 startinpos = s-starts;
2578 endinpos = startinpos+1;
2579 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002580
2581 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002582 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00002583 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002584 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002585 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00002586 goto utf8Error;
2587 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002588 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00002589 assert ((ch > 0x007F) && (ch <= 0x07FF));
2590 *p++ = (Py_UNICODE)ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002591 break;
2592
2593 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00002594 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
2595 will result in surrogates in range d800-dfff. Surrogates are
2596 not valid UTF-8 so they are rejected.
2597 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
2598 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00002599 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00002600 (s[2] & 0xc0) != 0x80 ||
2601 ((unsigned char)s[0] == 0xE0 &&
2602 (unsigned char)s[1] < 0xA0) ||
2603 ((unsigned char)s[0] == 0xED &&
2604 (unsigned char)s[1] > 0x9F)) {
2605 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002606 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002607 endinpos = startinpos + 1;
2608
2609 /* if s[1] first two bits are 1 and 0, then the invalid
2610 continuation byte is s[2], so increment endinpos by 1,
2611 if not, s[1] is invalid and endinpos doesn't need to
2612 be incremented. */
2613 if ((s[1] & 0xC0) == 0x80)
2614 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00002615 goto utf8Error;
2616 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002617 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00002618 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
2619 *p++ = (Py_UNICODE)ch;
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002620 break;
2621
2622 case 4:
2623 if ((s[1] & 0xc0) != 0x80 ||
2624 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00002625 (s[3] & 0xc0) != 0x80 ||
2626 ((unsigned char)s[0] == 0xF0 &&
2627 (unsigned char)s[1] < 0x90) ||
2628 ((unsigned char)s[0] == 0xF4 &&
2629 (unsigned char)s[1] > 0x8F)) {
2630 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002631 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002632 endinpos = startinpos + 1;
2633 if ((s[1] & 0xC0) == 0x80) {
2634 endinpos++;
2635 if ((s[2] & 0xC0) == 0x80)
2636 endinpos++;
2637 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002638 goto utf8Error;
2639 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002640 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00002641 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
2642 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
2643
Fredrik Lundh8f455852001-06-27 18:59:43 +00002644#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00002645 *p++ = (Py_UNICODE)ch;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002646#else
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002647 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00002648
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002649 /* translate from 10000..10FFFF to 0..FFFF */
2650 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00002651
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002652 /* high surrogate = top 10 bits added to D800 */
2653 *p++ = (Py_UNICODE)(0xD800 + (ch >> 10));
Tim Petersced69f82003-09-16 20:30:58 +00002654
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002655 /* low surrogate = bottom 10 bits added to DC00 */
Fredrik Lundh45714e92001-06-26 16:39:36 +00002656 *p++ = (Py_UNICODE)(0xDC00 + (ch & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002657#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00002658 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002659 }
2660 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00002661 continue;
Tim Petersced69f82003-09-16 20:30:58 +00002662
Benjamin Peterson29060642009-01-31 22:14:21 +00002663 utf8Error:
2664 outpos = p-PyUnicode_AS_UNICODE(unicode);
2665 if (unicode_decode_call_errorhandler(
2666 errors, &errorHandler,
2667 "utf8", errmsg,
2668 &starts, &e, &startinpos, &endinpos, &exc, &s,
2669 &unicode, &outpos, &p))
2670 goto onError;
2671 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002672 }
Walter Dörwald69652032004-09-07 20:24:22 +00002673 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00002674 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002675
2676 /* Adjust length */
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00002677 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002678 goto onError;
2679
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002680 Py_XDECREF(errorHandler);
2681 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002682 return (PyObject *)unicode;
2683
Benjamin Peterson29060642009-01-31 22:14:21 +00002684 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002685 Py_XDECREF(errorHandler);
2686 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002687 Py_DECREF(unicode);
2688 return NULL;
2689}
2690
Antoine Pitrouab868312009-01-10 15:40:25 +00002691#undef ASCII_CHAR_MASK
2692
2693
Tim Peters602f7402002-04-27 18:03:26 +00002694/* Allocation strategy: if the string is short, convert into a stack buffer
2695 and allocate exactly as much space needed at the end. Else allocate the
2696 maximum possible needed (4 result bytes per Unicode character), and return
2697 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002698*/
Tim Peters7e3d9612002-04-21 03:26:37 +00002699PyObject *
2700PyUnicode_EncodeUTF8(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002701 Py_ssize_t size,
2702 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002703{
Tim Peters602f7402002-04-27 18:03:26 +00002704#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00002705
Guido van Rossum98297ee2007-11-06 21:34:58 +00002706 Py_ssize_t i; /* index into s of next input byte */
2707 PyObject *result; /* result string object */
2708 char *p; /* next free byte in output buffer */
2709 Py_ssize_t nallocated; /* number of result bytes allocated */
2710 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00002711 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002712 PyObject *errorHandler = NULL;
2713 PyObject *exc = NULL;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00002714
Tim Peters602f7402002-04-27 18:03:26 +00002715 assert(s != NULL);
2716 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002717
Tim Peters602f7402002-04-27 18:03:26 +00002718 if (size <= MAX_SHORT_UNICHARS) {
2719 /* Write into the stack buffer; nallocated can't overflow.
2720 * At the end, we'll allocate exactly as much heap space as it
2721 * turns out we need.
2722 */
2723 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002724 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00002725 p = stackbuf;
2726 }
2727 else {
2728 /* Overallocate on the heap, and give the excess back at the end. */
2729 nallocated = size * 4;
2730 if (nallocated / 4 != size) /* overflow! */
2731 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00002732 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002733 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00002734 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00002735 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00002736 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002737
Tim Peters602f7402002-04-27 18:03:26 +00002738 for (i = 0; i < size;) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002739 Py_UCS4 ch = s[i++];
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002740
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002741 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00002742 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002743 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002744
Guido van Rossumd57fd912000-03-10 22:53:23 +00002745 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00002746 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00002747 *p++ = (char)(0xc0 | (ch >> 6));
2748 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00002749 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002750#ifndef Py_UNICODE_WIDE
Victor Stinner31be90b2010-04-22 19:38:16 +00002751 /* Special case: check for high and low surrogate */
2752 if (ch <= 0xDBFF && i != size && 0xDC00 <= s[i] && s[i] <= 0xDFFF) {
2753 Py_UCS4 ch2 = s[i];
2754 /* Combine the two surrogates to form a UCS4 value */
2755 ch = ((ch - 0xD800) << 10 | (ch2 - 0xDC00)) + 0x10000;
2756 i++;
2757
2758 /* Encode UCS4 Unicode ordinals */
2759 *p++ = (char)(0xf0 | (ch >> 18));
2760 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
Tim Peters602f7402002-04-27 18:03:26 +00002761 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2762 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00002763 } else {
Victor Stinner445a6232010-04-22 20:01:57 +00002764#endif
Victor Stinner31be90b2010-04-22 19:38:16 +00002765 Py_ssize_t newpos;
2766 PyObject *rep;
2767 Py_ssize_t repsize, k;
2768 rep = unicode_encode_call_errorhandler
2769 (errors, &errorHandler, "utf-8", "surrogates not allowed",
2770 s, size, &exc, i-1, i, &newpos);
2771 if (!rep)
2772 goto error;
2773
2774 if (PyBytes_Check(rep))
2775 repsize = PyBytes_GET_SIZE(rep);
2776 else
2777 repsize = PyUnicode_GET_SIZE(rep);
2778
2779 if (repsize > 4) {
2780 Py_ssize_t offset;
2781
2782 if (result == NULL)
2783 offset = p - stackbuf;
2784 else
2785 offset = p - PyBytes_AS_STRING(result);
2786
2787 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
2788 /* integer overflow */
2789 PyErr_NoMemory();
2790 goto error;
2791 }
2792 nallocated += repsize - 4;
2793 if (result != NULL) {
2794 if (_PyBytes_Resize(&result, nallocated) < 0)
2795 goto error;
2796 } else {
2797 result = PyBytes_FromStringAndSize(NULL, nallocated);
2798 if (result == NULL)
2799 goto error;
2800 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
2801 }
2802 p = PyBytes_AS_STRING(result) + offset;
2803 }
2804
2805 if (PyBytes_Check(rep)) {
2806 char *prep = PyBytes_AS_STRING(rep);
2807 for(k = repsize; k > 0; k--)
2808 *p++ = *prep++;
2809 } else /* rep is unicode */ {
2810 Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
2811 Py_UNICODE c;
2812
2813 for(k=0; k<repsize; k++) {
2814 c = prep[k];
2815 if (0x80 <= c) {
2816 raise_encode_exception(&exc, "utf-8", s, size,
2817 i-1, i, "surrogates not allowed");
2818 goto error;
2819 }
2820 *p++ = (char)prep[k];
2821 }
2822 }
2823 Py_DECREF(rep);
Victor Stinner445a6232010-04-22 20:01:57 +00002824#ifndef Py_UNICODE_WIDE
Victor Stinner31be90b2010-04-22 19:38:16 +00002825 }
Victor Stinner445a6232010-04-22 20:01:57 +00002826#endif
Victor Stinner31be90b2010-04-22 19:38:16 +00002827 } else if (ch < 0x10000) {
2828 *p++ = (char)(0xe0 | (ch >> 12));
2829 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2830 *p++ = (char)(0x80 | (ch & 0x3f));
2831 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00002832 /* Encode UCS4 Unicode ordinals */
2833 *p++ = (char)(0xf0 | (ch >> 18));
2834 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
2835 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2836 *p++ = (char)(0x80 | (ch & 0x3f));
2837 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002838 }
Tim Peters0eca65c2002-04-21 17:28:06 +00002839
Guido van Rossum98297ee2007-11-06 21:34:58 +00002840 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00002841 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002842 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00002843 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00002844 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00002845 }
2846 else {
Christian Heimesf3863112007-11-22 07:46:41 +00002847 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00002848 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00002849 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00002850 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00002851 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002852 Py_XDECREF(errorHandler);
2853 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002854 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002855 error:
2856 Py_XDECREF(errorHandler);
2857 Py_XDECREF(exc);
2858 Py_XDECREF(result);
2859 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002860
Tim Peters602f7402002-04-27 18:03:26 +00002861#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00002862}
2863
Guido van Rossumd57fd912000-03-10 22:53:23 +00002864PyObject *PyUnicode_AsUTF8String(PyObject *unicode)
2865{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002866 if (!PyUnicode_Check(unicode)) {
2867 PyErr_BadArgument();
2868 return NULL;
2869 }
Barry Warsaw2dd4abf2000-08-18 06:58:15 +00002870 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00002871 PyUnicode_GET_SIZE(unicode),
2872 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002873}
2874
Walter Dörwald41980ca2007-08-16 21:55:45 +00002875/* --- UTF-32 Codec ------------------------------------------------------- */
2876
2877PyObject *
2878PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002879 Py_ssize_t size,
2880 const char *errors,
2881 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00002882{
2883 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
2884}
2885
2886PyObject *
2887PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002888 Py_ssize_t size,
2889 const char *errors,
2890 int *byteorder,
2891 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00002892{
2893 const char *starts = s;
2894 Py_ssize_t startinpos;
2895 Py_ssize_t endinpos;
2896 Py_ssize_t outpos;
2897 PyUnicodeObject *unicode;
2898 Py_UNICODE *p;
2899#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00002900 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00002901 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002902#else
2903 const int pairs = 0;
2904#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00002905 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002906 int bo = 0; /* assume native ordering by default */
2907 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00002908 /* Offsets from q for retrieving bytes in the right order. */
2909#ifdef BYTEORDER_IS_LITTLE_ENDIAN
2910 int iorder[] = {0, 1, 2, 3};
2911#else
2912 int iorder[] = {3, 2, 1, 0};
2913#endif
2914 PyObject *errorHandler = NULL;
2915 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00002916
Walter Dörwald41980ca2007-08-16 21:55:45 +00002917 q = (unsigned char *)s;
2918 e = q + size;
2919
2920 if (byteorder)
2921 bo = *byteorder;
2922
2923 /* Check for BOM marks (U+FEFF) in the input and adjust current
2924 byte order setting accordingly. In native mode, the leading BOM
2925 mark is skipped, in all other modes, it is copied to the output
2926 stream as-is (giving a ZWNBSP character). */
2927 if (bo == 0) {
2928 if (size >= 4) {
2929 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00002930 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00002931#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00002932 if (bom == 0x0000FEFF) {
2933 q += 4;
2934 bo = -1;
2935 }
2936 else if (bom == 0xFFFE0000) {
2937 q += 4;
2938 bo = 1;
2939 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00002940#else
Benjamin Peterson29060642009-01-31 22:14:21 +00002941 if (bom == 0x0000FEFF) {
2942 q += 4;
2943 bo = 1;
2944 }
2945 else if (bom == 0xFFFE0000) {
2946 q += 4;
2947 bo = -1;
2948 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00002949#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00002950 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00002951 }
2952
2953 if (bo == -1) {
2954 /* force LE */
2955 iorder[0] = 0;
2956 iorder[1] = 1;
2957 iorder[2] = 2;
2958 iorder[3] = 3;
2959 }
2960 else if (bo == 1) {
2961 /* force BE */
2962 iorder[0] = 3;
2963 iorder[1] = 2;
2964 iorder[2] = 1;
2965 iorder[3] = 0;
2966 }
2967
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00002968 /* On narrow builds we split characters outside the BMP into two
2969 codepoints => count how much extra space we need. */
2970#ifndef Py_UNICODE_WIDE
2971 for (qq = q; qq < e; qq += 4)
2972 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
2973 pairs++;
2974#endif
2975
2976 /* This might be one to much, because of a BOM */
2977 unicode = _PyUnicode_New((size+3)/4+pairs);
2978 if (!unicode)
2979 return NULL;
2980 if (size == 0)
2981 return (PyObject *)unicode;
2982
2983 /* Unpack UTF-32 encoded data */
2984 p = unicode->str;
2985
Walter Dörwald41980ca2007-08-16 21:55:45 +00002986 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002987 Py_UCS4 ch;
2988 /* remaining bytes at the end? (size should be divisible by 4) */
2989 if (e-q<4) {
2990 if (consumed)
2991 break;
2992 errmsg = "truncated data";
2993 startinpos = ((const char *)q)-starts;
2994 endinpos = ((const char *)e)-starts;
2995 goto utf32Error;
2996 /* The remaining input chars are ignored if the callback
2997 chooses to skip the input */
2998 }
2999 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
3000 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00003001
Benjamin Peterson29060642009-01-31 22:14:21 +00003002 if (ch >= 0x110000)
3003 {
3004 errmsg = "codepoint not in range(0x110000)";
3005 startinpos = ((const char *)q)-starts;
3006 endinpos = startinpos+4;
3007 goto utf32Error;
3008 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003009#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003010 if (ch >= 0x10000)
3011 {
3012 *p++ = 0xD800 | ((ch-0x10000) >> 10);
3013 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
3014 }
3015 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00003016#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003017 *p++ = ch;
3018 q += 4;
3019 continue;
3020 utf32Error:
3021 outpos = p-PyUnicode_AS_UNICODE(unicode);
3022 if (unicode_decode_call_errorhandler(
3023 errors, &errorHandler,
3024 "utf32", errmsg,
3025 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
3026 &unicode, &outpos, &p))
3027 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003028 }
3029
3030 if (byteorder)
3031 *byteorder = bo;
3032
3033 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00003034 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003035
3036 /* Adjust length */
3037 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
3038 goto onError;
3039
3040 Py_XDECREF(errorHandler);
3041 Py_XDECREF(exc);
3042 return (PyObject *)unicode;
3043
Benjamin Peterson29060642009-01-31 22:14:21 +00003044 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00003045 Py_DECREF(unicode);
3046 Py_XDECREF(errorHandler);
3047 Py_XDECREF(exc);
3048 return NULL;
3049}
3050
3051PyObject *
3052PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003053 Py_ssize_t size,
3054 const char *errors,
3055 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00003056{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003057 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003058 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003059 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003060#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003061 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003062#else
3063 const int pairs = 0;
3064#endif
3065 /* Offsets from p for storing byte pairs in the right order. */
3066#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3067 int iorder[] = {0, 1, 2, 3};
3068#else
3069 int iorder[] = {3, 2, 1, 0};
3070#endif
3071
Benjamin Peterson29060642009-01-31 22:14:21 +00003072#define STORECHAR(CH) \
3073 do { \
3074 p[iorder[3]] = ((CH) >> 24) & 0xff; \
3075 p[iorder[2]] = ((CH) >> 16) & 0xff; \
3076 p[iorder[1]] = ((CH) >> 8) & 0xff; \
3077 p[iorder[0]] = (CH) & 0xff; \
3078 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00003079 } while(0)
3080
3081 /* In narrow builds we can output surrogate pairs as one codepoint,
3082 so we need less space. */
3083#ifndef Py_UNICODE_WIDE
3084 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00003085 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
3086 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
3087 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003088#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003089 nsize = (size - pairs + (byteorder == 0));
3090 bytesize = nsize * 4;
3091 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003092 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003093 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003094 if (v == NULL)
3095 return NULL;
3096
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003097 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003098 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003099 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003100 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00003101 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003102
3103 if (byteorder == -1) {
3104 /* force LE */
3105 iorder[0] = 0;
3106 iorder[1] = 1;
3107 iorder[2] = 2;
3108 iorder[3] = 3;
3109 }
3110 else if (byteorder == 1) {
3111 /* force BE */
3112 iorder[0] = 3;
3113 iorder[1] = 2;
3114 iorder[2] = 1;
3115 iorder[3] = 0;
3116 }
3117
3118 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003119 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003120#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003121 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
3122 Py_UCS4 ch2 = *s;
3123 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
3124 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
3125 s++;
3126 size--;
3127 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00003128 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00003129#endif
3130 STORECHAR(ch);
3131 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003132
3133 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003134 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00003135#undef STORECHAR
3136}
3137
3138PyObject *PyUnicode_AsUTF32String(PyObject *unicode)
3139{
3140 if (!PyUnicode_Check(unicode)) {
3141 PyErr_BadArgument();
3142 return NULL;
3143 }
3144 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003145 PyUnicode_GET_SIZE(unicode),
3146 NULL,
3147 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003148}
3149
Guido van Rossumd57fd912000-03-10 22:53:23 +00003150/* --- UTF-16 Codec ------------------------------------------------------- */
3151
Tim Peters772747b2001-08-09 22:21:55 +00003152PyObject *
3153PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003154 Py_ssize_t size,
3155 const char *errors,
3156 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003157{
Walter Dörwald69652032004-09-07 20:24:22 +00003158 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
3159}
3160
Antoine Pitrouab868312009-01-10 15:40:25 +00003161/* Two masks for fast checking of whether a C 'long' may contain
3162 UTF16-encoded surrogate characters. This is an efficient heuristic,
3163 assuming that non-surrogate characters with a code point >= 0x8000 are
3164 rare in most input.
3165 FAST_CHAR_MASK is used when the input is in native byte ordering,
3166 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00003167*/
Antoine Pitrouab868312009-01-10 15:40:25 +00003168#if (SIZEOF_LONG == 8)
3169# define FAST_CHAR_MASK 0x8000800080008000L
3170# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
3171#elif (SIZEOF_LONG == 4)
3172# define FAST_CHAR_MASK 0x80008000L
3173# define SWAPPED_FAST_CHAR_MASK 0x00800080L
3174#else
3175# error C 'long' size should be either 4 or 8!
3176#endif
3177
Walter Dörwald69652032004-09-07 20:24:22 +00003178PyObject *
3179PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003180 Py_ssize_t size,
3181 const char *errors,
3182 int *byteorder,
3183 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00003184{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003185 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003186 Py_ssize_t startinpos;
3187 Py_ssize_t endinpos;
3188 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003189 PyUnicodeObject *unicode;
3190 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00003191 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00003192 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00003193 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003194 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00003195 /* Offsets from q for retrieving byte pairs in the right order. */
3196#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3197 int ihi = 1, ilo = 0;
3198#else
3199 int ihi = 0, ilo = 1;
3200#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003201 PyObject *errorHandler = NULL;
3202 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003203
3204 /* Note: size will always be longer than the resulting Unicode
3205 character count */
3206 unicode = _PyUnicode_New(size);
3207 if (!unicode)
3208 return NULL;
3209 if (size == 0)
3210 return (PyObject *)unicode;
3211
3212 /* Unpack UTF-16 encoded data */
3213 p = unicode->str;
Tim Peters772747b2001-08-09 22:21:55 +00003214 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00003215 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003216
3217 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00003218 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003219
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003220 /* Check for BOM marks (U+FEFF) in the input and adjust current
3221 byte order setting accordingly. In native mode, the leading BOM
3222 mark is skipped, in all other modes, it is copied to the output
3223 stream as-is (giving a ZWNBSP character). */
3224 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00003225 if (size >= 2) {
3226 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003227#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00003228 if (bom == 0xFEFF) {
3229 q += 2;
3230 bo = -1;
3231 }
3232 else if (bom == 0xFFFE) {
3233 q += 2;
3234 bo = 1;
3235 }
Tim Petersced69f82003-09-16 20:30:58 +00003236#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003237 if (bom == 0xFEFF) {
3238 q += 2;
3239 bo = 1;
3240 }
3241 else if (bom == 0xFFFE) {
3242 q += 2;
3243 bo = -1;
3244 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003245#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003246 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003247 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003248
Tim Peters772747b2001-08-09 22:21:55 +00003249 if (bo == -1) {
3250 /* force LE */
3251 ihi = 1;
3252 ilo = 0;
3253 }
3254 else if (bo == 1) {
3255 /* force BE */
3256 ihi = 0;
3257 ilo = 1;
3258 }
Antoine Pitrouab868312009-01-10 15:40:25 +00003259#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3260 native_ordering = ilo < ihi;
3261#else
3262 native_ordering = ilo > ihi;
3263#endif
Tim Peters772747b2001-08-09 22:21:55 +00003264
Antoine Pitrouab868312009-01-10 15:40:25 +00003265 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00003266 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003267 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00003268 /* First check for possible aligned read of a C 'long'. Unaligned
3269 reads are more expensive, better to defer to another iteration. */
3270 if (!((size_t) q & LONG_PTR_MASK)) {
3271 /* Fast path for runs of non-surrogate chars. */
3272 register const unsigned char *_q = q;
3273 Py_UNICODE *_p = p;
3274 if (native_ordering) {
3275 /* Native ordering is simple: as long as the input cannot
3276 possibly contain a surrogate char, do an unrolled copy
3277 of several 16-bit code points to the target object.
3278 The non-surrogate check is done on several input bytes
3279 at a time (as many as a C 'long' can contain). */
3280 while (_q < aligned_end) {
3281 unsigned long data = * (unsigned long *) _q;
3282 if (data & FAST_CHAR_MASK)
3283 break;
3284 _p[0] = ((unsigned short *) _q)[0];
3285 _p[1] = ((unsigned short *) _q)[1];
3286#if (SIZEOF_LONG == 8)
3287 _p[2] = ((unsigned short *) _q)[2];
3288 _p[3] = ((unsigned short *) _q)[3];
3289#endif
3290 _q += SIZEOF_LONG;
3291 _p += SIZEOF_LONG / 2;
3292 }
3293 }
3294 else {
3295 /* Byteswapped ordering is similar, but we must decompose
3296 the copy bytewise, and take care of zero'ing out the
3297 upper bytes if the target object is in 32-bit units
3298 (that is, in UCS-4 builds). */
3299 while (_q < aligned_end) {
3300 unsigned long data = * (unsigned long *) _q;
3301 if (data & SWAPPED_FAST_CHAR_MASK)
3302 break;
3303 /* Zero upper bytes in UCS-4 builds */
3304#if (Py_UNICODE_SIZE > 2)
3305 _p[0] = 0;
3306 _p[1] = 0;
3307#if (SIZEOF_LONG == 8)
3308 _p[2] = 0;
3309 _p[3] = 0;
3310#endif
3311#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00003312 /* Issue #4916; UCS-4 builds on big endian machines must
3313 fill the two last bytes of each 4-byte unit. */
3314#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
3315# define OFF 2
3316#else
3317# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00003318#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00003319 ((unsigned char *) _p)[OFF + 1] = _q[0];
3320 ((unsigned char *) _p)[OFF + 0] = _q[1];
3321 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
3322 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
3323#if (SIZEOF_LONG == 8)
3324 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
3325 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
3326 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
3327 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
3328#endif
3329#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00003330 _q += SIZEOF_LONG;
3331 _p += SIZEOF_LONG / 2;
3332 }
3333 }
3334 p = _p;
3335 q = _q;
3336 if (q >= e)
3337 break;
3338 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003339 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003340
Benjamin Peterson14339b62009-01-31 16:36:08 +00003341 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00003342
3343 if (ch < 0xD800 || ch > 0xDFFF) {
3344 *p++ = ch;
3345 continue;
3346 }
3347
3348 /* UTF-16 code pair: */
3349 if (q > e) {
3350 errmsg = "unexpected end of data";
3351 startinpos = (((const char *)q) - 2) - starts;
3352 endinpos = ((const char *)e) + 1 - starts;
3353 goto utf16Error;
3354 }
3355 if (0xD800 <= ch && ch <= 0xDBFF) {
3356 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
3357 q += 2;
3358 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00003359#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003360 *p++ = ch;
3361 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003362#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003363 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003364#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003365 continue;
3366 }
3367 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003368 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00003369 startinpos = (((const char *)q)-4)-starts;
3370 endinpos = startinpos+2;
3371 goto utf16Error;
3372 }
3373
Benjamin Peterson14339b62009-01-31 16:36:08 +00003374 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003375 errmsg = "illegal encoding";
3376 startinpos = (((const char *)q)-2)-starts;
3377 endinpos = startinpos+2;
3378 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003379
Benjamin Peterson29060642009-01-31 22:14:21 +00003380 utf16Error:
3381 outpos = p - PyUnicode_AS_UNICODE(unicode);
3382 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00003383 errors,
3384 &errorHandler,
3385 "utf16", errmsg,
3386 &starts,
3387 (const char **)&e,
3388 &startinpos,
3389 &endinpos,
3390 &exc,
3391 (const char **)&q,
3392 &unicode,
3393 &outpos,
3394 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00003395 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003396 }
Antoine Pitrouab868312009-01-10 15:40:25 +00003397 /* remaining byte at the end? (size should be even) */
3398 if (e == q) {
3399 if (!consumed) {
3400 errmsg = "truncated data";
3401 startinpos = ((const char *)q) - starts;
3402 endinpos = ((const char *)e) + 1 - starts;
3403 outpos = p - PyUnicode_AS_UNICODE(unicode);
3404 if (unicode_decode_call_errorhandler(
3405 errors,
3406 &errorHandler,
3407 "utf16", errmsg,
3408 &starts,
3409 (const char **)&e,
3410 &startinpos,
3411 &endinpos,
3412 &exc,
3413 (const char **)&q,
3414 &unicode,
3415 &outpos,
3416 &p))
3417 goto onError;
3418 /* The remaining input chars are ignored if the callback
3419 chooses to skip the input */
3420 }
3421 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003422
3423 if (byteorder)
3424 *byteorder = bo;
3425
Walter Dörwald69652032004-09-07 20:24:22 +00003426 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00003427 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00003428
Guido van Rossumd57fd912000-03-10 22:53:23 +00003429 /* Adjust length */
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00003430 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003431 goto onError;
3432
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003433 Py_XDECREF(errorHandler);
3434 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003435 return (PyObject *)unicode;
3436
Benjamin Peterson29060642009-01-31 22:14:21 +00003437 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003438 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003439 Py_XDECREF(errorHandler);
3440 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003441 return NULL;
3442}
3443
Antoine Pitrouab868312009-01-10 15:40:25 +00003444#undef FAST_CHAR_MASK
3445#undef SWAPPED_FAST_CHAR_MASK
3446
Tim Peters772747b2001-08-09 22:21:55 +00003447PyObject *
3448PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003449 Py_ssize_t size,
3450 const char *errors,
3451 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003452{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003453 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00003454 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003455 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003456#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003457 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003458#else
3459 const int pairs = 0;
3460#endif
Tim Peters772747b2001-08-09 22:21:55 +00003461 /* Offsets from p for storing byte pairs in the right order. */
3462#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3463 int ihi = 1, ilo = 0;
3464#else
3465 int ihi = 0, ilo = 1;
3466#endif
3467
Benjamin Peterson29060642009-01-31 22:14:21 +00003468#define STORECHAR(CH) \
3469 do { \
3470 p[ihi] = ((CH) >> 8) & 0xff; \
3471 p[ilo] = (CH) & 0xff; \
3472 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00003473 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003474
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003475#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003476 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00003477 if (s[i] >= 0x10000)
3478 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003479#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003480 /* 2 * (size + pairs + (byteorder == 0)) */
3481 if (size > PY_SSIZE_T_MAX ||
3482 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00003483 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003484 nsize = size + pairs + (byteorder == 0);
3485 bytesize = nsize * 2;
3486 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003487 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003488 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003489 if (v == NULL)
3490 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003491
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003492 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003493 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003494 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00003495 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00003496 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00003497
3498 if (byteorder == -1) {
3499 /* force LE */
3500 ihi = 1;
3501 ilo = 0;
3502 }
3503 else if (byteorder == 1) {
3504 /* force BE */
3505 ihi = 0;
3506 ilo = 1;
3507 }
3508
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003509 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003510 Py_UNICODE ch = *s++;
3511 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003512#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003513 if (ch >= 0x10000) {
3514 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
3515 ch = 0xD800 | ((ch-0x10000) >> 10);
3516 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003517#endif
Tim Peters772747b2001-08-09 22:21:55 +00003518 STORECHAR(ch);
3519 if (ch2)
3520 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003521 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003522
3523 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003524 return v;
Tim Peters772747b2001-08-09 22:21:55 +00003525#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00003526}
3527
3528PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
3529{
3530 if (!PyUnicode_Check(unicode)) {
3531 PyErr_BadArgument();
3532 return NULL;
3533 }
3534 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003535 PyUnicode_GET_SIZE(unicode),
3536 NULL,
3537 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003538}
3539
3540/* --- Unicode Escape Codec ----------------------------------------------- */
3541
Fredrik Lundh06d12682001-01-24 07:59:11 +00003542static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00003543
Guido van Rossumd57fd912000-03-10 22:53:23 +00003544PyObject *PyUnicode_DecodeUnicodeEscape(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003545 Py_ssize_t size,
3546 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003547{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003548 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003549 Py_ssize_t startinpos;
3550 Py_ssize_t endinpos;
3551 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003552 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003553 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003554 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003555 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003556 char* message;
3557 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003558 PyObject *errorHandler = NULL;
3559 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003560
Guido van Rossumd57fd912000-03-10 22:53:23 +00003561 /* Escaped strings will always be longer than the resulting
3562 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003563 length after conversion to the true value.
3564 (but if the error callback returns a long replacement string
3565 we'll have to allocate more space) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003566 v = _PyUnicode_New(size);
3567 if (v == NULL)
3568 goto onError;
3569 if (size == 0)
3570 return (PyObject *)v;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003571
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003572 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003573 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003574
Guido van Rossumd57fd912000-03-10 22:53:23 +00003575 while (s < end) {
3576 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00003577 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003578 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003579
3580 /* Non-escape characters are interpreted as Unicode ordinals */
3581 if (*s != '\\') {
Fredrik Lundhccc74732001-02-18 22:13:49 +00003582 *p++ = (unsigned char) *s++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003583 continue;
3584 }
3585
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003586 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003587 /* \ - Escapes */
3588 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003589 c = *s++;
3590 if (s > end)
3591 c = '\0'; /* Invalid after \ */
3592 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003593
Benjamin Peterson29060642009-01-31 22:14:21 +00003594 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003595 case '\n': break;
3596 case '\\': *p++ = '\\'; break;
3597 case '\'': *p++ = '\''; break;
3598 case '\"': *p++ = '\"'; break;
3599 case 'b': *p++ = '\b'; break;
3600 case 'f': *p++ = '\014'; break; /* FF */
3601 case 't': *p++ = '\t'; break;
3602 case 'n': *p++ = '\n'; break;
3603 case 'r': *p++ = '\r'; break;
3604 case 'v': *p++ = '\013'; break; /* VT */
3605 case 'a': *p++ = '\007'; break; /* BEL, not classic C */
3606
Benjamin Peterson29060642009-01-31 22:14:21 +00003607 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003608 case '0': case '1': case '2': case '3':
3609 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003610 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003611 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003612 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003613 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003614 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00003615 }
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003616 *p++ = x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003617 break;
3618
Benjamin Peterson29060642009-01-31 22:14:21 +00003619 /* hex escapes */
3620 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003621 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003622 digits = 2;
3623 message = "truncated \\xXX escape";
3624 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003625
Benjamin Peterson29060642009-01-31 22:14:21 +00003626 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003627 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003628 digits = 4;
3629 message = "truncated \\uXXXX escape";
3630 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003631
Benjamin Peterson29060642009-01-31 22:14:21 +00003632 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00003633 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003634 digits = 8;
3635 message = "truncated \\UXXXXXXXX escape";
3636 hexescape:
3637 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003638 outpos = p-PyUnicode_AS_UNICODE(v);
3639 if (s+digits>end) {
3640 endinpos = size;
3641 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003642 errors, &errorHandler,
3643 "unicodeescape", "end of string in escape sequence",
3644 &starts, &end, &startinpos, &endinpos, &exc, &s,
3645 &v, &outpos, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003646 goto onError;
3647 goto nextByte;
3648 }
3649 for (i = 0; i < digits; ++i) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00003650 c = (unsigned char) s[i];
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003651 if (!ISXDIGIT(c)) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003652 endinpos = (s+i+1)-starts;
3653 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003654 errors, &errorHandler,
3655 "unicodeescape", message,
3656 &starts, &end, &startinpos, &endinpos, &exc, &s,
3657 &v, &outpos, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00003658 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003659 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00003660 }
3661 chr = (chr<<4) & ~0xF;
3662 if (c >= '0' && c <= '9')
3663 chr += c - '0';
3664 else if (c >= 'a' && c <= 'f')
3665 chr += 10 + c - 'a';
3666 else
3667 chr += 10 + c - 'A';
3668 }
3669 s += i;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00003670 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003671 /* _decoding_error will have already written into the
3672 target buffer. */
3673 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003674 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00003675 /* when we get here, chr is a 32-bit unicode character */
3676 if (chr <= 0xffff)
3677 /* UCS-2 character */
3678 *p++ = (Py_UNICODE) chr;
3679 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00003680 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00003681 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00003682#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003683 *p++ = chr;
3684#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00003685 chr -= 0x10000L;
3686 *p++ = 0xD800 + (Py_UNICODE) (chr >> 10);
Fredrik Lundh45714e92001-06-26 16:39:36 +00003687 *p++ = 0xDC00 + (Py_UNICODE) (chr & 0x03FF);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003688#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00003689 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003690 endinpos = s-starts;
3691 outpos = p-PyUnicode_AS_UNICODE(v);
3692 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003693 errors, &errorHandler,
3694 "unicodeescape", "illegal Unicode character",
3695 &starts, &end, &startinpos, &endinpos, &exc, &s,
3696 &v, &outpos, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00003697 goto onError;
3698 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00003699 break;
3700
Benjamin Peterson29060642009-01-31 22:14:21 +00003701 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00003702 case 'N':
3703 message = "malformed \\N character escape";
3704 if (ucnhash_CAPI == NULL) {
3705 /* load the unicode data module */
Benjamin Petersonb173f782009-05-05 22:31:58 +00003706 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00003707 if (ucnhash_CAPI == NULL)
3708 goto ucnhashError;
3709 }
3710 if (*s == '{') {
3711 const char *start = s+1;
3712 /* look for the closing brace */
3713 while (*s != '}' && s < end)
3714 s++;
3715 if (s > start && s < end && *s == '}') {
3716 /* found a name. look it up in the unicode database */
3717 message = "unknown Unicode character name";
3718 s++;
Martin v. Löwis480f1bb2006-03-09 23:38:20 +00003719 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1), &chr))
Fredrik Lundhccc74732001-02-18 22:13:49 +00003720 goto store;
3721 }
3722 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003723 endinpos = s-starts;
3724 outpos = p-PyUnicode_AS_UNICODE(v);
3725 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003726 errors, &errorHandler,
3727 "unicodeescape", message,
3728 &starts, &end, &startinpos, &endinpos, &exc, &s,
3729 &v, &outpos, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00003730 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003731 break;
3732
3733 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00003734 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003735 message = "\\ at end of string";
3736 s--;
3737 endinpos = s-starts;
3738 outpos = p-PyUnicode_AS_UNICODE(v);
3739 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003740 errors, &errorHandler,
3741 "unicodeescape", message,
3742 &starts, &end, &startinpos, &endinpos, &exc, &s,
3743 &v, &outpos, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00003744 goto onError;
3745 }
3746 else {
3747 *p++ = '\\';
3748 *p++ = (unsigned char)s[-1];
3749 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00003750 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003751 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003752 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003753 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003754 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003755 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003756 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00003757 Py_XDECREF(errorHandler);
3758 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003759 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00003760
Benjamin Peterson29060642009-01-31 22:14:21 +00003761 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00003762 PyErr_SetString(
3763 PyExc_UnicodeError,
3764 "\\N escapes not supported (can't load unicodedata module)"
3765 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003766 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003767 Py_XDECREF(errorHandler);
3768 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00003769 return NULL;
3770
Benjamin Peterson29060642009-01-31 22:14:21 +00003771 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003772 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003773 Py_XDECREF(errorHandler);
3774 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003775 return NULL;
3776}
3777
3778/* Return a Unicode-Escape string version of the Unicode object.
3779
3780 If quotes is true, the string is enclosed in u"" or u'' quotes as
3781 appropriate.
3782
3783*/
3784
Thomas Wouters477c8d52006-05-27 19:21:47 +00003785Py_LOCAL_INLINE(const Py_UNICODE *) findchar(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003786 Py_ssize_t size,
3787 Py_UNICODE ch)
Thomas Wouters477c8d52006-05-27 19:21:47 +00003788{
3789 /* like wcschr, but doesn't stop at NULL characters */
3790
3791 while (size-- > 0) {
3792 if (*s == ch)
3793 return s;
3794 s++;
3795 }
3796
3797 return NULL;
3798}
Barry Warsaw51ac5802000-03-20 16:36:48 +00003799
Walter Dörwald79e913e2007-05-12 11:08:06 +00003800static const char *hexdigits = "0123456789abcdef";
3801
3802PyObject *PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003803 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003804{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003805 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003806 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003807
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003808#ifdef Py_UNICODE_WIDE
3809 const Py_ssize_t expandsize = 10;
3810#else
3811 const Py_ssize_t expandsize = 6;
3812#endif
3813
Thomas Wouters89f507f2006-12-13 04:49:30 +00003814 /* XXX(nnorwitz): rather than over-allocating, it would be
3815 better to choose a different scheme. Perhaps scan the
3816 first N-chars of the string and allocate based on that size.
3817 */
3818 /* Initial allocation is based on the longest-possible unichr
3819 escape.
3820
3821 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
3822 unichr, so in this case it's the longest unichr escape. In
3823 narrow (UTF-16) builds this is five chars per source unichr
3824 since there are two unichrs in the surrogate pair, so in narrow
3825 (UTF-16) builds it's not the longest unichr escape.
3826
3827 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
3828 so in the narrow (UTF-16) build case it's the longest unichr
3829 escape.
3830 */
3831
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003832 if (size == 0)
3833 return PyBytes_FromStringAndSize(NULL, 0);
3834
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003835 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003836 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003837
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003838 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00003839 2
3840 + expandsize*size
3841 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003842 if (repr == NULL)
3843 return NULL;
3844
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003845 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003846
Guido van Rossumd57fd912000-03-10 22:53:23 +00003847 while (size-- > 0) {
3848 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00003849
Walter Dörwald79e913e2007-05-12 11:08:06 +00003850 /* Escape backslashes */
3851 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003852 *p++ = '\\';
3853 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00003854 continue;
Tim Petersced69f82003-09-16 20:30:58 +00003855 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00003856
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00003857#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003858 /* Map 21-bit characters to '\U00xxxxxx' */
3859 else if (ch >= 0x10000) {
3860 *p++ = '\\';
3861 *p++ = 'U';
Walter Dörwald79e913e2007-05-12 11:08:06 +00003862 *p++ = hexdigits[(ch >> 28) & 0x0000000F];
3863 *p++ = hexdigits[(ch >> 24) & 0x0000000F];
3864 *p++ = hexdigits[(ch >> 20) & 0x0000000F];
3865 *p++ = hexdigits[(ch >> 16) & 0x0000000F];
3866 *p++ = hexdigits[(ch >> 12) & 0x0000000F];
3867 *p++ = hexdigits[(ch >> 8) & 0x0000000F];
3868 *p++ = hexdigits[(ch >> 4) & 0x0000000F];
3869 *p++ = hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00003870 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003871 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00003872#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003873 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
3874 else if (ch >= 0xD800 && ch < 0xDC00) {
3875 Py_UNICODE ch2;
3876 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00003877
Benjamin Peterson29060642009-01-31 22:14:21 +00003878 ch2 = *s++;
3879 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00003880 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003881 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
3882 *p++ = '\\';
3883 *p++ = 'U';
3884 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
3885 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
3886 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
3887 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
3888 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
3889 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
3890 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
3891 *p++ = hexdigits[ucs & 0x0000000F];
3892 continue;
3893 }
3894 /* Fall through: isolated surrogates are copied as-is */
3895 s--;
3896 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003897 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00003898#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00003899
Guido van Rossumd57fd912000-03-10 22:53:23 +00003900 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00003901 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003902 *p++ = '\\';
3903 *p++ = 'u';
Walter Dörwald79e913e2007-05-12 11:08:06 +00003904 *p++ = hexdigits[(ch >> 12) & 0x000F];
3905 *p++ = hexdigits[(ch >> 8) & 0x000F];
3906 *p++ = hexdigits[(ch >> 4) & 0x000F];
3907 *p++ = hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00003908 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00003909
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00003910 /* Map special whitespace to '\t', \n', '\r' */
3911 else if (ch == '\t') {
3912 *p++ = '\\';
3913 *p++ = 't';
3914 }
3915 else if (ch == '\n') {
3916 *p++ = '\\';
3917 *p++ = 'n';
3918 }
3919 else if (ch == '\r') {
3920 *p++ = '\\';
3921 *p++ = 'r';
3922 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00003923
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00003924 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00003925 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003926 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00003927 *p++ = 'x';
Walter Dörwald79e913e2007-05-12 11:08:06 +00003928 *p++ = hexdigits[(ch >> 4) & 0x000F];
3929 *p++ = hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00003930 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00003931
Guido van Rossumd57fd912000-03-10 22:53:23 +00003932 /* Copy everything else as-is */
3933 else
3934 *p++ = (char) ch;
3935 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003936
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003937 assert(p - PyBytes_AS_STRING(repr) > 0);
3938 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
3939 return NULL;
3940 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003941}
3942
Alexandre Vassalotti2056bed2008-12-27 19:46:35 +00003943PyObject *PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003944{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00003945 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003946 if (!PyUnicode_Check(unicode)) {
3947 PyErr_BadArgument();
3948 return NULL;
3949 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00003950 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
3951 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00003952 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003953}
3954
3955/* --- Raw Unicode Escape Codec ------------------------------------------- */
3956
3957PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003958 Py_ssize_t size,
3959 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003960{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003961 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003962 Py_ssize_t startinpos;
3963 Py_ssize_t endinpos;
3964 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003965 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003966 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003967 const char *end;
3968 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003969 PyObject *errorHandler = NULL;
3970 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00003971
Guido van Rossumd57fd912000-03-10 22:53:23 +00003972 /* Escaped strings will always be longer than the resulting
3973 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003974 length after conversion to the true value. (But decoding error
3975 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003976 v = _PyUnicode_New(size);
3977 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003978 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003979 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003980 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003981 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003982 end = s + size;
3983 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003984 unsigned char c;
3985 Py_UCS4 x;
3986 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003987 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003988
Benjamin Peterson29060642009-01-31 22:14:21 +00003989 /* Non-escape characters are interpreted as Unicode ordinals */
3990 if (*s != '\\') {
3991 *p++ = (unsigned char)*s++;
3992 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003993 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003994 startinpos = s-starts;
3995
3996 /* \u-escapes are only interpreted iff the number of leading
3997 backslashes if odd */
3998 bs = s;
3999 for (;s < end;) {
4000 if (*s != '\\')
4001 break;
4002 *p++ = (unsigned char)*s++;
4003 }
4004 if (((s - bs) & 1) == 0 ||
4005 s >= end ||
4006 (*s != 'u' && *s != 'U')) {
4007 continue;
4008 }
4009 p--;
4010 count = *s=='u' ? 4 : 8;
4011 s++;
4012
4013 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
4014 outpos = p-PyUnicode_AS_UNICODE(v);
4015 for (x = 0, i = 0; i < count; ++i, ++s) {
4016 c = (unsigned char)*s;
4017 if (!ISXDIGIT(c)) {
4018 endinpos = s-starts;
4019 if (unicode_decode_call_errorhandler(
4020 errors, &errorHandler,
4021 "rawunicodeescape", "truncated \\uXXXX",
4022 &starts, &end, &startinpos, &endinpos, &exc, &s,
4023 &v, &outpos, &p))
4024 goto onError;
4025 goto nextByte;
4026 }
4027 x = (x<<4) & ~0xF;
4028 if (c >= '0' && c <= '9')
4029 x += c - '0';
4030 else if (c >= 'a' && c <= 'f')
4031 x += 10 + c - 'a';
4032 else
4033 x += 10 + c - 'A';
4034 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00004035 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00004036 /* UCS-2 character */
4037 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004038 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004039 /* UCS-4 character. Either store directly, or as
4040 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00004041#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004042 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004043#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004044 x -= 0x10000L;
4045 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
4046 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00004047#endif
4048 } else {
4049 endinpos = s-starts;
4050 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004051 if (unicode_decode_call_errorhandler(
4052 errors, &errorHandler,
4053 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00004054 &starts, &end, &startinpos, &endinpos, &exc, &s,
4055 &v, &outpos, &p))
4056 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004057 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004058 nextByte:
4059 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004060 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004061 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004062 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004063 Py_XDECREF(errorHandler);
4064 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004065 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004066
Benjamin Peterson29060642009-01-31 22:14:21 +00004067 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004068 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004069 Py_XDECREF(errorHandler);
4070 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004071 return NULL;
4072}
4073
4074PyObject *PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004075 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004076{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004077 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004078 char *p;
4079 char *q;
4080
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004081#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004082 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004083#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004084 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004085#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00004086
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004087 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00004088 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00004089
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004090 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004091 if (repr == NULL)
4092 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00004093 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004094 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004095
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004096 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004097 while (size-- > 0) {
4098 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004099#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004100 /* Map 32-bit characters to '\Uxxxxxxxx' */
4101 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004102 *p++ = '\\';
4103 *p++ = 'U';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00004104 *p++ = hexdigits[(ch >> 28) & 0xf];
4105 *p++ = hexdigits[(ch >> 24) & 0xf];
4106 *p++ = hexdigits[(ch >> 20) & 0xf];
4107 *p++ = hexdigits[(ch >> 16) & 0xf];
4108 *p++ = hexdigits[(ch >> 12) & 0xf];
4109 *p++ = hexdigits[(ch >> 8) & 0xf];
4110 *p++ = hexdigits[(ch >> 4) & 0xf];
4111 *p++ = hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00004112 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004113 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00004114#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004115 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
4116 if (ch >= 0xD800 && ch < 0xDC00) {
4117 Py_UNICODE ch2;
4118 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00004119
Benjamin Peterson29060642009-01-31 22:14:21 +00004120 ch2 = *s++;
4121 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00004122 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004123 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
4124 *p++ = '\\';
4125 *p++ = 'U';
4126 *p++ = hexdigits[(ucs >> 28) & 0xf];
4127 *p++ = hexdigits[(ucs >> 24) & 0xf];
4128 *p++ = hexdigits[(ucs >> 20) & 0xf];
4129 *p++ = hexdigits[(ucs >> 16) & 0xf];
4130 *p++ = hexdigits[(ucs >> 12) & 0xf];
4131 *p++ = hexdigits[(ucs >> 8) & 0xf];
4132 *p++ = hexdigits[(ucs >> 4) & 0xf];
4133 *p++ = hexdigits[ucs & 0xf];
4134 continue;
4135 }
4136 /* Fall through: isolated surrogates are copied as-is */
4137 s--;
4138 size++;
4139 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00004140#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004141 /* Map 16-bit characters to '\uxxxx' */
4142 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004143 *p++ = '\\';
4144 *p++ = 'u';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00004145 *p++ = hexdigits[(ch >> 12) & 0xf];
4146 *p++ = hexdigits[(ch >> 8) & 0xf];
4147 *p++ = hexdigits[(ch >> 4) & 0xf];
4148 *p++ = hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00004149 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004150 /* Copy everything else as-is */
4151 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00004152 *p++ = (char) ch;
4153 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00004154 size = p - q;
4155
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004156 assert(size > 0);
4157 if (_PyBytes_Resize(&repr, size) < 0)
4158 return NULL;
4159 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004160}
4161
4162PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
4163{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004164 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004165 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00004166 PyErr_BadArgument();
4167 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004168 }
Walter Dörwald711005d2007-05-12 12:03:26 +00004169 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
4170 PyUnicode_GET_SIZE(unicode));
4171
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004172 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004173}
4174
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004175/* --- Unicode Internal Codec ------------------------------------------- */
4176
4177PyObject *_PyUnicode_DecodeUnicodeInternal(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004178 Py_ssize_t size,
4179 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004180{
4181 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004182 Py_ssize_t startinpos;
4183 Py_ssize_t endinpos;
4184 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004185 PyUnicodeObject *v;
4186 Py_UNICODE *p;
4187 const char *end;
4188 const char *reason;
4189 PyObject *errorHandler = NULL;
4190 PyObject *exc = NULL;
4191
Neal Norwitzd43069c2006-01-08 01:12:10 +00004192#ifdef Py_UNICODE_WIDE
4193 Py_UNICODE unimax = PyUnicode_GetMax();
4194#endif
4195
Thomas Wouters89f507f2006-12-13 04:49:30 +00004196 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004197 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
4198 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004199 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004200 if (PyUnicode_GetSize((PyObject *)v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004201 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004202 p = PyUnicode_AS_UNICODE(v);
4203 end = s + size;
4204
4205 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00004206 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004207 /* We have to sanity check the raw data, otherwise doom looms for
4208 some malformed UCS-4 data. */
4209 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00004210#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004211 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00004212#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004213 end-s < Py_UNICODE_SIZE
4214 )
Benjamin Peterson29060642009-01-31 22:14:21 +00004215 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004216 startinpos = s - starts;
4217 if (end-s < Py_UNICODE_SIZE) {
4218 endinpos = end-starts;
4219 reason = "truncated input";
4220 }
4221 else {
4222 endinpos = s - starts + Py_UNICODE_SIZE;
4223 reason = "illegal code point (> 0x10FFFF)";
4224 }
4225 outpos = p - PyUnicode_AS_UNICODE(v);
4226 if (unicode_decode_call_errorhandler(
4227 errors, &errorHandler,
4228 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00004229 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00004230 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004231 goto onError;
4232 }
4233 }
4234 else {
4235 p++;
4236 s += Py_UNICODE_SIZE;
4237 }
4238 }
4239
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004240 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004241 goto onError;
4242 Py_XDECREF(errorHandler);
4243 Py_XDECREF(exc);
4244 return (PyObject *)v;
4245
Benjamin Peterson29060642009-01-31 22:14:21 +00004246 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004247 Py_XDECREF(v);
4248 Py_XDECREF(errorHandler);
4249 Py_XDECREF(exc);
4250 return NULL;
4251}
4252
Guido van Rossumd57fd912000-03-10 22:53:23 +00004253/* --- Latin-1 Codec ------------------------------------------------------ */
4254
4255PyObject *PyUnicode_DecodeLatin1(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004256 Py_ssize_t size,
4257 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004258{
4259 PyUnicodeObject *v;
4260 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00004261 const char *e, *unrolled_end;
Tim Petersced69f82003-09-16 20:30:58 +00004262
Guido van Rossumd57fd912000-03-10 22:53:23 +00004263 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004264 if (size == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004265 Py_UNICODE r = *(unsigned char*)s;
4266 return PyUnicode_FromUnicode(&r, 1);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004267 }
4268
Guido van Rossumd57fd912000-03-10 22:53:23 +00004269 v = _PyUnicode_New(size);
4270 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004271 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004272 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004273 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004274 p = PyUnicode_AS_UNICODE(v);
Antoine Pitrouab868312009-01-10 15:40:25 +00004275 e = s + size;
4276 /* Unrolling the copy makes it much faster by reducing the looping
4277 overhead. This is similar to what many memcpy() implementations do. */
4278 unrolled_end = e - 4;
4279 while (s < unrolled_end) {
4280 p[0] = (unsigned char) s[0];
4281 p[1] = (unsigned char) s[1];
4282 p[2] = (unsigned char) s[2];
4283 p[3] = (unsigned char) s[3];
4284 s += 4;
4285 p += 4;
4286 }
4287 while (s < e)
4288 *p++ = (unsigned char) *s++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004289 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004290
Benjamin Peterson29060642009-01-31 22:14:21 +00004291 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004292 Py_XDECREF(v);
4293 return NULL;
4294}
4295
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004296/* create or adjust a UnicodeEncodeError */
4297static void make_encode_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004298 const char *encoding,
4299 const Py_UNICODE *unicode, Py_ssize_t size,
4300 Py_ssize_t startpos, Py_ssize_t endpos,
4301 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004302{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004303 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004304 *exceptionObject = PyUnicodeEncodeError_Create(
4305 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004306 }
4307 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004308 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
4309 goto onError;
4310 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
4311 goto onError;
4312 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
4313 goto onError;
4314 return;
4315 onError:
4316 Py_DECREF(*exceptionObject);
4317 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004318 }
4319}
4320
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004321/* raises a UnicodeEncodeError */
4322static void raise_encode_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004323 const char *encoding,
4324 const Py_UNICODE *unicode, Py_ssize_t size,
4325 Py_ssize_t startpos, Py_ssize_t endpos,
4326 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004327{
4328 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004329 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004330 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004331 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004332}
4333
4334/* error handling callback helper:
4335 build arguments, call the callback and check the arguments,
4336 put the result into newpos and return the replacement string, which
4337 has to be freed by the caller */
4338static PyObject *unicode_encode_call_errorhandler(const char *errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00004339 PyObject **errorHandler,
4340 const char *encoding, const char *reason,
4341 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
4342 Py_ssize_t startpos, Py_ssize_t endpos,
4343 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004344{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004345 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004346
4347 PyObject *restuple;
4348 PyObject *resunicode;
4349
4350 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004351 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004352 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004353 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004354 }
4355
4356 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004357 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004358 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004359 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004360
4361 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00004362 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004363 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004364 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004365 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004366 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004367 Py_DECREF(restuple);
4368 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004369 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004370 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00004371 &resunicode, newpos)) {
4372 Py_DECREF(restuple);
4373 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004374 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004375 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
4376 PyErr_SetString(PyExc_TypeError, &argparse[3]);
4377 Py_DECREF(restuple);
4378 return NULL;
4379 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004380 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004381 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004382 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004383 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
4384 Py_DECREF(restuple);
4385 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004386 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004387 Py_INCREF(resunicode);
4388 Py_DECREF(restuple);
4389 return resunicode;
4390}
4391
4392static PyObject *unicode_encode_ucs1(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004393 Py_ssize_t size,
4394 const char *errors,
4395 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004396{
4397 /* output object */
4398 PyObject *res;
4399 /* pointers to the beginning and end+1 of input */
4400 const Py_UNICODE *startp = p;
4401 const Py_UNICODE *endp = p + size;
4402 /* pointer to the beginning of the unencodable characters */
4403 /* const Py_UNICODE *badp = NULL; */
4404 /* pointer into the output */
4405 char *str;
4406 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00004407 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004408 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
4409 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004410 PyObject *errorHandler = NULL;
4411 PyObject *exc = NULL;
4412 /* the following variable is used for caching string comparisons
4413 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
4414 int known_errorHandler = -1;
4415
4416 /* allocate enough for a simple encoding without
4417 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00004418 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00004419 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004420 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004421 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00004422 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004423 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004424 ressize = size;
4425
4426 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004427 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004428
Benjamin Peterson29060642009-01-31 22:14:21 +00004429 /* can we encode this? */
4430 if (c<limit) {
4431 /* no overflow check, because we know that the space is enough */
4432 *str++ = (char)c;
4433 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004434 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004435 else {
4436 Py_ssize_t unicodepos = p-startp;
4437 Py_ssize_t requiredsize;
4438 PyObject *repunicode;
4439 Py_ssize_t repsize;
4440 Py_ssize_t newpos;
4441 Py_ssize_t respos;
4442 Py_UNICODE *uni2;
4443 /* startpos for collecting unencodable chars */
4444 const Py_UNICODE *collstart = p;
4445 const Py_UNICODE *collend = p;
4446 /* find all unecodable characters */
4447 while ((collend < endp) && ((*collend)>=limit))
4448 ++collend;
4449 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
4450 if (known_errorHandler==-1) {
4451 if ((errors==NULL) || (!strcmp(errors, "strict")))
4452 known_errorHandler = 1;
4453 else if (!strcmp(errors, "replace"))
4454 known_errorHandler = 2;
4455 else if (!strcmp(errors, "ignore"))
4456 known_errorHandler = 3;
4457 else if (!strcmp(errors, "xmlcharrefreplace"))
4458 known_errorHandler = 4;
4459 else
4460 known_errorHandler = 0;
4461 }
4462 switch (known_errorHandler) {
4463 case 1: /* strict */
4464 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
4465 goto onError;
4466 case 2: /* replace */
4467 while (collstart++<collend)
4468 *str++ = '?'; /* fall through */
4469 case 3: /* ignore */
4470 p = collend;
4471 break;
4472 case 4: /* xmlcharrefreplace */
4473 respos = str - PyBytes_AS_STRING(res);
4474 /* determine replacement size (temporarily (mis)uses p) */
4475 for (p = collstart, repsize = 0; p < collend; ++p) {
4476 if (*p<10)
4477 repsize += 2+1+1;
4478 else if (*p<100)
4479 repsize += 2+2+1;
4480 else if (*p<1000)
4481 repsize += 2+3+1;
4482 else if (*p<10000)
4483 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00004484#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004485 else
4486 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00004487#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004488 else if (*p<100000)
4489 repsize += 2+5+1;
4490 else if (*p<1000000)
4491 repsize += 2+6+1;
4492 else
4493 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004494#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004495 }
4496 requiredsize = respos+repsize+(endp-collend);
4497 if (requiredsize > ressize) {
4498 if (requiredsize<2*ressize)
4499 requiredsize = 2*ressize;
4500 if (_PyBytes_Resize(&res, requiredsize))
4501 goto onError;
4502 str = PyBytes_AS_STRING(res) + respos;
4503 ressize = requiredsize;
4504 }
4505 /* generate replacement (temporarily (mis)uses p) */
4506 for (p = collstart; p < collend; ++p) {
4507 str += sprintf(str, "&#%d;", (int)*p);
4508 }
4509 p = collend;
4510 break;
4511 default:
4512 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
4513 encoding, reason, startp, size, &exc,
4514 collstart-startp, collend-startp, &newpos);
4515 if (repunicode == NULL)
4516 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004517 if (PyBytes_Check(repunicode)) {
4518 /* Directly copy bytes result to output. */
4519 repsize = PyBytes_Size(repunicode);
4520 if (repsize > 1) {
4521 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00004522 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00004523 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
4524 Py_DECREF(repunicode);
4525 goto onError;
4526 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00004527 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004528 ressize += repsize-1;
4529 }
4530 memcpy(str, PyBytes_AsString(repunicode), repsize);
4531 str += repsize;
4532 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004533 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00004534 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004535 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004536 /* need more space? (at least enough for what we
4537 have+the replacement+the rest of the string, so
4538 we won't have to check space for encodable characters) */
4539 respos = str - PyBytes_AS_STRING(res);
4540 repsize = PyUnicode_GET_SIZE(repunicode);
4541 requiredsize = respos+repsize+(endp-collend);
4542 if (requiredsize > ressize) {
4543 if (requiredsize<2*ressize)
4544 requiredsize = 2*ressize;
4545 if (_PyBytes_Resize(&res, requiredsize)) {
4546 Py_DECREF(repunicode);
4547 goto onError;
4548 }
4549 str = PyBytes_AS_STRING(res) + respos;
4550 ressize = requiredsize;
4551 }
4552 /* check if there is anything unencodable in the replacement
4553 and copy it to the output */
4554 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
4555 c = *uni2;
4556 if (c >= limit) {
4557 raise_encode_exception(&exc, encoding, startp, size,
4558 unicodepos, unicodepos+1, reason);
4559 Py_DECREF(repunicode);
4560 goto onError;
4561 }
4562 *str = (char)c;
4563 }
4564 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004565 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00004566 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004567 }
4568 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004569 /* Resize if we allocated to much */
4570 size = str - PyBytes_AS_STRING(res);
4571 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00004572 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004573 if (_PyBytes_Resize(&res, size) < 0)
4574 goto onError;
4575 }
4576
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004577 Py_XDECREF(errorHandler);
4578 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004579 return res;
4580
4581 onError:
4582 Py_XDECREF(res);
4583 Py_XDECREF(errorHandler);
4584 Py_XDECREF(exc);
4585 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004586}
4587
Guido van Rossumd57fd912000-03-10 22:53:23 +00004588PyObject *PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004589 Py_ssize_t size,
4590 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004591{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004592 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004593}
4594
4595PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
4596{
4597 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004598 PyErr_BadArgument();
4599 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004600 }
4601 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004602 PyUnicode_GET_SIZE(unicode),
4603 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004604}
4605
4606/* --- 7-bit ASCII Codec -------------------------------------------------- */
4607
Guido van Rossumd57fd912000-03-10 22:53:23 +00004608PyObject *PyUnicode_DecodeASCII(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004609 Py_ssize_t size,
4610 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004611{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004612 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004613 PyUnicodeObject *v;
4614 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004615 Py_ssize_t startinpos;
4616 Py_ssize_t endinpos;
4617 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004618 const char *e;
4619 PyObject *errorHandler = NULL;
4620 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00004621
Guido van Rossumd57fd912000-03-10 22:53:23 +00004622 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004623 if (size == 1 && *(unsigned char*)s < 128) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004624 Py_UNICODE r = *(unsigned char*)s;
4625 return PyUnicode_FromUnicode(&r, 1);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004626 }
Tim Petersced69f82003-09-16 20:30:58 +00004627
Guido van Rossumd57fd912000-03-10 22:53:23 +00004628 v = _PyUnicode_New(size);
4629 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004630 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004631 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004632 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004633 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004634 e = s + size;
4635 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004636 register unsigned char c = (unsigned char)*s;
4637 if (c < 128) {
4638 *p++ = c;
4639 ++s;
4640 }
4641 else {
4642 startinpos = s-starts;
4643 endinpos = startinpos + 1;
4644 outpos = p - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
4645 if (unicode_decode_call_errorhandler(
4646 errors, &errorHandler,
4647 "ascii", "ordinal not in range(128)",
4648 &starts, &e, &startinpos, &endinpos, &exc, &s,
4649 &v, &outpos, &p))
4650 goto onError;
4651 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004652 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00004653 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00004654 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
4655 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004656 Py_XDECREF(errorHandler);
4657 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004658 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004659
Benjamin Peterson29060642009-01-31 22:14:21 +00004660 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004661 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004662 Py_XDECREF(errorHandler);
4663 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004664 return NULL;
4665}
4666
Guido van Rossumd57fd912000-03-10 22:53:23 +00004667PyObject *PyUnicode_EncodeASCII(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004668 Py_ssize_t size,
4669 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004670{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004671 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004672}
4673
4674PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
4675{
4676 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004677 PyErr_BadArgument();
4678 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004679 }
4680 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004681 PyUnicode_GET_SIZE(unicode),
4682 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004683}
4684
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004685#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004686
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004687/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004688
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00004689#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004690#define NEED_RETRY
4691#endif
4692
4693/* XXX This code is limited to "true" double-byte encodings, as
4694 a) it assumes an incomplete character consists of a single byte, and
4695 b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
Benjamin Peterson29060642009-01-31 22:14:21 +00004696 encodings, see IsDBCSLeadByteEx documentation. */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004697
4698static int is_dbcs_lead_byte(const char *s, int offset)
4699{
4700 const char *curr = s + offset;
4701
4702 if (IsDBCSLeadByte(*curr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004703 const char *prev = CharPrev(s, curr);
4704 return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004705 }
4706 return 0;
4707}
4708
4709/*
4710 * Decode MBCS string into unicode object. If 'final' is set, converts
4711 * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
4712 */
4713static int decode_mbcs(PyUnicodeObject **v,
Benjamin Peterson29060642009-01-31 22:14:21 +00004714 const char *s, /* MBCS string */
4715 int size, /* sizeof MBCS string */
Victor Stinner554f3f02010-06-16 23:33:54 +00004716 int final,
4717 const char *errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004718{
4719 Py_UNICODE *p;
Victor Stinner554f3f02010-06-16 23:33:54 +00004720 Py_ssize_t n;
4721 DWORD usize;
4722 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004723
4724 assert(size >= 0);
4725
Victor Stinner554f3f02010-06-16 23:33:54 +00004726 /* check and handle 'errors' arg */
4727 if (errors==NULL || strcmp(errors, "strict")==0)
4728 flags = MB_ERR_INVALID_CHARS;
4729 else if (strcmp(errors, "ignore")==0)
4730 flags = 0;
4731 else {
4732 PyErr_Format(PyExc_ValueError,
4733 "mbcs encoding does not support errors='%s'",
4734 errors);
4735 return -1;
4736 }
4737
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004738 /* Skip trailing lead-byte unless 'final' is set */
4739 if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
Benjamin Peterson29060642009-01-31 22:14:21 +00004740 --size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004741
4742 /* First get the size of the result */
4743 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00004744 usize = MultiByteToWideChar(CP_ACP, flags, s, size, NULL, 0);
4745 if (usize==0)
4746 goto mbcs_decode_error;
4747 } else
4748 usize = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004749
4750 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004751 /* Create unicode object */
4752 *v = _PyUnicode_New(usize);
4753 if (*v == NULL)
4754 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00004755 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004756 }
4757 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004758 /* Extend unicode object */
4759 n = PyUnicode_GET_SIZE(*v);
4760 if (_PyUnicode_Resize(v, n + usize) < 0)
4761 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004762 }
4763
4764 /* Do the conversion */
Victor Stinner554f3f02010-06-16 23:33:54 +00004765 if (usize > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004766 p = PyUnicode_AS_UNICODE(*v) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00004767 if (0 == MultiByteToWideChar(CP_ACP, flags, s, size, p, usize)) {
4768 goto mbcs_decode_error;
Benjamin Peterson29060642009-01-31 22:14:21 +00004769 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004770 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004771 return size;
Victor Stinner554f3f02010-06-16 23:33:54 +00004772
4773mbcs_decode_error:
4774 /* If the last error was ERROR_NO_UNICODE_TRANSLATION, then
4775 we raise a UnicodeDecodeError - else it is a 'generic'
4776 windows error
4777 */
4778 if (GetLastError()==ERROR_NO_UNICODE_TRANSLATION) {
4779 /* Ideally, we should get reason from FormatMessage - this
4780 is the Windows 2000 English version of the message
4781 */
4782 PyObject *exc = NULL;
4783 const char *reason = "No mapping for the Unicode character exists "
4784 "in the target multi-byte code page.";
4785 make_decode_exception(&exc, "mbcs", s, size, 0, 0, reason);
4786 if (exc != NULL) {
4787 PyCodec_StrictErrors(exc);
4788 Py_DECREF(exc);
4789 }
4790 } else {
4791 PyErr_SetFromWindowsErrWithFilename(0, NULL);
4792 }
4793 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004794}
4795
4796PyObject *PyUnicode_DecodeMBCSStateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004797 Py_ssize_t size,
4798 const char *errors,
4799 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004800{
4801 PyUnicodeObject *v = NULL;
4802 int done;
4803
4804 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004805 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004806
4807#ifdef NEED_RETRY
4808 retry:
4809 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00004810 done = decode_mbcs(&v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004811 else
4812#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00004813 done = decode_mbcs(&v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004814
4815 if (done < 0) {
4816 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00004817 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004818 }
4819
4820 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004821 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004822
4823#ifdef NEED_RETRY
4824 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004825 s += done;
4826 size -= done;
4827 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004828 }
4829#endif
4830
4831 return (PyObject *)v;
4832}
4833
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004834PyObject *PyUnicode_DecodeMBCS(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004835 Py_ssize_t size,
4836 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004837{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004838 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
4839}
4840
4841/*
4842 * Convert unicode into string object (MBCS).
4843 * Returns 0 if succeed, -1 otherwise.
4844 */
4845static int encode_mbcs(PyObject **repr,
Benjamin Peterson29060642009-01-31 22:14:21 +00004846 const Py_UNICODE *p, /* unicode */
Victor Stinner554f3f02010-06-16 23:33:54 +00004847 int size, /* size of unicode */
4848 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004849{
Victor Stinner554f3f02010-06-16 23:33:54 +00004850 BOOL usedDefaultChar = FALSE;
4851 BOOL *pusedDefaultChar;
4852 int mbcssize;
4853 Py_ssize_t n;
4854 PyObject *exc = NULL;
4855 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004856
4857 assert(size >= 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004858
Victor Stinner554f3f02010-06-16 23:33:54 +00004859 /* check and handle 'errors' arg */
4860 if (errors==NULL || strcmp(errors, "strict")==0) {
4861 flags = WC_NO_BEST_FIT_CHARS;
4862 pusedDefaultChar = &usedDefaultChar;
4863 } else if (strcmp(errors, "replace")==0) {
4864 flags = 0;
4865 pusedDefaultChar = NULL;
4866 } else {
4867 PyErr_Format(PyExc_ValueError,
4868 "mbcs encoding does not support errors='%s'",
4869 errors);
4870 return -1;
4871 }
4872
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004873 /* First get the size of the result */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004874 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00004875 mbcssize = WideCharToMultiByte(CP_ACP, flags, p, size, NULL, 0,
4876 NULL, pusedDefaultChar);
Benjamin Peterson29060642009-01-31 22:14:21 +00004877 if (mbcssize == 0) {
4878 PyErr_SetFromWindowsErrWithFilename(0, NULL);
4879 return -1;
4880 }
Victor Stinner554f3f02010-06-16 23:33:54 +00004881 /* If we used a default char, then we failed! */
4882 if (pusedDefaultChar && *pusedDefaultChar)
4883 goto mbcs_encode_error;
4884 } else {
4885 mbcssize = 0;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004886 }
4887
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004888 if (*repr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004889 /* Create string object */
4890 *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
4891 if (*repr == NULL)
4892 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00004893 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004894 }
4895 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004896 /* Extend string object */
4897 n = PyBytes_Size(*repr);
4898 if (_PyBytes_Resize(repr, n + mbcssize) < 0)
4899 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004900 }
4901
4902 /* Do the conversion */
4903 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004904 char *s = PyBytes_AS_STRING(*repr) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00004905 if (0 == WideCharToMultiByte(CP_ACP, flags, p, size, s, mbcssize,
4906 NULL, pusedDefaultChar)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004907 PyErr_SetFromWindowsErrWithFilename(0, NULL);
4908 return -1;
4909 }
Victor Stinner554f3f02010-06-16 23:33:54 +00004910 if (pusedDefaultChar && *pusedDefaultChar)
4911 goto mbcs_encode_error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004912 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004913 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00004914
4915mbcs_encode_error:
4916 raise_encode_exception(&exc, "mbcs", p, size, 0, 0, "invalid character");
4917 Py_XDECREF(exc);
4918 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004919}
4920
4921PyObject *PyUnicode_EncodeMBCS(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004922 Py_ssize_t size,
4923 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004924{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004925 PyObject *repr = NULL;
4926 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00004927
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004928#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00004929 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004930 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00004931 ret = encode_mbcs(&repr, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004932 else
4933#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00004934 ret = encode_mbcs(&repr, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004935
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004936 if (ret < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004937 Py_XDECREF(repr);
4938 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004939 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004940
4941#ifdef NEED_RETRY
4942 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004943 p += INT_MAX;
4944 size -= INT_MAX;
4945 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004946 }
4947#endif
4948
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004949 return repr;
4950}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004951
Mark Hammond0ccda1e2003-07-01 00:13:27 +00004952PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
4953{
4954 if (!PyUnicode_Check(unicode)) {
4955 PyErr_BadArgument();
4956 return NULL;
4957 }
4958 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004959 PyUnicode_GET_SIZE(unicode),
4960 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00004961}
4962
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004963#undef NEED_RETRY
4964
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004965#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004966
Guido van Rossumd57fd912000-03-10 22:53:23 +00004967/* --- Character Mapping Codec -------------------------------------------- */
4968
Guido van Rossumd57fd912000-03-10 22:53:23 +00004969PyObject *PyUnicode_DecodeCharmap(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004970 Py_ssize_t size,
4971 PyObject *mapping,
4972 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004973{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004974 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004975 Py_ssize_t startinpos;
4976 Py_ssize_t endinpos;
4977 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004978 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004979 PyUnicodeObject *v;
4980 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004981 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004982 PyObject *errorHandler = NULL;
4983 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00004984 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004985 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00004986
Guido van Rossumd57fd912000-03-10 22:53:23 +00004987 /* Default to Latin-1 */
4988 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004989 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004990
4991 v = _PyUnicode_New(size);
4992 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004993 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004994 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004995 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004996 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004997 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00004998 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004999 mapstring = PyUnicode_AS_UNICODE(mapping);
5000 maplen = PyUnicode_GET_SIZE(mapping);
5001 while (s < e) {
5002 unsigned char ch = *s;
5003 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005004
Benjamin Peterson29060642009-01-31 22:14:21 +00005005 if (ch < maplen)
5006 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005007
Benjamin Peterson29060642009-01-31 22:14:21 +00005008 if (x == 0xfffe) {
5009 /* undefined mapping */
5010 outpos = p-PyUnicode_AS_UNICODE(v);
5011 startinpos = s-starts;
5012 endinpos = startinpos+1;
5013 if (unicode_decode_call_errorhandler(
5014 errors, &errorHandler,
5015 "charmap", "character maps to <undefined>",
5016 &starts, &e, &startinpos, &endinpos, &exc, &s,
5017 &v, &outpos, &p)) {
5018 goto onError;
5019 }
5020 continue;
5021 }
5022 *p++ = x;
5023 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005024 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005025 }
5026 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005027 while (s < e) {
5028 unsigned char ch = *s;
5029 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00005030
Benjamin Peterson29060642009-01-31 22:14:21 +00005031 /* Get mapping (char ordinal -> integer, Unicode char or None) */
5032 w = PyLong_FromLong((long)ch);
5033 if (w == NULL)
5034 goto onError;
5035 x = PyObject_GetItem(mapping, w);
5036 Py_DECREF(w);
5037 if (x == NULL) {
5038 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5039 /* No mapping found means: mapping is undefined. */
5040 PyErr_Clear();
5041 x = Py_None;
5042 Py_INCREF(x);
5043 } else
5044 goto onError;
5045 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005046
Benjamin Peterson29060642009-01-31 22:14:21 +00005047 /* Apply mapping */
5048 if (PyLong_Check(x)) {
5049 long value = PyLong_AS_LONG(x);
5050 if (value < 0 || value > 65535) {
5051 PyErr_SetString(PyExc_TypeError,
5052 "character mapping must be in range(65536)");
5053 Py_DECREF(x);
5054 goto onError;
5055 }
5056 *p++ = (Py_UNICODE)value;
5057 }
5058 else if (x == Py_None) {
5059 /* undefined mapping */
5060 outpos = p-PyUnicode_AS_UNICODE(v);
5061 startinpos = s-starts;
5062 endinpos = startinpos+1;
5063 if (unicode_decode_call_errorhandler(
5064 errors, &errorHandler,
5065 "charmap", "character maps to <undefined>",
5066 &starts, &e, &startinpos, &endinpos, &exc, &s,
5067 &v, &outpos, &p)) {
5068 Py_DECREF(x);
5069 goto onError;
5070 }
5071 Py_DECREF(x);
5072 continue;
5073 }
5074 else if (PyUnicode_Check(x)) {
5075 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005076
Benjamin Peterson29060642009-01-31 22:14:21 +00005077 if (targetsize == 1)
5078 /* 1-1 mapping */
5079 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005080
Benjamin Peterson29060642009-01-31 22:14:21 +00005081 else if (targetsize > 1) {
5082 /* 1-n mapping */
5083 if (targetsize > extrachars) {
5084 /* resize first */
5085 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
5086 Py_ssize_t needed = (targetsize - extrachars) + \
5087 (targetsize << 2);
5088 extrachars += needed;
5089 /* XXX overflow detection missing */
5090 if (_PyUnicode_Resize(&v,
5091 PyUnicode_GET_SIZE(v) + needed) < 0) {
5092 Py_DECREF(x);
5093 goto onError;
5094 }
5095 p = PyUnicode_AS_UNICODE(v) + oldpos;
5096 }
5097 Py_UNICODE_COPY(p,
5098 PyUnicode_AS_UNICODE(x),
5099 targetsize);
5100 p += targetsize;
5101 extrachars -= targetsize;
5102 }
5103 /* 1-0 mapping: skip the character */
5104 }
5105 else {
5106 /* wrong return value */
5107 PyErr_SetString(PyExc_TypeError,
5108 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00005109 Py_DECREF(x);
5110 goto onError;
5111 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005112 Py_DECREF(x);
5113 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005114 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005115 }
5116 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00005117 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
5118 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005119 Py_XDECREF(errorHandler);
5120 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005121 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00005122
Benjamin Peterson29060642009-01-31 22:14:21 +00005123 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005124 Py_XDECREF(errorHandler);
5125 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005126 Py_XDECREF(v);
5127 return NULL;
5128}
5129
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005130/* Charmap encoding: the lookup table */
5131
5132struct encoding_map{
Benjamin Peterson29060642009-01-31 22:14:21 +00005133 PyObject_HEAD
5134 unsigned char level1[32];
5135 int count2, count3;
5136 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005137};
5138
5139static PyObject*
5140encoding_map_size(PyObject *obj, PyObject* args)
5141{
5142 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005143 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00005144 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005145}
5146
5147static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005148 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00005149 PyDoc_STR("Return the size (in bytes) of this object") },
5150 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005151};
5152
5153static void
5154encoding_map_dealloc(PyObject* o)
5155{
Benjamin Peterson14339b62009-01-31 16:36:08 +00005156 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005157}
5158
5159static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005160 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005161 "EncodingMap", /*tp_name*/
5162 sizeof(struct encoding_map), /*tp_basicsize*/
5163 0, /*tp_itemsize*/
5164 /* methods */
5165 encoding_map_dealloc, /*tp_dealloc*/
5166 0, /*tp_print*/
5167 0, /*tp_getattr*/
5168 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00005169 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00005170 0, /*tp_repr*/
5171 0, /*tp_as_number*/
5172 0, /*tp_as_sequence*/
5173 0, /*tp_as_mapping*/
5174 0, /*tp_hash*/
5175 0, /*tp_call*/
5176 0, /*tp_str*/
5177 0, /*tp_getattro*/
5178 0, /*tp_setattro*/
5179 0, /*tp_as_buffer*/
5180 Py_TPFLAGS_DEFAULT, /*tp_flags*/
5181 0, /*tp_doc*/
5182 0, /*tp_traverse*/
5183 0, /*tp_clear*/
5184 0, /*tp_richcompare*/
5185 0, /*tp_weaklistoffset*/
5186 0, /*tp_iter*/
5187 0, /*tp_iternext*/
5188 encoding_map_methods, /*tp_methods*/
5189 0, /*tp_members*/
5190 0, /*tp_getset*/
5191 0, /*tp_base*/
5192 0, /*tp_dict*/
5193 0, /*tp_descr_get*/
5194 0, /*tp_descr_set*/
5195 0, /*tp_dictoffset*/
5196 0, /*tp_init*/
5197 0, /*tp_alloc*/
5198 0, /*tp_new*/
5199 0, /*tp_free*/
5200 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005201};
5202
5203PyObject*
5204PyUnicode_BuildEncodingMap(PyObject* string)
5205{
5206 Py_UNICODE *decode;
5207 PyObject *result;
5208 struct encoding_map *mresult;
5209 int i;
5210 int need_dict = 0;
5211 unsigned char level1[32];
5212 unsigned char level2[512];
5213 unsigned char *mlevel1, *mlevel2, *mlevel3;
5214 int count2 = 0, count3 = 0;
5215
5216 if (!PyUnicode_Check(string) || PyUnicode_GetSize(string) != 256) {
5217 PyErr_BadArgument();
5218 return NULL;
5219 }
5220 decode = PyUnicode_AS_UNICODE(string);
5221 memset(level1, 0xFF, sizeof level1);
5222 memset(level2, 0xFF, sizeof level2);
5223
5224 /* If there isn't a one-to-one mapping of NULL to \0,
5225 or if there are non-BMP characters, we need to use
5226 a mapping dictionary. */
5227 if (decode[0] != 0)
5228 need_dict = 1;
5229 for (i = 1; i < 256; i++) {
5230 int l1, l2;
5231 if (decode[i] == 0
Benjamin Peterson29060642009-01-31 22:14:21 +00005232#ifdef Py_UNICODE_WIDE
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005233 || decode[i] > 0xFFFF
Benjamin Peterson29060642009-01-31 22:14:21 +00005234#endif
5235 ) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005236 need_dict = 1;
5237 break;
5238 }
5239 if (decode[i] == 0xFFFE)
5240 /* unmapped character */
5241 continue;
5242 l1 = decode[i] >> 11;
5243 l2 = decode[i] >> 7;
5244 if (level1[l1] == 0xFF)
5245 level1[l1] = count2++;
5246 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00005247 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005248 }
5249
5250 if (count2 >= 0xFF || count3 >= 0xFF)
5251 need_dict = 1;
5252
5253 if (need_dict) {
5254 PyObject *result = PyDict_New();
5255 PyObject *key, *value;
5256 if (!result)
5257 return NULL;
5258 for (i = 0; i < 256; i++) {
5259 key = value = NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00005260 key = PyLong_FromLong(decode[i]);
5261 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005262 if (!key || !value)
5263 goto failed1;
5264 if (PyDict_SetItem(result, key, value) == -1)
5265 goto failed1;
5266 Py_DECREF(key);
5267 Py_DECREF(value);
5268 }
5269 return result;
5270 failed1:
5271 Py_XDECREF(key);
5272 Py_XDECREF(value);
5273 Py_DECREF(result);
5274 return NULL;
5275 }
5276
5277 /* Create a three-level trie */
5278 result = PyObject_MALLOC(sizeof(struct encoding_map) +
5279 16*count2 + 128*count3 - 1);
5280 if (!result)
5281 return PyErr_NoMemory();
5282 PyObject_Init(result, &EncodingMapType);
5283 mresult = (struct encoding_map*)result;
5284 mresult->count2 = count2;
5285 mresult->count3 = count3;
5286 mlevel1 = mresult->level1;
5287 mlevel2 = mresult->level23;
5288 mlevel3 = mresult->level23 + 16*count2;
5289 memcpy(mlevel1, level1, 32);
5290 memset(mlevel2, 0xFF, 16*count2);
5291 memset(mlevel3, 0, 128*count3);
5292 count3 = 0;
5293 for (i = 1; i < 256; i++) {
5294 int o1, o2, o3, i2, i3;
5295 if (decode[i] == 0xFFFE)
5296 /* unmapped character */
5297 continue;
5298 o1 = decode[i]>>11;
5299 o2 = (decode[i]>>7) & 0xF;
5300 i2 = 16*mlevel1[o1] + o2;
5301 if (mlevel2[i2] == 0xFF)
5302 mlevel2[i2] = count3++;
5303 o3 = decode[i] & 0x7F;
5304 i3 = 128*mlevel2[i2] + o3;
5305 mlevel3[i3] = i;
5306 }
5307 return result;
5308}
5309
5310static int
5311encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
5312{
5313 struct encoding_map *map = (struct encoding_map*)mapping;
5314 int l1 = c>>11;
5315 int l2 = (c>>7) & 0xF;
5316 int l3 = c & 0x7F;
5317 int i;
5318
5319#ifdef Py_UNICODE_WIDE
5320 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005321 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005322 }
5323#endif
5324 if (c == 0)
5325 return 0;
5326 /* level 1*/
5327 i = map->level1[l1];
5328 if (i == 0xFF) {
5329 return -1;
5330 }
5331 /* level 2*/
5332 i = map->level23[16*i+l2];
5333 if (i == 0xFF) {
5334 return -1;
5335 }
5336 /* level 3 */
5337 i = map->level23[16*map->count2 + 128*i + l3];
5338 if (i == 0) {
5339 return -1;
5340 }
5341 return i;
5342}
5343
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005344/* Lookup the character ch in the mapping. If the character
5345 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00005346 error occurred). */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005347static PyObject *charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005348{
Christian Heimes217cfd12007-12-02 14:31:20 +00005349 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005350 PyObject *x;
5351
5352 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005353 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005354 x = PyObject_GetItem(mapping, w);
5355 Py_DECREF(w);
5356 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005357 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5358 /* No mapping found means: mapping is undefined. */
5359 PyErr_Clear();
5360 x = Py_None;
5361 Py_INCREF(x);
5362 return x;
5363 } else
5364 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005365 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00005366 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00005367 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00005368 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005369 long value = PyLong_AS_LONG(x);
5370 if (value < 0 || value > 255) {
5371 PyErr_SetString(PyExc_TypeError,
5372 "character mapping must be in range(256)");
5373 Py_DECREF(x);
5374 return NULL;
5375 }
5376 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005377 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005378 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00005379 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005380 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005381 /* wrong return value */
5382 PyErr_Format(PyExc_TypeError,
5383 "character mapping must return integer, bytes or None, not %.400s",
5384 x->ob_type->tp_name);
5385 Py_DECREF(x);
5386 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005387 }
5388}
5389
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005390static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00005391charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005392{
Benjamin Peterson14339b62009-01-31 16:36:08 +00005393 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
5394 /* exponentially overallocate to minimize reallocations */
5395 if (requiredsize < 2*outsize)
5396 requiredsize = 2*outsize;
5397 if (_PyBytes_Resize(outobj, requiredsize))
5398 return -1;
5399 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005400}
5401
Benjamin Peterson14339b62009-01-31 16:36:08 +00005402typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00005403 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005404}charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005405/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00005406 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005407 space is available. Return a new reference to the object that
5408 was put in the output buffer, or Py_None, if the mapping was undefined
5409 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00005410 reallocation error occurred. The caller must decref the result */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005411static
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005412charmapencode_result charmapencode_output(Py_UNICODE c, PyObject *mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00005413 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005414{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005415 PyObject *rep;
5416 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00005417 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005418
Christian Heimes90aa7642007-12-19 02:45:37 +00005419 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005420 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00005421 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005422 if (res == -1)
5423 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00005424 if (outsize<requiredsize)
5425 if (charmapencode_resize(outobj, outpos, requiredsize))
5426 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00005427 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005428 outstart[(*outpos)++] = (char)res;
5429 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005430 }
5431
5432 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005433 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005434 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005435 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005436 Py_DECREF(rep);
5437 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005438 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005439 if (PyLong_Check(rep)) {
5440 Py_ssize_t requiredsize = *outpos+1;
5441 if (outsize<requiredsize)
5442 if (charmapencode_resize(outobj, outpos, requiredsize)) {
5443 Py_DECREF(rep);
5444 return enc_EXCEPTION;
5445 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005446 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005447 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005448 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005449 else {
5450 const char *repchars = PyBytes_AS_STRING(rep);
5451 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
5452 Py_ssize_t requiredsize = *outpos+repsize;
5453 if (outsize<requiredsize)
5454 if (charmapencode_resize(outobj, outpos, requiredsize)) {
5455 Py_DECREF(rep);
5456 return enc_EXCEPTION;
5457 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005458 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005459 memcpy(outstart + *outpos, repchars, repsize);
5460 *outpos += repsize;
5461 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005462 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005463 Py_DECREF(rep);
5464 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005465}
5466
5467/* handle an error in PyUnicode_EncodeCharmap
5468 Return 0 on success, -1 on error */
5469static
5470int charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00005471 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005472 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00005473 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00005474 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005475{
5476 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005477 Py_ssize_t repsize;
5478 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005479 Py_UNICODE *uni2;
5480 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005481 Py_ssize_t collstartpos = *inpos;
5482 Py_ssize_t collendpos = *inpos+1;
5483 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005484 char *encoding = "charmap";
5485 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005486 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005487
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005488 /* find all unencodable characters */
5489 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005490 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00005491 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005492 int res = encoding_map_lookup(p[collendpos], mapping);
5493 if (res != -1)
5494 break;
5495 ++collendpos;
5496 continue;
5497 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005498
Benjamin Peterson29060642009-01-31 22:14:21 +00005499 rep = charmapencode_lookup(p[collendpos], mapping);
5500 if (rep==NULL)
5501 return -1;
5502 else if (rep!=Py_None) {
5503 Py_DECREF(rep);
5504 break;
5505 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005506 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00005507 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005508 }
5509 /* cache callback name lookup
5510 * (if not done yet, i.e. it's the first error) */
5511 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005512 if ((errors==NULL) || (!strcmp(errors, "strict")))
5513 *known_errorHandler = 1;
5514 else if (!strcmp(errors, "replace"))
5515 *known_errorHandler = 2;
5516 else if (!strcmp(errors, "ignore"))
5517 *known_errorHandler = 3;
5518 else if (!strcmp(errors, "xmlcharrefreplace"))
5519 *known_errorHandler = 4;
5520 else
5521 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005522 }
5523 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005524 case 1: /* strict */
5525 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5526 return -1;
5527 case 2: /* replace */
5528 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005529 x = charmapencode_output('?', mapping, res, respos);
5530 if (x==enc_EXCEPTION) {
5531 return -1;
5532 }
5533 else if (x==enc_FAILED) {
5534 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5535 return -1;
5536 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005537 }
5538 /* fall through */
5539 case 3: /* ignore */
5540 *inpos = collendpos;
5541 break;
5542 case 4: /* xmlcharrefreplace */
5543 /* generate replacement (temporarily (mis)uses p) */
5544 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005545 char buffer[2+29+1+1];
5546 char *cp;
5547 sprintf(buffer, "&#%d;", (int)p[collpos]);
5548 for (cp = buffer; *cp; ++cp) {
5549 x = charmapencode_output(*cp, mapping, res, respos);
5550 if (x==enc_EXCEPTION)
5551 return -1;
5552 else if (x==enc_FAILED) {
5553 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5554 return -1;
5555 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005556 }
5557 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005558 *inpos = collendpos;
5559 break;
5560 default:
5561 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00005562 encoding, reason, p, size, exceptionObject,
5563 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005564 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005565 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005566 if (PyBytes_Check(repunicode)) {
5567 /* Directly copy bytes result to output. */
5568 Py_ssize_t outsize = PyBytes_Size(*res);
5569 Py_ssize_t requiredsize;
5570 repsize = PyBytes_Size(repunicode);
5571 requiredsize = *respos + repsize;
5572 if (requiredsize > outsize)
5573 /* Make room for all additional bytes. */
5574 if (charmapencode_resize(res, respos, requiredsize)) {
5575 Py_DECREF(repunicode);
5576 return -1;
5577 }
5578 memcpy(PyBytes_AsString(*res) + *respos,
5579 PyBytes_AsString(repunicode), repsize);
5580 *respos += repsize;
5581 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005582 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00005583 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005584 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005585 /* generate replacement */
5586 repsize = PyUnicode_GET_SIZE(repunicode);
5587 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005588 x = charmapencode_output(*uni2, mapping, res, respos);
5589 if (x==enc_EXCEPTION) {
5590 return -1;
5591 }
5592 else if (x==enc_FAILED) {
5593 Py_DECREF(repunicode);
5594 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5595 return -1;
5596 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005597 }
5598 *inpos = newpos;
5599 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005600 }
5601 return 0;
5602}
5603
Guido van Rossumd57fd912000-03-10 22:53:23 +00005604PyObject *PyUnicode_EncodeCharmap(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00005605 Py_ssize_t size,
5606 PyObject *mapping,
5607 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005608{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005609 /* output object */
5610 PyObject *res = NULL;
5611 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005612 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005613 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005614 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005615 PyObject *errorHandler = NULL;
5616 PyObject *exc = NULL;
5617 /* the following variable is used for caching string comparisons
5618 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
5619 * 3=ignore, 4=xmlcharrefreplace */
5620 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005621
5622 /* Default to Latin-1 */
5623 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005624 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005625
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005626 /* allocate enough for a simple encoding without
5627 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00005628 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005629 if (res == NULL)
5630 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00005631 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005632 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005633
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005634 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005635 /* try to encode it */
5636 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
5637 if (x==enc_EXCEPTION) /* error */
5638 goto onError;
5639 if (x==enc_FAILED) { /* unencodable character */
5640 if (charmap_encoding_error(p, size, &inpos, mapping,
5641 &exc,
5642 &known_errorHandler, &errorHandler, errors,
5643 &res, &respos)) {
5644 goto onError;
5645 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005646 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005647 else
5648 /* done with this character => adjust input position */
5649 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005650 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005651
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005652 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00005653 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005654 if (_PyBytes_Resize(&res, respos) < 0)
5655 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005656
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005657 Py_XDECREF(exc);
5658 Py_XDECREF(errorHandler);
5659 return res;
5660
Benjamin Peterson29060642009-01-31 22:14:21 +00005661 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005662 Py_XDECREF(res);
5663 Py_XDECREF(exc);
5664 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005665 return NULL;
5666}
5667
5668PyObject *PyUnicode_AsCharmapString(PyObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00005669 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005670{
5671 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005672 PyErr_BadArgument();
5673 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005674 }
5675 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005676 PyUnicode_GET_SIZE(unicode),
5677 mapping,
5678 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005679}
5680
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005681/* create or adjust a UnicodeTranslateError */
5682static void make_translate_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005683 const Py_UNICODE *unicode, Py_ssize_t size,
5684 Py_ssize_t startpos, Py_ssize_t endpos,
5685 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005686{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005687 if (*exceptionObject == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005688 *exceptionObject = PyUnicodeTranslateError_Create(
Benjamin Peterson29060642009-01-31 22:14:21 +00005689 unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005690 }
5691 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005692 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
5693 goto onError;
5694 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
5695 goto onError;
5696 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
5697 goto onError;
5698 return;
5699 onError:
5700 Py_DECREF(*exceptionObject);
5701 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005702 }
5703}
5704
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005705/* raises a UnicodeTranslateError */
5706static void raise_translate_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005707 const Py_UNICODE *unicode, Py_ssize_t size,
5708 Py_ssize_t startpos, Py_ssize_t endpos,
5709 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005710{
5711 make_translate_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005712 unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005713 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005714 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005715}
5716
5717/* error handling callback helper:
5718 build arguments, call the callback and check the arguments,
5719 put the result into newpos and return the replacement string, which
5720 has to be freed by the caller */
5721static PyObject *unicode_translate_call_errorhandler(const char *errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00005722 PyObject **errorHandler,
5723 const char *reason,
5724 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
5725 Py_ssize_t startpos, Py_ssize_t endpos,
5726 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005727{
Benjamin Peterson142957c2008-07-04 19:55:29 +00005728 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005729
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005730 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005731 PyObject *restuple;
5732 PyObject *resunicode;
5733
5734 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005735 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005736 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005737 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005738 }
5739
5740 make_translate_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005741 unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005742 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005743 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005744
5745 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00005746 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005747 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005748 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005749 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00005750 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00005751 Py_DECREF(restuple);
5752 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005753 }
5754 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00005755 &resunicode, &i_newpos)) {
5756 Py_DECREF(restuple);
5757 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005758 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00005759 if (i_newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005760 *newpos = size+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005761 else
5762 *newpos = i_newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005763 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005764 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
5765 Py_DECREF(restuple);
5766 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005767 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005768 Py_INCREF(resunicode);
5769 Py_DECREF(restuple);
5770 return resunicode;
5771}
5772
5773/* Lookup the character ch in the mapping and put the result in result,
5774 which must be decrefed by the caller.
5775 Return 0 on success, -1 on error */
5776static
5777int charmaptranslate_lookup(Py_UNICODE c, PyObject *mapping, PyObject **result)
5778{
Christian Heimes217cfd12007-12-02 14:31:20 +00005779 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005780 PyObject *x;
5781
5782 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005783 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005784 x = PyObject_GetItem(mapping, w);
5785 Py_DECREF(w);
5786 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005787 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5788 /* No mapping found means: use 1:1 mapping. */
5789 PyErr_Clear();
5790 *result = NULL;
5791 return 0;
5792 } else
5793 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005794 }
5795 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005796 *result = x;
5797 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005798 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005799 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005800 long value = PyLong_AS_LONG(x);
5801 long max = PyUnicode_GetMax();
5802 if (value < 0 || value > max) {
5803 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00005804 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00005805 Py_DECREF(x);
5806 return -1;
5807 }
5808 *result = x;
5809 return 0;
5810 }
5811 else if (PyUnicode_Check(x)) {
5812 *result = x;
5813 return 0;
5814 }
5815 else {
5816 /* wrong return value */
5817 PyErr_SetString(PyExc_TypeError,
5818 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00005819 Py_DECREF(x);
5820 return -1;
5821 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005822}
5823/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00005824 if not reallocate and adjust various state variables.
5825 Return 0 on success, -1 on error */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005826static
Walter Dörwald4894c302003-10-24 14:25:28 +00005827int charmaptranslate_makespace(PyObject **outobj, Py_UNICODE **outp,
Benjamin Peterson29060642009-01-31 22:14:21 +00005828 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005829{
Martin v. Löwis18e16552006-02-15 17:27:45 +00005830 Py_ssize_t oldsize = PyUnicode_GET_SIZE(*outobj);
Walter Dörwald4894c302003-10-24 14:25:28 +00005831 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005832 /* remember old output position */
5833 Py_ssize_t outpos = *outp-PyUnicode_AS_UNICODE(*outobj);
5834 /* exponentially overallocate to minimize reallocations */
5835 if (requiredsize < 2 * oldsize)
5836 requiredsize = 2 * oldsize;
5837 if (PyUnicode_Resize(outobj, requiredsize) < 0)
5838 return -1;
5839 *outp = PyUnicode_AS_UNICODE(*outobj) + outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005840 }
5841 return 0;
5842}
5843/* lookup the character, put the result in the output string and adjust
5844 various state variables. Return a new reference to the object that
5845 was put in the output buffer in *result, or Py_None, if the mapping was
5846 undefined (in which case no character was written).
5847 The called must decref result.
5848 Return 0 on success, -1 on error. */
5849static
Walter Dörwald4894c302003-10-24 14:25:28 +00005850int charmaptranslate_output(const Py_UNICODE *startinp, const Py_UNICODE *curinp,
Benjamin Peterson29060642009-01-31 22:14:21 +00005851 Py_ssize_t insize, PyObject *mapping, PyObject **outobj, Py_UNICODE **outp,
5852 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005853{
Walter Dörwald4894c302003-10-24 14:25:28 +00005854 if (charmaptranslate_lookup(*curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00005855 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005856 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005857 /* not found => default to 1:1 mapping */
5858 *(*outp)++ = *curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005859 }
5860 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00005861 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00005862 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005863 /* no overflow check, because we know that the space is enough */
5864 *(*outp)++ = (Py_UNICODE)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005865 }
5866 else if (PyUnicode_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005867 Py_ssize_t repsize = PyUnicode_GET_SIZE(*res);
5868 if (repsize==1) {
5869 /* no overflow check, because we know that the space is enough */
5870 *(*outp)++ = *PyUnicode_AS_UNICODE(*res);
5871 }
5872 else if (repsize!=0) {
5873 /* more than one character */
5874 Py_ssize_t requiredsize = (*outp-PyUnicode_AS_UNICODE(*outobj)) +
5875 (insize - (curinp-startinp)) +
5876 repsize - 1;
5877 if (charmaptranslate_makespace(outobj, outp, requiredsize))
5878 return -1;
5879 memcpy(*outp, PyUnicode_AS_UNICODE(*res), sizeof(Py_UNICODE)*repsize);
5880 *outp += repsize;
5881 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005882 }
5883 else
Benjamin Peterson29060642009-01-31 22:14:21 +00005884 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005885 return 0;
5886}
5887
5888PyObject *PyUnicode_TranslateCharmap(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00005889 Py_ssize_t size,
5890 PyObject *mapping,
5891 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005892{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005893 /* output object */
5894 PyObject *res = NULL;
5895 /* pointers to the beginning and end+1 of input */
5896 const Py_UNICODE *startp = p;
5897 const Py_UNICODE *endp = p + size;
5898 /* pointer into the output */
5899 Py_UNICODE *str;
5900 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005901 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005902 char *reason = "character maps to <undefined>";
5903 PyObject *errorHandler = NULL;
5904 PyObject *exc = NULL;
5905 /* the following variable is used for caching string comparisons
5906 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
5907 * 3=ignore, 4=xmlcharrefreplace */
5908 int known_errorHandler = -1;
5909
Guido van Rossumd57fd912000-03-10 22:53:23 +00005910 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005911 PyErr_BadArgument();
5912 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005913 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005914
5915 /* allocate enough for a simple 1:1 translation without
5916 replacements, if we need more, we'll resize */
5917 res = PyUnicode_FromUnicode(NULL, size);
5918 if (res == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005919 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005920 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005921 return res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005922 str = PyUnicode_AS_UNICODE(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005923
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005924 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005925 /* try to encode it */
5926 PyObject *x = NULL;
5927 if (charmaptranslate_output(startp, p, size, mapping, &res, &str, &x)) {
5928 Py_XDECREF(x);
5929 goto onError;
5930 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005931 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00005932 if (x!=Py_None) /* it worked => adjust input pointer */
5933 ++p;
5934 else { /* untranslatable character */
5935 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
5936 Py_ssize_t repsize;
5937 Py_ssize_t newpos;
5938 Py_UNICODE *uni2;
5939 /* startpos for collecting untranslatable chars */
5940 const Py_UNICODE *collstart = p;
5941 const Py_UNICODE *collend = p+1;
5942 const Py_UNICODE *coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005943
Benjamin Peterson29060642009-01-31 22:14:21 +00005944 /* find all untranslatable characters */
5945 while (collend < endp) {
5946 if (charmaptranslate_lookup(*collend, mapping, &x))
5947 goto onError;
5948 Py_XDECREF(x);
5949 if (x!=Py_None)
5950 break;
5951 ++collend;
5952 }
5953 /* cache callback name lookup
5954 * (if not done yet, i.e. it's the first error) */
5955 if (known_errorHandler==-1) {
5956 if ((errors==NULL) || (!strcmp(errors, "strict")))
5957 known_errorHandler = 1;
5958 else if (!strcmp(errors, "replace"))
5959 known_errorHandler = 2;
5960 else if (!strcmp(errors, "ignore"))
5961 known_errorHandler = 3;
5962 else if (!strcmp(errors, "xmlcharrefreplace"))
5963 known_errorHandler = 4;
5964 else
5965 known_errorHandler = 0;
5966 }
5967 switch (known_errorHandler) {
5968 case 1: /* strict */
5969 raise_translate_exception(&exc, startp, size, collstart-startp, collend-startp, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005970 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005971 case 2: /* replace */
5972 /* No need to check for space, this is a 1:1 replacement */
5973 for (coll = collstart; coll<collend; ++coll)
5974 *str++ = '?';
5975 /* fall through */
5976 case 3: /* ignore */
5977 p = collend;
5978 break;
5979 case 4: /* xmlcharrefreplace */
5980 /* generate replacement (temporarily (mis)uses p) */
5981 for (p = collstart; p < collend; ++p) {
5982 char buffer[2+29+1+1];
5983 char *cp;
5984 sprintf(buffer, "&#%d;", (int)*p);
5985 if (charmaptranslate_makespace(&res, &str,
5986 (str-PyUnicode_AS_UNICODE(res))+strlen(buffer)+(endp-collend)))
5987 goto onError;
5988 for (cp = buffer; *cp; ++cp)
5989 *str++ = *cp;
5990 }
5991 p = collend;
5992 break;
5993 default:
5994 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
5995 reason, startp, size, &exc,
5996 collstart-startp, collend-startp, &newpos);
5997 if (repunicode == NULL)
5998 goto onError;
5999 /* generate replacement */
6000 repsize = PyUnicode_GET_SIZE(repunicode);
6001 if (charmaptranslate_makespace(&res, &str,
6002 (str-PyUnicode_AS_UNICODE(res))+repsize+(endp-collend))) {
6003 Py_DECREF(repunicode);
6004 goto onError;
6005 }
6006 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2)
6007 *str++ = *uni2;
6008 p = startp + newpos;
6009 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006010 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006011 }
6012 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006013 /* Resize if we allocated to much */
6014 respos = str-PyUnicode_AS_UNICODE(res);
Walter Dörwald4894c302003-10-24 14:25:28 +00006015 if (respos<PyUnicode_GET_SIZE(res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006016 if (PyUnicode_Resize(&res, respos) < 0)
6017 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006018 }
6019 Py_XDECREF(exc);
6020 Py_XDECREF(errorHandler);
6021 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006022
Benjamin Peterson29060642009-01-31 22:14:21 +00006023 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006024 Py_XDECREF(res);
6025 Py_XDECREF(exc);
6026 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006027 return NULL;
6028}
6029
6030PyObject *PyUnicode_Translate(PyObject *str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006031 PyObject *mapping,
6032 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006033{
6034 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00006035
Guido van Rossumd57fd912000-03-10 22:53:23 +00006036 str = PyUnicode_FromObject(str);
6037 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006038 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039 result = PyUnicode_TranslateCharmap(PyUnicode_AS_UNICODE(str),
Benjamin Peterson29060642009-01-31 22:14:21 +00006040 PyUnicode_GET_SIZE(str),
6041 mapping,
6042 errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006043 Py_DECREF(str);
6044 return result;
Tim Petersced69f82003-09-16 20:30:58 +00006045
Benjamin Peterson29060642009-01-31 22:14:21 +00006046 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006047 Py_XDECREF(str);
6048 return NULL;
6049}
Tim Petersced69f82003-09-16 20:30:58 +00006050
Guido van Rossum9e896b32000-04-05 20:11:21 +00006051/* --- Decimal Encoder ---------------------------------------------------- */
6052
6053int PyUnicode_EncodeDecimal(Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00006054 Py_ssize_t length,
6055 char *output,
6056 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00006057{
6058 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006059 PyObject *errorHandler = NULL;
6060 PyObject *exc = NULL;
6061 const char *encoding = "decimal";
6062 const char *reason = "invalid decimal Unicode string";
6063 /* the following variable is used for caching string comparisons
6064 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6065 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00006066
6067 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006068 PyErr_BadArgument();
6069 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00006070 }
6071
6072 p = s;
6073 end = s + length;
6074 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006075 register Py_UNICODE ch = *p;
6076 int decimal;
6077 PyObject *repunicode;
6078 Py_ssize_t repsize;
6079 Py_ssize_t newpos;
6080 Py_UNICODE *uni2;
6081 Py_UNICODE *collstart;
6082 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00006083
Benjamin Peterson29060642009-01-31 22:14:21 +00006084 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006085 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00006086 ++p;
6087 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006088 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006089 decimal = Py_UNICODE_TODECIMAL(ch);
6090 if (decimal >= 0) {
6091 *output++ = '0' + decimal;
6092 ++p;
6093 continue;
6094 }
6095 if (0 < ch && ch < 256) {
6096 *output++ = (char)ch;
6097 ++p;
6098 continue;
6099 }
6100 /* All other characters are considered unencodable */
6101 collstart = p;
6102 collend = p+1;
6103 while (collend < end) {
6104 if ((0 < *collend && *collend < 256) ||
6105 !Py_UNICODE_ISSPACE(*collend) ||
6106 Py_UNICODE_TODECIMAL(*collend))
6107 break;
6108 }
6109 /* cache callback name lookup
6110 * (if not done yet, i.e. it's the first error) */
6111 if (known_errorHandler==-1) {
6112 if ((errors==NULL) || (!strcmp(errors, "strict")))
6113 known_errorHandler = 1;
6114 else if (!strcmp(errors, "replace"))
6115 known_errorHandler = 2;
6116 else if (!strcmp(errors, "ignore"))
6117 known_errorHandler = 3;
6118 else if (!strcmp(errors, "xmlcharrefreplace"))
6119 known_errorHandler = 4;
6120 else
6121 known_errorHandler = 0;
6122 }
6123 switch (known_errorHandler) {
6124 case 1: /* strict */
6125 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
6126 goto onError;
6127 case 2: /* replace */
6128 for (p = collstart; p < collend; ++p)
6129 *output++ = '?';
6130 /* fall through */
6131 case 3: /* ignore */
6132 p = collend;
6133 break;
6134 case 4: /* xmlcharrefreplace */
6135 /* generate replacement (temporarily (mis)uses p) */
6136 for (p = collstart; p < collend; ++p)
6137 output += sprintf(output, "&#%d;", (int)*p);
6138 p = collend;
6139 break;
6140 default:
6141 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
6142 encoding, reason, s, length, &exc,
6143 collstart-s, collend-s, &newpos);
6144 if (repunicode == NULL)
6145 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006146 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006147 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006148 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
6149 Py_DECREF(repunicode);
6150 goto onError;
6151 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006152 /* generate replacement */
6153 repsize = PyUnicode_GET_SIZE(repunicode);
6154 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
6155 Py_UNICODE ch = *uni2;
6156 if (Py_UNICODE_ISSPACE(ch))
6157 *output++ = ' ';
6158 else {
6159 decimal = Py_UNICODE_TODECIMAL(ch);
6160 if (decimal >= 0)
6161 *output++ = '0' + decimal;
6162 else if (0 < ch && ch < 256)
6163 *output++ = (char)ch;
6164 else {
6165 Py_DECREF(repunicode);
6166 raise_encode_exception(&exc, encoding,
6167 s, length, collstart-s, collend-s, reason);
6168 goto onError;
6169 }
6170 }
6171 }
6172 p = s + newpos;
6173 Py_DECREF(repunicode);
6174 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00006175 }
6176 /* 0-terminate the output string */
6177 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006178 Py_XDECREF(exc);
6179 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00006180 return 0;
6181
Benjamin Peterson29060642009-01-31 22:14:21 +00006182 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006183 Py_XDECREF(exc);
6184 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00006185 return -1;
6186}
6187
Guido van Rossumd57fd912000-03-10 22:53:23 +00006188/* --- Helpers ------------------------------------------------------------ */
6189
Eric Smith8c663262007-08-25 02:26:07 +00006190#include "stringlib/unicodedefs.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00006191#include "stringlib/fastsearch.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006192
Thomas Wouters477c8d52006-05-27 19:21:47 +00006193#include "stringlib/count.h"
6194#include "stringlib/find.h"
6195#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006196#include "stringlib/split.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00006197
Eric Smith5807c412008-05-11 21:00:57 +00006198#define _Py_InsertThousandsGrouping _PyUnicode_InsertThousandsGrouping
Eric Smitha3b1ac82009-04-03 14:45:06 +00006199#define _Py_InsertThousandsGroupingLocale _PyUnicode_InsertThousandsGroupingLocale
Eric Smith5807c412008-05-11 21:00:57 +00006200#include "stringlib/localeutil.h"
6201
Thomas Wouters477c8d52006-05-27 19:21:47 +00006202/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006203#define ADJUST_INDICES(start, end, len) \
6204 if (end > len) \
6205 end = len; \
6206 else if (end < 0) { \
6207 end += len; \
6208 if (end < 0) \
6209 end = 0; \
6210 } \
6211 if (start < 0) { \
6212 start += len; \
6213 if (start < 0) \
6214 start = 0; \
6215 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00006216
Martin v. Löwis18e16552006-02-15 17:27:45 +00006217Py_ssize_t PyUnicode_Count(PyObject *str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00006218 PyObject *substr,
6219 Py_ssize_t start,
6220 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006221{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006222 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006223 PyUnicodeObject* str_obj;
6224 PyUnicodeObject* sub_obj;
Tim Petersced69f82003-09-16 20:30:58 +00006225
Thomas Wouters477c8d52006-05-27 19:21:47 +00006226 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
6227 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00006228 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006229 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
6230 if (!sub_obj) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006231 Py_DECREF(str_obj);
6232 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006233 }
Tim Petersced69f82003-09-16 20:30:58 +00006234
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006235 ADJUST_INDICES(start, end, str_obj->length);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006236 result = stringlib_count(
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006237 str_obj->str + start, end - start, sub_obj->str, sub_obj->length,
6238 PY_SSIZE_T_MAX
Thomas Wouters477c8d52006-05-27 19:21:47 +00006239 );
6240
6241 Py_DECREF(sub_obj);
6242 Py_DECREF(str_obj);
6243
Guido van Rossumd57fd912000-03-10 22:53:23 +00006244 return result;
6245}
6246
Martin v. Löwis18e16552006-02-15 17:27:45 +00006247Py_ssize_t PyUnicode_Find(PyObject *str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00006248 PyObject *sub,
6249 Py_ssize_t start,
6250 Py_ssize_t end,
6251 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006252{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006253 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00006254
Guido van Rossumd57fd912000-03-10 22:53:23 +00006255 str = PyUnicode_FromObject(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006256 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00006257 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006258 sub = PyUnicode_FromObject(sub);
6259 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006260 Py_DECREF(str);
6261 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006262 }
Tim Petersced69f82003-09-16 20:30:58 +00006263
Thomas Wouters477c8d52006-05-27 19:21:47 +00006264 if (direction > 0)
6265 result = stringlib_find_slice(
6266 PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
6267 PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
6268 start, end
6269 );
6270 else
6271 result = stringlib_rfind_slice(
6272 PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
6273 PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
6274 start, end
6275 );
6276
Guido van Rossumd57fd912000-03-10 22:53:23 +00006277 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006278 Py_DECREF(sub);
6279
Guido van Rossumd57fd912000-03-10 22:53:23 +00006280 return result;
6281}
6282
Tim Petersced69f82003-09-16 20:30:58 +00006283static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006284int tailmatch(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006285 PyUnicodeObject *substring,
6286 Py_ssize_t start,
6287 Py_ssize_t end,
6288 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006289{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006290 if (substring->length == 0)
6291 return 1;
6292
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006293 ADJUST_INDICES(start, end, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006294 end -= substring->length;
6295 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00006296 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006297
6298 if (direction > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006299 if (Py_UNICODE_MATCH(self, end, substring))
6300 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006301 } else {
6302 if (Py_UNICODE_MATCH(self, start, substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00006303 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006304 }
6305
6306 return 0;
6307}
6308
Martin v. Löwis18e16552006-02-15 17:27:45 +00006309Py_ssize_t PyUnicode_Tailmatch(PyObject *str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006310 PyObject *substr,
6311 Py_ssize_t start,
6312 Py_ssize_t end,
6313 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006314{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006315 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00006316
Guido van Rossumd57fd912000-03-10 22:53:23 +00006317 str = PyUnicode_FromObject(str);
6318 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006319 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006320 substr = PyUnicode_FromObject(substr);
6321 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006322 Py_DECREF(str);
6323 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006324 }
Tim Petersced69f82003-09-16 20:30:58 +00006325
Guido van Rossumd57fd912000-03-10 22:53:23 +00006326 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006327 (PyUnicodeObject *)substr,
6328 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006329 Py_DECREF(str);
6330 Py_DECREF(substr);
6331 return result;
6332}
6333
Guido van Rossumd57fd912000-03-10 22:53:23 +00006334/* Apply fixfct filter to the Unicode object self and return a
6335 reference to the modified object */
6336
Tim Petersced69f82003-09-16 20:30:58 +00006337static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006338PyObject *fixup(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006339 int (*fixfct)(PyUnicodeObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00006340{
6341
6342 PyUnicodeObject *u;
6343
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006344 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006345 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006346 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006347
6348 Py_UNICODE_COPY(u->str, self->str, self->length);
6349
Tim Peters7a29bd52001-09-12 03:03:31 +00006350 if (!fixfct(u) && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006351 /* fixfct should return TRUE if it modified the buffer. If
6352 FALSE, return a reference to the original buffer instead
6353 (to save space, not time) */
6354 Py_INCREF(self);
6355 Py_DECREF(u);
6356 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006357 }
6358 return (PyObject*) u;
6359}
6360
Tim Petersced69f82003-09-16 20:30:58 +00006361static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006362int fixupper(PyUnicodeObject *self)
6363{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006364 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006365 Py_UNICODE *s = self->str;
6366 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006367
Guido van Rossumd57fd912000-03-10 22:53:23 +00006368 while (len-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006369 register Py_UNICODE ch;
Tim Petersced69f82003-09-16 20:30:58 +00006370
Benjamin Peterson29060642009-01-31 22:14:21 +00006371 ch = Py_UNICODE_TOUPPER(*s);
6372 if (ch != *s) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006373 status = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006374 *s = ch;
6375 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006376 s++;
6377 }
6378
6379 return status;
6380}
6381
Tim Petersced69f82003-09-16 20:30:58 +00006382static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006383int fixlower(PyUnicodeObject *self)
6384{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006385 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006386 Py_UNICODE *s = self->str;
6387 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006388
Guido van Rossumd57fd912000-03-10 22:53:23 +00006389 while (len-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006390 register Py_UNICODE ch;
Tim Petersced69f82003-09-16 20:30:58 +00006391
Benjamin Peterson29060642009-01-31 22:14:21 +00006392 ch = Py_UNICODE_TOLOWER(*s);
6393 if (ch != *s) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006394 status = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006395 *s = ch;
6396 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006397 s++;
6398 }
6399
6400 return status;
6401}
6402
Tim Petersced69f82003-09-16 20:30:58 +00006403static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006404int fixswapcase(PyUnicodeObject *self)
6405{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006406 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006407 Py_UNICODE *s = self->str;
6408 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006409
Guido van Rossumd57fd912000-03-10 22:53:23 +00006410 while (len-- > 0) {
6411 if (Py_UNICODE_ISUPPER(*s)) {
6412 *s = Py_UNICODE_TOLOWER(*s);
6413 status = 1;
6414 } else if (Py_UNICODE_ISLOWER(*s)) {
6415 *s = Py_UNICODE_TOUPPER(*s);
6416 status = 1;
6417 }
6418 s++;
6419 }
6420
6421 return status;
6422}
6423
Tim Petersced69f82003-09-16 20:30:58 +00006424static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006425int fixcapitalize(PyUnicodeObject *self)
6426{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006427 Py_ssize_t len = self->length;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006428 Py_UNICODE *s = self->str;
6429 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006430
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006431 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006432 return 0;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006433 if (Py_UNICODE_ISLOWER(*s)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006434 *s = Py_UNICODE_TOUPPER(*s);
6435 status = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006436 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006437 s++;
6438 while (--len > 0) {
6439 if (Py_UNICODE_ISUPPER(*s)) {
6440 *s = Py_UNICODE_TOLOWER(*s);
6441 status = 1;
6442 }
6443 s++;
6444 }
6445 return status;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006446}
6447
6448static
6449int fixtitle(PyUnicodeObject *self)
6450{
6451 register Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
6452 register Py_UNICODE *e;
6453 int previous_is_cased;
6454
6455 /* Shortcut for single character strings */
6456 if (PyUnicode_GET_SIZE(self) == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006457 Py_UNICODE ch = Py_UNICODE_TOTITLE(*p);
6458 if (*p != ch) {
6459 *p = ch;
6460 return 1;
6461 }
6462 else
6463 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006464 }
Tim Petersced69f82003-09-16 20:30:58 +00006465
Guido van Rossumd57fd912000-03-10 22:53:23 +00006466 e = p + PyUnicode_GET_SIZE(self);
6467 previous_is_cased = 0;
6468 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006469 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00006470
Benjamin Peterson29060642009-01-31 22:14:21 +00006471 if (previous_is_cased)
6472 *p = Py_UNICODE_TOLOWER(ch);
6473 else
6474 *p = Py_UNICODE_TOTITLE(ch);
Tim Petersced69f82003-09-16 20:30:58 +00006475
Benjamin Peterson29060642009-01-31 22:14:21 +00006476 if (Py_UNICODE_ISLOWER(ch) ||
6477 Py_UNICODE_ISUPPER(ch) ||
6478 Py_UNICODE_ISTITLE(ch))
6479 previous_is_cased = 1;
6480 else
6481 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006482 }
6483 return 1;
6484}
6485
Tim Peters8ce9f162004-08-27 01:49:32 +00006486PyObject *
6487PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006488{
Skip Montanaro6543b452004-09-16 03:28:13 +00006489 const Py_UNICODE blank = ' ';
6490 const Py_UNICODE *sep = &blank;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006491 Py_ssize_t seplen = 1;
Tim Peters05eba1f2004-08-27 21:32:02 +00006492 PyUnicodeObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00006493 Py_UNICODE *res_p; /* pointer to free byte in res's string area */
6494 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006495 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
6496 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00006497 PyObject *item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006498 Py_ssize_t sz, i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006499
Tim Peters05eba1f2004-08-27 21:32:02 +00006500 fseq = PySequence_Fast(seq, "");
6501 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006502 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00006503 }
6504
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006505 /* NOTE: the following code can't call back into Python code,
6506 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00006507 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006508
Tim Peters05eba1f2004-08-27 21:32:02 +00006509 seqlen = PySequence_Fast_GET_SIZE(fseq);
6510 /* If empty sequence, return u"". */
6511 if (seqlen == 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006512 res = _PyUnicode_New(0); /* empty sequence; return u"" */
6513 goto Done;
Tim Peters05eba1f2004-08-27 21:32:02 +00006514 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006515 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00006516 /* If singleton sequence with an exact Unicode, return that. */
6517 if (seqlen == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006518 item = items[0];
6519 if (PyUnicode_CheckExact(item)) {
6520 Py_INCREF(item);
6521 res = (PyUnicodeObject *)item;
6522 goto Done;
6523 }
Tim Peters8ce9f162004-08-27 01:49:32 +00006524 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006525 else {
6526 /* Set up sep and seplen */
6527 if (separator == NULL) {
6528 sep = &blank;
6529 seplen = 1;
Tim Peters05eba1f2004-08-27 21:32:02 +00006530 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006531 else {
6532 if (!PyUnicode_Check(separator)) {
6533 PyErr_Format(PyExc_TypeError,
6534 "separator: expected str instance,"
6535 " %.80s found",
6536 Py_TYPE(separator)->tp_name);
6537 goto onError;
6538 }
6539 sep = PyUnicode_AS_UNICODE(separator);
6540 seplen = PyUnicode_GET_SIZE(separator);
Tim Peters05eba1f2004-08-27 21:32:02 +00006541 }
6542 }
6543
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006544 /* There are at least two things to join, or else we have a subclass
6545 * of str in the sequence.
6546 * Do a pre-pass to figure out the total amount of space we'll
6547 * need (sz), and see whether all argument are strings.
6548 */
6549 sz = 0;
6550 for (i = 0; i < seqlen; i++) {
6551 const Py_ssize_t old_sz = sz;
6552 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00006553 if (!PyUnicode_Check(item)) {
6554 PyErr_Format(PyExc_TypeError,
6555 "sequence item %zd: expected str instance,"
6556 " %.80s found",
6557 i, Py_TYPE(item)->tp_name);
6558 goto onError;
6559 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006560 sz += PyUnicode_GET_SIZE(item);
6561 if (i != 0)
6562 sz += seplen;
6563 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
6564 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00006565 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006566 goto onError;
6567 }
6568 }
Tim Petersced69f82003-09-16 20:30:58 +00006569
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006570 res = _PyUnicode_New(sz);
6571 if (res == NULL)
6572 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00006573
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006574 /* Catenate everything. */
6575 res_p = PyUnicode_AS_UNICODE(res);
6576 for (i = 0; i < seqlen; ++i) {
6577 Py_ssize_t itemlen;
6578 item = items[i];
6579 itemlen = PyUnicode_GET_SIZE(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00006580 /* Copy item, and maybe the separator. */
6581 if (i) {
6582 Py_UNICODE_COPY(res_p, sep, seplen);
6583 res_p += seplen;
6584 }
6585 Py_UNICODE_COPY(res_p, PyUnicode_AS_UNICODE(item), itemlen);
6586 res_p += itemlen;
Tim Peters05eba1f2004-08-27 21:32:02 +00006587 }
Tim Peters8ce9f162004-08-27 01:49:32 +00006588
Benjamin Peterson29060642009-01-31 22:14:21 +00006589 Done:
Tim Peters05eba1f2004-08-27 21:32:02 +00006590 Py_DECREF(fseq);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006591 return (PyObject *)res;
6592
Benjamin Peterson29060642009-01-31 22:14:21 +00006593 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00006594 Py_DECREF(fseq);
Tim Peters8ce9f162004-08-27 01:49:32 +00006595 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006596 return NULL;
6597}
6598
Tim Petersced69f82003-09-16 20:30:58 +00006599static
6600PyUnicodeObject *pad(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006601 Py_ssize_t left,
6602 Py_ssize_t right,
6603 Py_UNICODE fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006604{
6605 PyUnicodeObject *u;
6606
6607 if (left < 0)
6608 left = 0;
6609 if (right < 0)
6610 right = 0;
6611
Tim Peters7a29bd52001-09-12 03:03:31 +00006612 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006613 Py_INCREF(self);
6614 return self;
6615 }
6616
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006617 if (left > PY_SSIZE_T_MAX - self->length ||
6618 right > PY_SSIZE_T_MAX - (left + self->length)) {
6619 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
6620 return NULL;
6621 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006622 u = _PyUnicode_New(left + self->length + right);
6623 if (u) {
6624 if (left)
6625 Py_UNICODE_FILL(u->str, fill, left);
6626 Py_UNICODE_COPY(u->str + left, self->str, self->length);
6627 if (right)
6628 Py_UNICODE_FILL(u->str + left + self->length, fill, right);
6629 }
6630
6631 return u;
6632}
6633
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006634PyObject *PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006635{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006636 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006637
6638 string = PyUnicode_FromObject(string);
6639 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006640 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006641
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006642 list = stringlib_splitlines(
6643 (PyObject*) string, PyUnicode_AS_UNICODE(string),
6644 PyUnicode_GET_SIZE(string), keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006645
6646 Py_DECREF(string);
6647 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006648}
6649
Tim Petersced69f82003-09-16 20:30:58 +00006650static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006651PyObject *split(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006652 PyUnicodeObject *substring,
6653 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006654{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006655 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006656 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006657
Guido van Rossumd57fd912000-03-10 22:53:23 +00006658 if (substring == NULL)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006659 return stringlib_split_whitespace(
6660 (PyObject*) self, self->str, self->length, maxcount
6661 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00006662
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006663 return stringlib_split(
6664 (PyObject*) self, self->str, self->length,
6665 substring->str, substring->length,
6666 maxcount
6667 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00006668}
6669
Tim Petersced69f82003-09-16 20:30:58 +00006670static
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006671PyObject *rsplit(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006672 PyUnicodeObject *substring,
6673 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006674{
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006675 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006676 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006677
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006678 if (substring == NULL)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006679 return stringlib_rsplit_whitespace(
6680 (PyObject*) self, self->str, self->length, maxcount
6681 );
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006682
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006683 return stringlib_rsplit(
6684 (PyObject*) self, self->str, self->length,
6685 substring->str, substring->length,
6686 maxcount
6687 );
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006688}
6689
6690static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006691PyObject *replace(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006692 PyUnicodeObject *str1,
6693 PyUnicodeObject *str2,
6694 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006695{
6696 PyUnicodeObject *u;
6697
6698 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006699 maxcount = PY_SSIZE_T_MAX;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006700 else if (maxcount == 0 || self->length == 0)
6701 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006702
Thomas Wouters477c8d52006-05-27 19:21:47 +00006703 if (str1->length == str2->length) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +00006704 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006705 /* same length */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006706 if (str1->length == 0)
6707 goto nothing;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006708 if (str1->length == 1) {
6709 /* replace characters */
6710 Py_UNICODE u1, u2;
6711 if (!findchar(self->str, self->length, str1->str[0]))
6712 goto nothing;
6713 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
6714 if (!u)
6715 return NULL;
6716 Py_UNICODE_COPY(u->str, self->str, self->length);
6717 u1 = str1->str[0];
6718 u2 = str2->str[0];
6719 for (i = 0; i < u->length; i++)
6720 if (u->str[i] == u1) {
6721 if (--maxcount < 0)
6722 break;
6723 u->str[i] = u2;
6724 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006725 } else {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006726 i = stringlib_find(
6727 self->str, self->length, str1->str, str1->length, 0
Guido van Rossumd57fd912000-03-10 22:53:23 +00006728 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00006729 if (i < 0)
6730 goto nothing;
6731 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
6732 if (!u)
6733 return NULL;
6734 Py_UNICODE_COPY(u->str, self->str, self->length);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006735
6736 /* change everything in-place, starting with this one */
6737 Py_UNICODE_COPY(u->str+i, str2->str, str2->length);
6738 i += str1->length;
6739
6740 while ( --maxcount > 0) {
6741 i = stringlib_find(self->str+i, self->length-i,
6742 str1->str, str1->length,
6743 i);
6744 if (i == -1)
6745 break;
6746 Py_UNICODE_COPY(u->str+i, str2->str, str2->length);
6747 i += str1->length;
6748 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006749 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006750 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006751
6752 Py_ssize_t n, i, j, e;
6753 Py_ssize_t product, new_size, delta;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006754 Py_UNICODE *p;
6755
6756 /* replace strings */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006757 n = stringlib_count(self->str, self->length, str1->str, str1->length,
6758 maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006759 if (n == 0)
6760 goto nothing;
6761 /* new_size = self->length + n * (str2->length - str1->length)); */
6762 delta = (str2->length - str1->length);
6763 if (delta == 0) {
6764 new_size = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006765 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006766 product = n * (str2->length - str1->length);
6767 if ((product / (str2->length - str1->length)) != n) {
6768 PyErr_SetString(PyExc_OverflowError,
6769 "replace string is too long");
6770 return NULL;
6771 }
6772 new_size = self->length + product;
6773 if (new_size < 0) {
6774 PyErr_SetString(PyExc_OverflowError,
6775 "replace string is too long");
6776 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006777 }
6778 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00006779 u = _PyUnicode_New(new_size);
6780 if (!u)
6781 return NULL;
6782 i = 0;
6783 p = u->str;
6784 e = self->length - str1->length;
6785 if (str1->length > 0) {
6786 while (n-- > 0) {
6787 /* look for next match */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006788 j = stringlib_find(self->str+i, self->length-i,
6789 str1->str, str1->length,
6790 i);
6791 if (j == -1)
6792 break;
6793 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006794 /* copy unchanged part [i:j] */
6795 Py_UNICODE_COPY(p, self->str+i, j-i);
6796 p += j - i;
6797 }
6798 /* copy substitution string */
6799 if (str2->length > 0) {
6800 Py_UNICODE_COPY(p, str2->str, str2->length);
6801 p += str2->length;
6802 }
6803 i = j + str1->length;
6804 }
6805 if (i < self->length)
6806 /* copy tail [i:] */
6807 Py_UNICODE_COPY(p, self->str+i, self->length-i);
6808 } else {
6809 /* interleave */
6810 while (n > 0) {
6811 Py_UNICODE_COPY(p, str2->str, str2->length);
6812 p += str2->length;
6813 if (--n <= 0)
6814 break;
6815 *p++ = self->str[i++];
6816 }
6817 Py_UNICODE_COPY(p, self->str+i, self->length-i);
6818 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006819 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006820 return (PyObject *) u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006821
Benjamin Peterson29060642009-01-31 22:14:21 +00006822 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00006823 /* nothing to replace; return original string (when possible) */
6824 if (PyUnicode_CheckExact(self)) {
6825 Py_INCREF(self);
6826 return (PyObject *) self;
6827 }
6828 return PyUnicode_FromUnicode(self->str, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006829}
6830
6831/* --- Unicode Object Methods --------------------------------------------- */
6832
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006833PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00006834 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00006835\n\
6836Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006837characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00006838
6839static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00006840unicode_title(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006841{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006842 return fixup(self, fixtitle);
6843}
6844
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006845PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00006846 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00006847\n\
6848Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +00006849have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00006850
6851static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00006852unicode_capitalize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006853{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006854 return fixup(self, fixcapitalize);
6855}
6856
6857#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006858PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00006859 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00006860\n\
6861Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006862normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00006863
6864static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00006865unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006866{
6867 PyObject *list;
6868 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006869 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006870
Guido van Rossumd57fd912000-03-10 22:53:23 +00006871 /* Split into words */
6872 list = split(self, NULL, -1);
6873 if (!list)
6874 return NULL;
6875
6876 /* Capitalize each word */
6877 for (i = 0; i < PyList_GET_SIZE(list); i++) {
6878 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00006879 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006880 if (item == NULL)
6881 goto onError;
6882 Py_DECREF(PyList_GET_ITEM(list, i));
6883 PyList_SET_ITEM(list, i, item);
6884 }
6885
6886 /* Join the words to form a new string */
6887 item = PyUnicode_Join(NULL, list);
6888
Benjamin Peterson29060642009-01-31 22:14:21 +00006889 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006890 Py_DECREF(list);
6891 return (PyObject *)item;
6892}
6893#endif
6894
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006895/* Argument converter. Coerces to a single unicode character */
6896
6897static int
6898convert_uc(PyObject *obj, void *addr)
6899{
Benjamin Peterson14339b62009-01-31 16:36:08 +00006900 Py_UNICODE *fillcharloc = (Py_UNICODE *)addr;
6901 PyObject *uniobj;
6902 Py_UNICODE *unistr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006903
Benjamin Peterson14339b62009-01-31 16:36:08 +00006904 uniobj = PyUnicode_FromObject(obj);
6905 if (uniobj == NULL) {
6906 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00006907 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +00006908 return 0;
6909 }
6910 if (PyUnicode_GET_SIZE(uniobj) != 1) {
6911 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00006912 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +00006913 Py_DECREF(uniobj);
6914 return 0;
6915 }
6916 unistr = PyUnicode_AS_UNICODE(uniobj);
6917 *fillcharloc = unistr[0];
6918 Py_DECREF(uniobj);
6919 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006920}
6921
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006922PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00006923 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00006924\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00006925Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006926done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +00006927
6928static PyObject *
6929unicode_center(PyUnicodeObject *self, PyObject *args)
6930{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006931 Py_ssize_t marg, left;
6932 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006933 Py_UNICODE fillchar = ' ';
Guido van Rossumd57fd912000-03-10 22:53:23 +00006934
Thomas Woutersde017742006-02-16 19:34:37 +00006935 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00006936 return NULL;
6937
Tim Peters7a29bd52001-09-12 03:03:31 +00006938 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006939 Py_INCREF(self);
6940 return (PyObject*) self;
6941 }
6942
6943 marg = width - self->length;
6944 left = marg / 2 + (marg & width & 1);
6945
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006946 return (PyObject*) pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006947}
6948
Marc-André Lemburge5034372000-08-08 08:04:29 +00006949#if 0
6950
6951/* This code should go into some future Unicode collation support
6952 module. The basic comparison should compare ordinals on a naive
Georg Brandlc6c31782009-06-08 13:41:29 +00006953 basis (this is what Java does and thus Jython too). */
Marc-André Lemburge5034372000-08-08 08:04:29 +00006954
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006955/* speedy UTF-16 code point order comparison */
6956/* gleaned from: */
6957/* http://www-4.ibm.com/software/developer/library/utf16.html?dwzone=unicode */
6958
Marc-André Lemburge12896e2000-07-07 17:51:08 +00006959static short utf16Fixup[32] =
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006960{
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006961 0, 0, 0, 0, 0, 0, 0, 0,
Tim Petersced69f82003-09-16 20:30:58 +00006962 0, 0, 0, 0, 0, 0, 0, 0,
6963 0, 0, 0, 0, 0, 0, 0, 0,
Marc-André Lemburge12896e2000-07-07 17:51:08 +00006964 0, 0, 0, 0x2000, -0x800, -0x800, -0x800, -0x800
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006965};
6966
Guido van Rossumd57fd912000-03-10 22:53:23 +00006967static int
6968unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
6969{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006970 Py_ssize_t len1, len2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006971
Guido van Rossumd57fd912000-03-10 22:53:23 +00006972 Py_UNICODE *s1 = str1->str;
6973 Py_UNICODE *s2 = str2->str;
6974
6975 len1 = str1->length;
6976 len2 = str2->length;
Tim Petersced69f82003-09-16 20:30:58 +00006977
Guido van Rossumd57fd912000-03-10 22:53:23 +00006978 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00006979 Py_UNICODE c1, c2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006980
6981 c1 = *s1++;
6982 c2 = *s2++;
Fredrik Lundh45714e92001-06-26 16:39:36 +00006983
Benjamin Peterson29060642009-01-31 22:14:21 +00006984 if (c1 > (1<<11) * 26)
6985 c1 += utf16Fixup[c1>>11];
6986 if (c2 > (1<<11) * 26)
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006987 c2 += utf16Fixup[c2>>11];
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006988 /* now c1 and c2 are in UTF-32-compatible order */
Fredrik Lundh45714e92001-06-26 16:39:36 +00006989
6990 if (c1 != c2)
6991 return (c1 < c2) ? -1 : 1;
Tim Petersced69f82003-09-16 20:30:58 +00006992
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006993 len1--; len2--;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006994 }
6995
6996 return (len1 < len2) ? -1 : (len1 != len2);
6997}
6998
Marc-André Lemburge5034372000-08-08 08:04:29 +00006999#else
7000
7001static int
7002unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
7003{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007004 register Py_ssize_t len1, len2;
Marc-André Lemburge5034372000-08-08 08:04:29 +00007005
7006 Py_UNICODE *s1 = str1->str;
7007 Py_UNICODE *s2 = str2->str;
7008
7009 len1 = str1->length;
7010 len2 = str2->length;
Tim Petersced69f82003-09-16 20:30:58 +00007011
Marc-André Lemburge5034372000-08-08 08:04:29 +00007012 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00007013 Py_UNICODE c1, c2;
Marc-André Lemburge5034372000-08-08 08:04:29 +00007014
Fredrik Lundh45714e92001-06-26 16:39:36 +00007015 c1 = *s1++;
7016 c2 = *s2++;
7017
7018 if (c1 != c2)
7019 return (c1 < c2) ? -1 : 1;
7020
Marc-André Lemburge5034372000-08-08 08:04:29 +00007021 len1--; len2--;
7022 }
7023
7024 return (len1 < len2) ? -1 : (len1 != len2);
7025}
7026
7027#endif
7028
Guido van Rossumd57fd912000-03-10 22:53:23 +00007029int PyUnicode_Compare(PyObject *left,
Benjamin Peterson29060642009-01-31 22:14:21 +00007030 PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007031{
Guido van Rossum09dc34f2007-05-04 04:17:33 +00007032 if (PyUnicode_Check(left) && PyUnicode_Check(right))
7033 return unicode_compare((PyUnicodeObject *)left,
7034 (PyUnicodeObject *)right);
Guido van Rossum09dc34f2007-05-04 04:17:33 +00007035 PyErr_Format(PyExc_TypeError,
7036 "Can't compare %.100s and %.100s",
7037 left->ob_type->tp_name,
7038 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007039 return -1;
7040}
7041
Martin v. Löwis5b222132007-06-10 09:51:05 +00007042int
7043PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
7044{
7045 int i;
7046 Py_UNICODE *id;
7047 assert(PyUnicode_Check(uni));
7048 id = PyUnicode_AS_UNICODE(uni);
7049 /* Compare Unicode string and source character set string */
7050 for (i = 0; id[i] && str[i]; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00007051 if (id[i] != str[i])
7052 return ((int)id[i] < (int)str[i]) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +00007053 /* This check keeps Python strings that end in '\0' from comparing equal
7054 to C strings identical up to that point. */
Benjamin Petersona23831f2010-04-25 21:54:00 +00007055 if (PyUnicode_GET_SIZE(uni) != i || id[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00007056 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00007057 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00007058 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00007059 return 0;
7060}
7061
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007062
Benjamin Peterson29060642009-01-31 22:14:21 +00007063#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +00007064 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007065
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007066PyObject *PyUnicode_RichCompare(PyObject *left,
7067 PyObject *right,
7068 int op)
7069{
7070 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007071
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007072 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
7073 PyObject *v;
7074 if (((PyUnicodeObject *) left)->length !=
7075 ((PyUnicodeObject *) right)->length) {
7076 if (op == Py_EQ) {
7077 Py_INCREF(Py_False);
7078 return Py_False;
7079 }
7080 if (op == Py_NE) {
7081 Py_INCREF(Py_True);
7082 return Py_True;
7083 }
7084 }
7085 if (left == right)
7086 result = 0;
7087 else
7088 result = unicode_compare((PyUnicodeObject *)left,
7089 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007090
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007091 /* Convert the return value to a Boolean */
7092 switch (op) {
7093 case Py_EQ:
7094 v = TEST_COND(result == 0);
7095 break;
7096 case Py_NE:
7097 v = TEST_COND(result != 0);
7098 break;
7099 case Py_LE:
7100 v = TEST_COND(result <= 0);
7101 break;
7102 case Py_GE:
7103 v = TEST_COND(result >= 0);
7104 break;
7105 case Py_LT:
7106 v = TEST_COND(result == -1);
7107 break;
7108 case Py_GT:
7109 v = TEST_COND(result == 1);
7110 break;
7111 default:
7112 PyErr_BadArgument();
7113 return NULL;
7114 }
7115 Py_INCREF(v);
7116 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007117 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007118
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007119 Py_INCREF(Py_NotImplemented);
7120 return Py_NotImplemented;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007121}
7122
Guido van Rossum403d68b2000-03-13 15:55:09 +00007123int PyUnicode_Contains(PyObject *container,
Benjamin Peterson29060642009-01-31 22:14:21 +00007124 PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +00007125{
Thomas Wouters477c8d52006-05-27 19:21:47 +00007126 PyObject *str, *sub;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007127 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007128
7129 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +00007130 sub = PyUnicode_FromObject(element);
7131 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007132 PyErr_Format(PyExc_TypeError,
7133 "'in <string>' requires string as left operand, not %s",
7134 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007135 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007136 }
7137
Thomas Wouters477c8d52006-05-27 19:21:47 +00007138 str = PyUnicode_FromObject(container);
7139 if (!str) {
7140 Py_DECREF(sub);
7141 return -1;
7142 }
7143
7144 result = stringlib_contains_obj(str, sub);
7145
7146 Py_DECREF(str);
7147 Py_DECREF(sub);
7148
Guido van Rossum403d68b2000-03-13 15:55:09 +00007149 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007150}
7151
Guido van Rossumd57fd912000-03-10 22:53:23 +00007152/* Concat to string or Unicode object giving a new Unicode object. */
7153
7154PyObject *PyUnicode_Concat(PyObject *left,
Benjamin Peterson29060642009-01-31 22:14:21 +00007155 PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007156{
7157 PyUnicodeObject *u = NULL, *v = NULL, *w;
7158
7159 /* Coerce the two arguments */
7160 u = (PyUnicodeObject *)PyUnicode_FromObject(left);
7161 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007162 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007163 v = (PyUnicodeObject *)PyUnicode_FromObject(right);
7164 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007165 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007166
7167 /* Shortcuts */
7168 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007169 Py_DECREF(v);
7170 return (PyObject *)u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007171 }
7172 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007173 Py_DECREF(u);
7174 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007175 }
7176
7177 /* Concat the two Unicode strings */
7178 w = _PyUnicode_New(u->length + v->length);
7179 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007180 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007181 Py_UNICODE_COPY(w->str, u->str, u->length);
7182 Py_UNICODE_COPY(w->str + u->length, v->str, v->length);
7183
7184 Py_DECREF(u);
7185 Py_DECREF(v);
7186 return (PyObject *)w;
7187
Benjamin Peterson29060642009-01-31 22:14:21 +00007188 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007189 Py_XDECREF(u);
7190 Py_XDECREF(v);
7191 return NULL;
7192}
7193
Walter Dörwald1ab83302007-05-18 17:15:44 +00007194void
7195PyUnicode_Append(PyObject **pleft, PyObject *right)
7196{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007197 PyObject *new;
7198 if (*pleft == NULL)
7199 return;
7200 if (right == NULL || !PyUnicode_Check(*pleft)) {
7201 Py_DECREF(*pleft);
7202 *pleft = NULL;
7203 return;
7204 }
7205 new = PyUnicode_Concat(*pleft, right);
7206 Py_DECREF(*pleft);
7207 *pleft = new;
Walter Dörwald1ab83302007-05-18 17:15:44 +00007208}
7209
7210void
7211PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
7212{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007213 PyUnicode_Append(pleft, right);
7214 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +00007215}
7216
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007217PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007218 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007219\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00007220Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007221string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007222interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007223
7224static PyObject *
7225unicode_count(PyUnicodeObject *self, PyObject *args)
7226{
7227 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007228 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007229 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007230 PyObject *result;
7231
Guido van Rossumb8872e62000-05-09 14:14:27 +00007232 if (!PyArg_ParseTuple(args, "O|O&O&:count", &substring,
Benjamin Peterson29060642009-01-31 22:14:21 +00007233 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007234 return NULL;
7235
7236 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Thomas Wouters477c8d52006-05-27 19:21:47 +00007237 (PyObject *)substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007238 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007239 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007240
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007241 ADJUST_INDICES(start, end, self->length);
Christian Heimes217cfd12007-12-02 14:31:20 +00007242 result = PyLong_FromSsize_t(
Thomas Wouters477c8d52006-05-27 19:21:47 +00007243 stringlib_count(self->str + start, end - start,
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007244 substring->str, substring->length,
7245 PY_SSIZE_T_MAX)
Thomas Wouters477c8d52006-05-27 19:21:47 +00007246 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007247
7248 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007249
Guido van Rossumd57fd912000-03-10 22:53:23 +00007250 return result;
7251}
7252
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007253PyDoc_STRVAR(encode__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007254 "S.encode([encoding[, errors]]) -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007255\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00007256Encode S using the codec registered for encoding. encoding defaults\n\
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007257to the default encoding. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +00007258handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007259a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
7260'xmlcharrefreplace' as well as any other name registered with\n\
7261codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007262
7263static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +00007264unicode_encode(PyUnicodeObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007265{
Benjamin Peterson308d6372009-09-18 21:42:35 +00007266 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +00007267 char *encoding = NULL;
7268 char *errors = NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007269 PyObject *v;
Guido van Rossum35d94282007-08-27 18:20:11 +00007270
Benjamin Peterson308d6372009-09-18 21:42:35 +00007271 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
7272 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007273 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00007274 v = PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00007275 if (v == NULL)
7276 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00007277 if (!PyBytes_Check(v)) {
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007278 PyErr_Format(PyExc_TypeError,
Guido van Rossumf15a29f2007-05-04 00:41:39 +00007279 "encoder did not return a bytes object "
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007280 "(type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00007281 Py_TYPE(v)->tp_name);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007282 Py_DECREF(v);
7283 return NULL;
7284 }
7285 return v;
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00007286
Benjamin Peterson29060642009-01-31 22:14:21 +00007287 onError:
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00007288 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007289}
7290
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007291PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007292 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007293\n\
7294Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007295If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007296
7297static PyObject*
7298unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
7299{
7300 Py_UNICODE *e;
7301 Py_UNICODE *p;
7302 Py_UNICODE *q;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007303 Py_UNICODE *qe;
7304 Py_ssize_t i, j, incr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007305 PyUnicodeObject *u;
7306 int tabsize = 8;
7307
7308 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00007309 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007310
Thomas Wouters7e474022000-07-16 12:04:32 +00007311 /* First pass: determine size of output string */
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007312 i = 0; /* chars up to and including most recent \n or \r */
7313 j = 0; /* chars since most recent \n or \r (use in tab calculations) */
7314 e = self->str + self->length; /* end of input */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007315 for (p = self->str; p < e; p++)
7316 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007317 if (tabsize > 0) {
7318 incr = tabsize - (j % tabsize); /* cannot overflow */
7319 if (j > PY_SSIZE_T_MAX - incr)
7320 goto overflow1;
7321 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007322 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007323 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007324 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007325 if (j > PY_SSIZE_T_MAX - 1)
7326 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007327 j++;
7328 if (*p == '\n' || *p == '\r') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007329 if (i > PY_SSIZE_T_MAX - j)
7330 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007331 i += j;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007332 j = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007333 }
7334 }
7335
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007336 if (i > PY_SSIZE_T_MAX - j)
Benjamin Peterson29060642009-01-31 22:14:21 +00007337 goto overflow1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007338
Guido van Rossumd57fd912000-03-10 22:53:23 +00007339 /* Second pass: create output string and fill it */
7340 u = _PyUnicode_New(i + j);
7341 if (!u)
7342 return NULL;
7343
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007344 j = 0; /* same as in first pass */
7345 q = u->str; /* next output char */
7346 qe = u->str + u->length; /* end of output */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007347
7348 for (p = self->str; p < e; p++)
7349 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007350 if (tabsize > 0) {
7351 i = tabsize - (j % tabsize);
7352 j += i;
7353 while (i--) {
7354 if (q >= qe)
7355 goto overflow2;
7356 *q++ = ' ';
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007357 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007358 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007359 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007360 else {
7361 if (q >= qe)
7362 goto overflow2;
7363 *q++ = *p;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007364 j++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007365 if (*p == '\n' || *p == '\r')
7366 j = 0;
7367 }
7368
7369 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007370
7371 overflow2:
7372 Py_DECREF(u);
7373 overflow1:
7374 PyErr_SetString(PyExc_OverflowError, "new string is too long");
7375 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007376}
7377
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007378PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007379 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007380\n\
7381Return the lowest index in S where substring sub is found,\n\
Guido van Rossum806c2462007-08-06 23:33:07 +00007382such that sub is contained within s[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007383arguments start and end are interpreted as in slice notation.\n\
7384\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007385Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007386
7387static PyObject *
7388unicode_find(PyUnicodeObject *self, PyObject *args)
7389{
Thomas Wouters477c8d52006-05-27 19:21:47 +00007390 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00007391 Py_ssize_t start;
7392 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007393 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007394
Christian Heimes9cd17752007-11-18 19:35:23 +00007395 if (!_ParseTupleFinds(args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007396 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007397
Thomas Wouters477c8d52006-05-27 19:21:47 +00007398 result = stringlib_find_slice(
7399 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
7400 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
7401 start, end
7402 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007403
7404 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007405
Christian Heimes217cfd12007-12-02 14:31:20 +00007406 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007407}
7408
7409static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00007410unicode_getitem(PyUnicodeObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007411{
7412 if (index < 0 || index >= self->length) {
7413 PyErr_SetString(PyExc_IndexError, "string index out of range");
7414 return NULL;
7415 }
7416
7417 return (PyObject*) PyUnicode_FromUnicode(&self->str[index], 1);
7418}
7419
Guido van Rossumc2504932007-09-18 19:42:40 +00007420/* Believe it or not, this produces the same value for ASCII strings
7421 as string_hash(). */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007422static long
Neil Schemenauerf8c37d12007-09-07 20:49:04 +00007423unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007424{
Guido van Rossumc2504932007-09-18 19:42:40 +00007425 Py_ssize_t len;
7426 Py_UNICODE *p;
7427 long x;
7428
7429 if (self->hash != -1)
7430 return self->hash;
Christian Heimes90aa7642007-12-19 02:45:37 +00007431 len = Py_SIZE(self);
Guido van Rossumc2504932007-09-18 19:42:40 +00007432 p = self->str;
7433 x = *p << 7;
7434 while (--len >= 0)
7435 x = (1000003*x) ^ *p++;
Christian Heimes90aa7642007-12-19 02:45:37 +00007436 x ^= Py_SIZE(self);
Guido van Rossumc2504932007-09-18 19:42:40 +00007437 if (x == -1)
7438 x = -2;
7439 self->hash = x;
7440 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007441}
7442
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007443PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007444 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007445\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007446Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007447
7448static PyObject *
7449unicode_index(PyUnicodeObject *self, PyObject *args)
7450{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007451 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007452 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00007453 Py_ssize_t start;
7454 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007455
Christian Heimes9cd17752007-11-18 19:35:23 +00007456 if (!_ParseTupleFinds(args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007457 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007458
Thomas Wouters477c8d52006-05-27 19:21:47 +00007459 result = stringlib_find_slice(
7460 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
7461 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
7462 start, end
7463 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007464
7465 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007466
Guido van Rossumd57fd912000-03-10 22:53:23 +00007467 if (result < 0) {
7468 PyErr_SetString(PyExc_ValueError, "substring not found");
7469 return NULL;
7470 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00007471
Christian Heimes217cfd12007-12-02 14:31:20 +00007472 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007473}
7474
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007475PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007476 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007477\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007478Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007479at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007480
7481static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007482unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007483{
7484 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7485 register const Py_UNICODE *e;
7486 int cased;
7487
Guido van Rossumd57fd912000-03-10 22:53:23 +00007488 /* Shortcut for single character strings */
7489 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007490 return PyBool_FromLong(Py_UNICODE_ISLOWER(*p));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007491
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007492 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007493 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007494 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007495
Guido van Rossumd57fd912000-03-10 22:53:23 +00007496 e = p + PyUnicode_GET_SIZE(self);
7497 cased = 0;
7498 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007499 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007500
Benjamin Peterson29060642009-01-31 22:14:21 +00007501 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
7502 return PyBool_FromLong(0);
7503 else if (!cased && Py_UNICODE_ISLOWER(ch))
7504 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007505 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007506 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007507}
7508
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007509PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007510 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007511\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007512Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007513at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007514
7515static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007516unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007517{
7518 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7519 register const Py_UNICODE *e;
7520 int cased;
7521
Guido van Rossumd57fd912000-03-10 22:53:23 +00007522 /* Shortcut for single character strings */
7523 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007524 return PyBool_FromLong(Py_UNICODE_ISUPPER(*p) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007525
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007526 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007527 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007528 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007529
Guido van Rossumd57fd912000-03-10 22:53:23 +00007530 e = p + PyUnicode_GET_SIZE(self);
7531 cased = 0;
7532 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007533 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007534
Benjamin Peterson29060642009-01-31 22:14:21 +00007535 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
7536 return PyBool_FromLong(0);
7537 else if (!cased && Py_UNICODE_ISUPPER(ch))
7538 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007539 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007540 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007541}
7542
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007543PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007544 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007545\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007546Return True if S is a titlecased string and there is at least one\n\
7547character in S, i.e. upper- and titlecase characters may only\n\
7548follow uncased characters and lowercase characters only cased ones.\n\
7549Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007550
7551static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007552unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007553{
7554 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7555 register const Py_UNICODE *e;
7556 int cased, previous_is_cased;
7557
Guido van Rossumd57fd912000-03-10 22:53:23 +00007558 /* Shortcut for single character strings */
7559 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007560 return PyBool_FromLong((Py_UNICODE_ISTITLE(*p) != 0) ||
7561 (Py_UNICODE_ISUPPER(*p) != 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007562
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007563 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007564 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007565 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007566
Guido van Rossumd57fd912000-03-10 22:53:23 +00007567 e = p + PyUnicode_GET_SIZE(self);
7568 cased = 0;
7569 previous_is_cased = 0;
7570 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007571 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007572
Benjamin Peterson29060642009-01-31 22:14:21 +00007573 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
7574 if (previous_is_cased)
7575 return PyBool_FromLong(0);
7576 previous_is_cased = 1;
7577 cased = 1;
7578 }
7579 else if (Py_UNICODE_ISLOWER(ch)) {
7580 if (!previous_is_cased)
7581 return PyBool_FromLong(0);
7582 previous_is_cased = 1;
7583 cased = 1;
7584 }
7585 else
7586 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007587 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007588 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007589}
7590
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007591PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007592 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007593\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007594Return True if all characters in S are whitespace\n\
7595and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007596
7597static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007598unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007599{
7600 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7601 register const Py_UNICODE *e;
7602
Guido van Rossumd57fd912000-03-10 22:53:23 +00007603 /* Shortcut for single character strings */
7604 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007605 Py_UNICODE_ISSPACE(*p))
7606 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007607
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007608 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007609 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007610 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007611
Guido van Rossumd57fd912000-03-10 22:53:23 +00007612 e = p + PyUnicode_GET_SIZE(self);
7613 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007614 if (!Py_UNICODE_ISSPACE(*p))
7615 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007616 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007617 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007618}
7619
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007620PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007621 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007622\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007623Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007624and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007625
7626static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007627unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007628{
7629 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7630 register const Py_UNICODE *e;
7631
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007632 /* Shortcut for single character strings */
7633 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007634 Py_UNICODE_ISALPHA(*p))
7635 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007636
7637 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007638 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007639 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007640
7641 e = p + PyUnicode_GET_SIZE(self);
7642 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007643 if (!Py_UNICODE_ISALPHA(*p))
7644 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007645 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007646 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007647}
7648
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007649PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007650 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007651\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007652Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007653and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007654
7655static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007656unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007657{
7658 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7659 register const Py_UNICODE *e;
7660
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007661 /* Shortcut for single character strings */
7662 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007663 Py_UNICODE_ISALNUM(*p))
7664 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007665
7666 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007667 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007668 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007669
7670 e = p + PyUnicode_GET_SIZE(self);
7671 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007672 if (!Py_UNICODE_ISALNUM(*p))
7673 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007674 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007675 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007676}
7677
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007678PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007679 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007680\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007681Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007682False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007683
7684static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007685unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007686{
7687 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7688 register const Py_UNICODE *e;
7689
Guido van Rossumd57fd912000-03-10 22:53:23 +00007690 /* Shortcut for single character strings */
7691 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007692 Py_UNICODE_ISDECIMAL(*p))
7693 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007694
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007695 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007696 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007697 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007698
Guido van Rossumd57fd912000-03-10 22:53:23 +00007699 e = p + PyUnicode_GET_SIZE(self);
7700 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007701 if (!Py_UNICODE_ISDECIMAL(*p))
7702 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007703 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007704 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007705}
7706
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007707PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007708 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007709\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007710Return True if all characters in S are digits\n\
7711and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007712
7713static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007714unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007715{
7716 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7717 register const Py_UNICODE *e;
7718
Guido van Rossumd57fd912000-03-10 22:53:23 +00007719 /* Shortcut for single character strings */
7720 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007721 Py_UNICODE_ISDIGIT(*p))
7722 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007723
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007724 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007725 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007726 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007727
Guido van Rossumd57fd912000-03-10 22:53:23 +00007728 e = p + PyUnicode_GET_SIZE(self);
7729 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007730 if (!Py_UNICODE_ISDIGIT(*p))
7731 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007732 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007733 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007734}
7735
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007736PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007737 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007738\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007739Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007740False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007741
7742static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007743unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007744{
7745 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7746 register const Py_UNICODE *e;
7747
Guido van Rossumd57fd912000-03-10 22:53:23 +00007748 /* Shortcut for single character strings */
7749 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007750 Py_UNICODE_ISNUMERIC(*p))
7751 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007752
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007753 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007754 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007755 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007756
Guido van Rossumd57fd912000-03-10 22:53:23 +00007757 e = p + PyUnicode_GET_SIZE(self);
7758 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007759 if (!Py_UNICODE_ISNUMERIC(*p))
7760 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007761 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007762 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007763}
7764
Martin v. Löwis47383402007-08-15 07:32:56 +00007765int
7766PyUnicode_IsIdentifier(PyObject *self)
7767{
7768 register const Py_UNICODE *p = PyUnicode_AS_UNICODE((PyUnicodeObject*)self);
7769 register const Py_UNICODE *e;
7770
7771 /* Special case for empty strings */
7772 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007773 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +00007774
7775 /* PEP 3131 says that the first character must be in
7776 XID_Start and subsequent characters in XID_Continue,
7777 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +00007778 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +00007779 letters, digits, underscore). However, given the current
7780 definition of XID_Start and XID_Continue, it is sufficient
7781 to check just for these, except that _ must be allowed
7782 as starting an identifier. */
7783 if (!_PyUnicode_IsXidStart(*p) && *p != 0x5F /* LOW LINE */)
7784 return 0;
7785
7786 e = p + PyUnicode_GET_SIZE(self);
7787 for (p++; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007788 if (!_PyUnicode_IsXidContinue(*p))
7789 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +00007790 }
7791 return 1;
7792}
7793
7794PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007795 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +00007796\n\
7797Return True if S is a valid identifier according\n\
7798to the language definition.");
7799
7800static PyObject*
7801unicode_isidentifier(PyObject *self)
7802{
7803 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
7804}
7805
Georg Brandl559e5d72008-06-11 18:37:52 +00007806PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007807 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +00007808\n\
7809Return True if all characters in S are considered\n\
7810printable in repr() or S is empty, False otherwise.");
7811
7812static PyObject*
7813unicode_isprintable(PyObject *self)
7814{
7815 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7816 register const Py_UNICODE *e;
7817
7818 /* Shortcut for single character strings */
7819 if (PyUnicode_GET_SIZE(self) == 1 && Py_UNICODE_ISPRINTABLE(*p)) {
7820 Py_RETURN_TRUE;
7821 }
7822
7823 e = p + PyUnicode_GET_SIZE(self);
7824 for (; p < e; p++) {
7825 if (!Py_UNICODE_ISPRINTABLE(*p)) {
7826 Py_RETURN_FALSE;
7827 }
7828 }
7829 Py_RETURN_TRUE;
7830}
7831
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007832PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +00007833 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007834\n\
7835Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +00007836iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007837
7838static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007839unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007840{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007841 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007842}
7843
Martin v. Löwis18e16552006-02-15 17:27:45 +00007844static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +00007845unicode_length(PyUnicodeObject *self)
7846{
7847 return self->length;
7848}
7849
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007850PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007851 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007852\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00007853Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007854done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007855
7856static PyObject *
7857unicode_ljust(PyUnicodeObject *self, PyObject *args)
7858{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007859 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007860 Py_UNICODE fillchar = ' ';
7861
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007862 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007863 return NULL;
7864
Tim Peters7a29bd52001-09-12 03:03:31 +00007865 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00007866 Py_INCREF(self);
7867 return (PyObject*) self;
7868 }
7869
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007870 return (PyObject*) pad(self, 0, width - self->length, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007871}
7872
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007873PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007874 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007875\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007876Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007877
7878static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007879unicode_lower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007880{
Guido van Rossumd57fd912000-03-10 22:53:23 +00007881 return fixup(self, fixlower);
7882}
7883
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007884#define LEFTSTRIP 0
7885#define RIGHTSTRIP 1
7886#define BOTHSTRIP 2
7887
7888/* Arrays indexed by above */
7889static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
7890
7891#define STRIPNAME(i) (stripformat[i]+3)
7892
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007893/* externally visible for str.strip(unicode) */
7894PyObject *
7895_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
7896{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007897 Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
7898 Py_ssize_t len = PyUnicode_GET_SIZE(self);
7899 Py_UNICODE *sep = PyUnicode_AS_UNICODE(sepobj);
7900 Py_ssize_t seplen = PyUnicode_GET_SIZE(sepobj);
7901 Py_ssize_t i, j;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007902
Benjamin Peterson29060642009-01-31 22:14:21 +00007903 BLOOM_MASK sepmask = make_bloom_mask(sep, seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007904
Benjamin Peterson14339b62009-01-31 16:36:08 +00007905 i = 0;
7906 if (striptype != RIGHTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007907 while (i < len && BLOOM_MEMBER(sepmask, s[i], sep, seplen)) {
7908 i++;
7909 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007910 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007911
Benjamin Peterson14339b62009-01-31 16:36:08 +00007912 j = len;
7913 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007914 do {
7915 j--;
7916 } while (j >= i && BLOOM_MEMBER(sepmask, s[j], sep, seplen));
7917 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007918 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007919
Benjamin Peterson14339b62009-01-31 16:36:08 +00007920 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007921 Py_INCREF(self);
7922 return (PyObject*)self;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007923 }
7924 else
Benjamin Peterson29060642009-01-31 22:14:21 +00007925 return PyUnicode_FromUnicode(s+i, j-i);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007926}
7927
Guido van Rossumd57fd912000-03-10 22:53:23 +00007928
7929static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007930do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007931{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007932 Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
7933 Py_ssize_t len = PyUnicode_GET_SIZE(self), i, j;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007934
Benjamin Peterson14339b62009-01-31 16:36:08 +00007935 i = 0;
7936 if (striptype != RIGHTSTRIP) {
7937 while (i < len && Py_UNICODE_ISSPACE(s[i])) {
7938 i++;
7939 }
7940 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007941
Benjamin Peterson14339b62009-01-31 16:36:08 +00007942 j = len;
7943 if (striptype != LEFTSTRIP) {
7944 do {
7945 j--;
7946 } while (j >= i && Py_UNICODE_ISSPACE(s[j]));
7947 j++;
7948 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007949
Benjamin Peterson14339b62009-01-31 16:36:08 +00007950 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
7951 Py_INCREF(self);
7952 return (PyObject*)self;
7953 }
7954 else
7955 return PyUnicode_FromUnicode(s+i, j-i);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007956}
7957
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007958
7959static PyObject *
7960do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
7961{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007962 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007963
Benjamin Peterson14339b62009-01-31 16:36:08 +00007964 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
7965 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007966
Benjamin Peterson14339b62009-01-31 16:36:08 +00007967 if (sep != NULL && sep != Py_None) {
7968 if (PyUnicode_Check(sep))
7969 return _PyUnicode_XStrip(self, striptype, sep);
7970 else {
7971 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00007972 "%s arg must be None or str",
7973 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +00007974 return NULL;
7975 }
7976 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007977
Benjamin Peterson14339b62009-01-31 16:36:08 +00007978 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007979}
7980
7981
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007982PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007983 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007984\n\
7985Return a copy of the string S with leading and trailing\n\
7986whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007987If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007988
7989static PyObject *
7990unicode_strip(PyUnicodeObject *self, PyObject *args)
7991{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007992 if (PyTuple_GET_SIZE(args) == 0)
7993 return do_strip(self, BOTHSTRIP); /* Common case */
7994 else
7995 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007996}
7997
7998
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007999PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008000 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008001\n\
8002Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008003If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008004
8005static PyObject *
8006unicode_lstrip(PyUnicodeObject *self, PyObject *args)
8007{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008008 if (PyTuple_GET_SIZE(args) == 0)
8009 return do_strip(self, LEFTSTRIP); /* Common case */
8010 else
8011 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008012}
8013
8014
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008015PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008016 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008017\n\
8018Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008019If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008020
8021static PyObject *
8022unicode_rstrip(PyUnicodeObject *self, PyObject *args)
8023{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008024 if (PyTuple_GET_SIZE(args) == 0)
8025 return do_strip(self, RIGHTSTRIP); /* Common case */
8026 else
8027 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008028}
8029
8030
Guido van Rossumd57fd912000-03-10 22:53:23 +00008031static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +00008032unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008033{
8034 PyUnicodeObject *u;
8035 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008036 Py_ssize_t nchars;
Tim Peters8f422462000-09-09 06:13:41 +00008037 size_t nbytes;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008038
Georg Brandl222de0f2009-04-12 12:01:50 +00008039 if (len < 1) {
8040 Py_INCREF(unicode_empty);
8041 return (PyObject *)unicode_empty;
8042 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008043
Tim Peters7a29bd52001-09-12 03:03:31 +00008044 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008045 /* no repeat, return original string */
8046 Py_INCREF(str);
8047 return (PyObject*) str;
8048 }
Tim Peters8f422462000-09-09 06:13:41 +00008049
8050 /* ensure # of chars needed doesn't overflow int and # of bytes
8051 * needed doesn't overflow size_t
8052 */
8053 nchars = len * str->length;
Georg Brandl222de0f2009-04-12 12:01:50 +00008054 if (nchars / len != str->length) {
Tim Peters8f422462000-09-09 06:13:41 +00008055 PyErr_SetString(PyExc_OverflowError,
8056 "repeated string is too long");
8057 return NULL;
8058 }
8059 nbytes = (nchars + 1) * sizeof(Py_UNICODE);
8060 if (nbytes / sizeof(Py_UNICODE) != (size_t)(nchars + 1)) {
8061 PyErr_SetString(PyExc_OverflowError,
8062 "repeated string is too long");
8063 return NULL;
8064 }
8065 u = _PyUnicode_New(nchars);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008066 if (!u)
8067 return NULL;
8068
8069 p = u->str;
8070
Georg Brandl222de0f2009-04-12 12:01:50 +00008071 if (str->length == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00008072 Py_UNICODE_FILL(p, str->str[0], len);
8073 } else {
Georg Brandl222de0f2009-04-12 12:01:50 +00008074 Py_ssize_t done = str->length; /* number of characters copied this far */
8075 Py_UNICODE_COPY(p, str->str, str->length);
Benjamin Peterson29060642009-01-31 22:14:21 +00008076 while (done < nchars) {
Christian Heimescc47b052008-03-25 14:56:36 +00008077 Py_ssize_t n = (done <= nchars-done) ? done : nchars-done;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008078 Py_UNICODE_COPY(p+done, p, n);
8079 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00008080 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008081 }
8082
8083 return (PyObject*) u;
8084}
8085
8086PyObject *PyUnicode_Replace(PyObject *obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00008087 PyObject *subobj,
8088 PyObject *replobj,
8089 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008090{
8091 PyObject *self;
8092 PyObject *str1;
8093 PyObject *str2;
8094 PyObject *result;
8095
8096 self = PyUnicode_FromObject(obj);
8097 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008098 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008099 str1 = PyUnicode_FromObject(subobj);
8100 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008101 Py_DECREF(self);
8102 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008103 }
8104 str2 = PyUnicode_FromObject(replobj);
8105 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008106 Py_DECREF(self);
8107 Py_DECREF(str1);
8108 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008109 }
Tim Petersced69f82003-09-16 20:30:58 +00008110 result = replace((PyUnicodeObject *)self,
Benjamin Peterson29060642009-01-31 22:14:21 +00008111 (PyUnicodeObject *)str1,
8112 (PyUnicodeObject *)str2,
8113 maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008114 Py_DECREF(self);
8115 Py_DECREF(str1);
8116 Py_DECREF(str2);
8117 return result;
8118}
8119
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008120PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +00008121 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008122\n\
8123Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +00008124old replaced by new. If the optional argument count is\n\
8125given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008126
8127static PyObject*
8128unicode_replace(PyUnicodeObject *self, PyObject *args)
8129{
8130 PyUnicodeObject *str1;
8131 PyUnicodeObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008132 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008133 PyObject *result;
8134
Martin v. Löwis18e16552006-02-15 17:27:45 +00008135 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008136 return NULL;
8137 str1 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str1);
8138 if (str1 == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008139 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008140 str2 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str2);
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +00008141 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008142 Py_DECREF(str1);
8143 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +00008144 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008145
8146 result = replace(self, str1, str2, maxcount);
8147
8148 Py_DECREF(str1);
8149 Py_DECREF(str2);
8150 return result;
8151}
8152
8153static
8154PyObject *unicode_repr(PyObject *unicode)
8155{
Walter Dörwald79e913e2007-05-12 11:08:06 +00008156 PyObject *repr;
Walter Dörwald1ab83302007-05-18 17:15:44 +00008157 Py_UNICODE *p;
Walter Dörwald79e913e2007-05-12 11:08:06 +00008158 Py_UNICODE *s = PyUnicode_AS_UNICODE(unicode);
8159 Py_ssize_t size = PyUnicode_GET_SIZE(unicode);
8160
8161 /* XXX(nnorwitz): rather than over-allocating, it would be
8162 better to choose a different scheme. Perhaps scan the
8163 first N-chars of the string and allocate based on that size.
8164 */
8165 /* Initial allocation is based on the longest-possible unichr
8166 escape.
8167
8168 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
8169 unichr, so in this case it's the longest unichr escape. In
8170 narrow (UTF-16) builds this is five chars per source unichr
8171 since there are two unichrs in the surrogate pair, so in narrow
8172 (UTF-16) builds it's not the longest unichr escape.
8173
8174 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
8175 so in the narrow (UTF-16) build case it's the longest unichr
8176 escape.
8177 */
8178
Walter Dörwald1ab83302007-05-18 17:15:44 +00008179 repr = PyUnicode_FromUnicode(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00008180 2 /* quotes */
Walter Dörwald79e913e2007-05-12 11:08:06 +00008181#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00008182 + 10*size
Walter Dörwald79e913e2007-05-12 11:08:06 +00008183#else
Benjamin Peterson29060642009-01-31 22:14:21 +00008184 + 6*size
Walter Dörwald79e913e2007-05-12 11:08:06 +00008185#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00008186 + 1);
Walter Dörwald79e913e2007-05-12 11:08:06 +00008187 if (repr == NULL)
8188 return NULL;
8189
Walter Dörwald1ab83302007-05-18 17:15:44 +00008190 p = PyUnicode_AS_UNICODE(repr);
Walter Dörwald79e913e2007-05-12 11:08:06 +00008191
8192 /* Add quote */
8193 *p++ = (findchar(s, size, '\'') &&
8194 !findchar(s, size, '"')) ? '"' : '\'';
8195 while (size-- > 0) {
8196 Py_UNICODE ch = *s++;
8197
8198 /* Escape quotes and backslashes */
Walter Dörwald1ab83302007-05-18 17:15:44 +00008199 if ((ch == PyUnicode_AS_UNICODE(repr)[0]) || (ch == '\\')) {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008200 *p++ = '\\';
Walter Dörwald1ab83302007-05-18 17:15:44 +00008201 *p++ = ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00008202 continue;
8203 }
8204
Benjamin Peterson29060642009-01-31 22:14:21 +00008205 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +00008206 if (ch == '\t') {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008207 *p++ = '\\';
8208 *p++ = 't';
8209 }
8210 else if (ch == '\n') {
8211 *p++ = '\\';
8212 *p++ = 'n';
8213 }
8214 else if (ch == '\r') {
8215 *p++ = '\\';
8216 *p++ = 'r';
8217 }
8218
8219 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +00008220 else if (ch < ' ' || ch == 0x7F) {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008221 *p++ = '\\';
8222 *p++ = 'x';
8223 *p++ = hexdigits[(ch >> 4) & 0x000F];
8224 *p++ = hexdigits[ch & 0x000F];
8225 }
8226
Georg Brandl559e5d72008-06-11 18:37:52 +00008227 /* Copy ASCII characters as-is */
8228 else if (ch < 0x7F) {
8229 *p++ = ch;
8230 }
8231
Benjamin Peterson29060642009-01-31 22:14:21 +00008232 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +00008233 else {
8234 Py_UCS4 ucs = ch;
8235
8236#ifndef Py_UNICODE_WIDE
8237 Py_UNICODE ch2 = 0;
8238 /* Get code point from surrogate pair */
8239 if (size > 0) {
8240 ch2 = *s;
8241 if (ch >= 0xD800 && ch < 0xDC00 && ch2 >= 0xDC00
Benjamin Peterson29060642009-01-31 22:14:21 +00008242 && ch2 <= 0xDFFF) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008243 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF))
Benjamin Peterson29060642009-01-31 22:14:21 +00008244 + 0x00010000;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008245 s++;
Georg Brandl559e5d72008-06-11 18:37:52 +00008246 size--;
8247 }
8248 }
8249#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00008250 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +00008251 (categories Z* and C* except ASCII space)
8252 */
8253 if (!Py_UNICODE_ISPRINTABLE(ucs)) {
8254 /* Map 8-bit characters to '\xhh' */
8255 if (ucs <= 0xff) {
8256 *p++ = '\\';
8257 *p++ = 'x';
8258 *p++ = hexdigits[(ch >> 4) & 0x000F];
8259 *p++ = hexdigits[ch & 0x000F];
8260 }
8261 /* Map 21-bit characters to '\U00xxxxxx' */
8262 else if (ucs >= 0x10000) {
8263 *p++ = '\\';
8264 *p++ = 'U';
8265 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
8266 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
8267 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
8268 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
8269 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
8270 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
8271 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
8272 *p++ = hexdigits[ucs & 0x0000000F];
8273 }
8274 /* Map 16-bit characters to '\uxxxx' */
8275 else {
8276 *p++ = '\\';
8277 *p++ = 'u';
8278 *p++ = hexdigits[(ucs >> 12) & 0x000F];
8279 *p++ = hexdigits[(ucs >> 8) & 0x000F];
8280 *p++ = hexdigits[(ucs >> 4) & 0x000F];
8281 *p++ = hexdigits[ucs & 0x000F];
8282 }
8283 }
8284 /* Copy characters as-is */
8285 else {
8286 *p++ = ch;
8287#ifndef Py_UNICODE_WIDE
8288 if (ucs >= 0x10000)
8289 *p++ = ch2;
8290#endif
8291 }
8292 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00008293 }
8294 /* Add quote */
Walter Dörwald1ab83302007-05-18 17:15:44 +00008295 *p++ = PyUnicode_AS_UNICODE(repr)[0];
Walter Dörwald79e913e2007-05-12 11:08:06 +00008296
8297 *p = '\0';
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00008298 PyUnicode_Resize(&repr, p - PyUnicode_AS_UNICODE(repr));
Walter Dörwald79e913e2007-05-12 11:08:06 +00008299 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008300}
8301
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008302PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008303 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008304\n\
8305Return the highest index in S where substring sub is found,\n\
Guido van Rossum806c2462007-08-06 23:33:07 +00008306such that sub is contained within s[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008307arguments start and end are interpreted as in slice notation.\n\
8308\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008309Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008310
8311static PyObject *
8312unicode_rfind(PyUnicodeObject *self, PyObject *args)
8313{
Thomas Wouters477c8d52006-05-27 19:21:47 +00008314 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00008315 Py_ssize_t start;
8316 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008317 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008318
Christian Heimes9cd17752007-11-18 19:35:23 +00008319 if (!_ParseTupleFinds(args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008320 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008321
Thomas Wouters477c8d52006-05-27 19:21:47 +00008322 result = stringlib_rfind_slice(
8323 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
8324 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
8325 start, end
8326 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008327
8328 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008329
Christian Heimes217cfd12007-12-02 14:31:20 +00008330 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008331}
8332
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008333PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008334 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008335\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008336Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008337
8338static PyObject *
8339unicode_rindex(PyUnicodeObject *self, PyObject *args)
8340{
Thomas Wouters477c8d52006-05-27 19:21:47 +00008341 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00008342 Py_ssize_t start;
8343 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008344 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008345
Christian Heimes9cd17752007-11-18 19:35:23 +00008346 if (!_ParseTupleFinds(args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008347 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008348
Thomas Wouters477c8d52006-05-27 19:21:47 +00008349 result = stringlib_rfind_slice(
8350 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
8351 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
8352 start, end
8353 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008354
8355 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008356
Guido van Rossumd57fd912000-03-10 22:53:23 +00008357 if (result < 0) {
8358 PyErr_SetString(PyExc_ValueError, "substring not found");
8359 return NULL;
8360 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008361 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008362}
8363
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008364PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008365 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008366\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008367Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008368done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008369
8370static PyObject *
8371unicode_rjust(PyUnicodeObject *self, PyObject *args)
8372{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008373 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008374 Py_UNICODE fillchar = ' ';
8375
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008376 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008377 return NULL;
8378
Tim Peters7a29bd52001-09-12 03:03:31 +00008379 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008380 Py_INCREF(self);
8381 return (PyObject*) self;
8382 }
8383
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008384 return (PyObject*) pad(self, width - self->length, 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008385}
8386
Guido van Rossumd57fd912000-03-10 22:53:23 +00008387PyObject *PyUnicode_Split(PyObject *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00008388 PyObject *sep,
8389 Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008390{
8391 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008392
Guido van Rossumd57fd912000-03-10 22:53:23 +00008393 s = PyUnicode_FromObject(s);
8394 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008395 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00008396 if (sep != NULL) {
8397 sep = PyUnicode_FromObject(sep);
8398 if (sep == NULL) {
8399 Py_DECREF(s);
8400 return NULL;
8401 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008402 }
8403
8404 result = split((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
8405
8406 Py_DECREF(s);
8407 Py_XDECREF(sep);
8408 return result;
8409}
8410
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008411PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008412 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008413\n\
8414Return a list of the words in S, using sep as the\n\
8415delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00008416splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00008417whitespace string is a separator and empty strings are\n\
8418removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008419
8420static PyObject*
8421unicode_split(PyUnicodeObject *self, PyObject *args)
8422{
8423 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008424 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008425
Martin v. Löwis18e16552006-02-15 17:27:45 +00008426 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008427 return NULL;
8428
8429 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008430 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008431 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00008432 return split(self, (PyUnicodeObject *)substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008433 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008434 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008435}
8436
Thomas Wouters477c8d52006-05-27 19:21:47 +00008437PyObject *
8438PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
8439{
8440 PyObject* str_obj;
8441 PyObject* sep_obj;
8442 PyObject* out;
8443
8444 str_obj = PyUnicode_FromObject(str_in);
8445 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008446 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008447 sep_obj = PyUnicode_FromObject(sep_in);
8448 if (!sep_obj) {
8449 Py_DECREF(str_obj);
8450 return NULL;
8451 }
8452
8453 out = stringlib_partition(
8454 str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
8455 sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
8456 );
8457
8458 Py_DECREF(sep_obj);
8459 Py_DECREF(str_obj);
8460
8461 return out;
8462}
8463
8464
8465PyObject *
8466PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
8467{
8468 PyObject* str_obj;
8469 PyObject* sep_obj;
8470 PyObject* out;
8471
8472 str_obj = PyUnicode_FromObject(str_in);
8473 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008474 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008475 sep_obj = PyUnicode_FromObject(sep_in);
8476 if (!sep_obj) {
8477 Py_DECREF(str_obj);
8478 return NULL;
8479 }
8480
8481 out = stringlib_rpartition(
8482 str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
8483 sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
8484 );
8485
8486 Py_DECREF(sep_obj);
8487 Py_DECREF(str_obj);
8488
8489 return out;
8490}
8491
8492PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008493 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008494\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00008495Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008496the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008497found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00008498
8499static PyObject*
8500unicode_partition(PyUnicodeObject *self, PyObject *separator)
8501{
8502 return PyUnicode_Partition((PyObject *)self, separator);
8503}
8504
8505PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +00008506 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008507\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00008508Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008509the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008510separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00008511
8512static PyObject*
8513unicode_rpartition(PyUnicodeObject *self, PyObject *separator)
8514{
8515 return PyUnicode_RPartition((PyObject *)self, separator);
8516}
8517
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008518PyObject *PyUnicode_RSplit(PyObject *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00008519 PyObject *sep,
8520 Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008521{
8522 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008523
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008524 s = PyUnicode_FromObject(s);
8525 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008526 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00008527 if (sep != NULL) {
8528 sep = PyUnicode_FromObject(sep);
8529 if (sep == NULL) {
8530 Py_DECREF(s);
8531 return NULL;
8532 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008533 }
8534
8535 result = rsplit((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
8536
8537 Py_DECREF(s);
8538 Py_XDECREF(sep);
8539 return result;
8540}
8541
8542PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008543 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008544\n\
8545Return a list of the words in S, using sep as the\n\
8546delimiter string, starting at the end of the string and\n\
8547working to the front. If maxsplit is given, at most maxsplit\n\
8548splits are done. If sep is not specified, any whitespace string\n\
8549is a separator.");
8550
8551static PyObject*
8552unicode_rsplit(PyUnicodeObject *self, PyObject *args)
8553{
8554 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008555 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008556
Martin v. Löwis18e16552006-02-15 17:27:45 +00008557 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008558 return NULL;
8559
8560 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008561 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008562 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00008563 return rsplit(self, (PyUnicodeObject *)substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008564 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008565 return PyUnicode_RSplit((PyObject *)self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008566}
8567
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008568PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008569 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008570\n\
8571Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +00008572Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008573is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008574
8575static PyObject*
8576unicode_splitlines(PyUnicodeObject *self, PyObject *args)
8577{
Guido van Rossum86662912000-04-11 15:38:46 +00008578 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008579
Guido van Rossum86662912000-04-11 15:38:46 +00008580 if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008581 return NULL;
8582
Guido van Rossum86662912000-04-11 15:38:46 +00008583 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008584}
8585
8586static
Guido van Rossumf15a29f2007-05-04 00:41:39 +00008587PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008588{
Walter Dörwald346737f2007-05-31 10:44:43 +00008589 if (PyUnicode_CheckExact(self)) {
8590 Py_INCREF(self);
8591 return self;
8592 } else
8593 /* Subtype -- return genuine unicode string with the same value. */
8594 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(self),
8595 PyUnicode_GET_SIZE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +00008596}
8597
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008598PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008599 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008600\n\
8601Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008602and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008603
8604static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008605unicode_swapcase(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008606{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008607 return fixup(self, fixswapcase);
8608}
8609
Georg Brandlceee0772007-11-27 23:48:05 +00008610PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008611 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +00008612\n\
8613Return a translation table usable for str.translate().\n\
8614If there is only one argument, it must be a dictionary mapping Unicode\n\
8615ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008616Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +00008617If there are two arguments, they must be strings of equal length, and\n\
8618in the resulting dictionary, each character in x will be mapped to the\n\
8619character at the same position in y. If there is a third argument, it\n\
8620must be a string, whose characters will be mapped to None in the result.");
8621
8622static PyObject*
8623unicode_maketrans(PyUnicodeObject *null, PyObject *args)
8624{
8625 PyObject *x, *y = NULL, *z = NULL;
8626 PyObject *new = NULL, *key, *value;
8627 Py_ssize_t i = 0;
8628 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008629
Georg Brandlceee0772007-11-27 23:48:05 +00008630 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
8631 return NULL;
8632 new = PyDict_New();
8633 if (!new)
8634 return NULL;
8635 if (y != NULL) {
8636 /* x must be a string too, of equal length */
8637 Py_ssize_t ylen = PyUnicode_GET_SIZE(y);
8638 if (!PyUnicode_Check(x)) {
8639 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
8640 "be a string if there is a second argument");
8641 goto err;
8642 }
8643 if (PyUnicode_GET_SIZE(x) != ylen) {
8644 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
8645 "arguments must have equal length");
8646 goto err;
8647 }
8648 /* create entries for translating chars in x to those in y */
8649 for (i = 0; i < PyUnicode_GET_SIZE(x); i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +00008650 key = PyLong_FromLong(PyUnicode_AS_UNICODE(x)[i]);
8651 value = PyLong_FromLong(PyUnicode_AS_UNICODE(y)[i]);
Georg Brandlceee0772007-11-27 23:48:05 +00008652 if (!key || !value)
8653 goto err;
8654 res = PyDict_SetItem(new, key, value);
8655 Py_DECREF(key);
8656 Py_DECREF(value);
8657 if (res < 0)
8658 goto err;
8659 }
8660 /* create entries for deleting chars in z */
8661 if (z != NULL) {
8662 for (i = 0; i < PyUnicode_GET_SIZE(z); i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +00008663 key = PyLong_FromLong(PyUnicode_AS_UNICODE(z)[i]);
Georg Brandlceee0772007-11-27 23:48:05 +00008664 if (!key)
8665 goto err;
8666 res = PyDict_SetItem(new, key, Py_None);
8667 Py_DECREF(key);
8668 if (res < 0)
8669 goto err;
8670 }
8671 }
8672 } else {
8673 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +00008674 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +00008675 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
8676 "to maketrans it must be a dict");
8677 goto err;
8678 }
8679 /* copy entries into the new dict, converting string keys to int keys */
8680 while (PyDict_Next(x, &i, &key, &value)) {
8681 if (PyUnicode_Check(key)) {
8682 /* convert string keys to integer keys */
8683 PyObject *newkey;
8684 if (PyUnicode_GET_SIZE(key) != 1) {
8685 PyErr_SetString(PyExc_ValueError, "string keys in translate "
8686 "table must be of length 1");
8687 goto err;
8688 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008689 newkey = PyLong_FromLong(PyUnicode_AS_UNICODE(key)[0]);
Georg Brandlceee0772007-11-27 23:48:05 +00008690 if (!newkey)
8691 goto err;
8692 res = PyDict_SetItem(new, newkey, value);
8693 Py_DECREF(newkey);
8694 if (res < 0)
8695 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +00008696 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +00008697 /* just keep integer keys */
8698 if (PyDict_SetItem(new, key, value) < 0)
8699 goto err;
8700 } else {
8701 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
8702 "be strings or integers");
8703 goto err;
8704 }
8705 }
8706 }
8707 return new;
8708 err:
8709 Py_DECREF(new);
8710 return NULL;
8711}
8712
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008713PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008714 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008715\n\
8716Return a copy of the string S, where all characters have been mapped\n\
8717through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008718Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +00008719Unmapped characters are left untouched. Characters mapped to None\n\
8720are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008721
8722static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008723unicode_translate(PyUnicodeObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008724{
Georg Brandlceee0772007-11-27 23:48:05 +00008725 return PyUnicode_TranslateCharmap(self->str, self->length, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008726}
8727
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008728PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008729 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008730\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008731Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008732
8733static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008734unicode_upper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008735{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008736 return fixup(self, fixupper);
8737}
8738
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008739PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008740 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008741\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +00008742Pad a numeric string S with zeros on the left, to fill a field\n\
8743of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008744
8745static PyObject *
8746unicode_zfill(PyUnicodeObject *self, PyObject *args)
8747{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008748 Py_ssize_t fill;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008749 PyUnicodeObject *u;
8750
Martin v. Löwis18e16552006-02-15 17:27:45 +00008751 Py_ssize_t width;
8752 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008753 return NULL;
8754
8755 if (self->length >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +00008756 if (PyUnicode_CheckExact(self)) {
8757 Py_INCREF(self);
8758 return (PyObject*) self;
8759 }
8760 else
8761 return PyUnicode_FromUnicode(
8762 PyUnicode_AS_UNICODE(self),
8763 PyUnicode_GET_SIZE(self)
Benjamin Peterson29060642009-01-31 22:14:21 +00008764 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008765 }
8766
8767 fill = width - self->length;
8768
8769 u = pad(self, fill, 0, '0');
8770
Walter Dörwald068325e2002-04-15 13:36:47 +00008771 if (u == NULL)
8772 return NULL;
8773
Guido van Rossumd57fd912000-03-10 22:53:23 +00008774 if (u->str[fill] == '+' || u->str[fill] == '-') {
8775 /* move sign to beginning of string */
8776 u->str[0] = u->str[fill];
8777 u->str[fill] = '0';
8778 }
8779
8780 return (PyObject*) u;
8781}
Guido van Rossumd57fd912000-03-10 22:53:23 +00008782
8783#if 0
8784static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008785unicode_freelistsize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008786{
Christian Heimes2202f872008-02-06 14:31:34 +00008787 return PyLong_FromLong(numfree);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008788}
8789#endif
8790
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008791PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008792 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008793\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00008794Return True if S starts with the specified prefix, False otherwise.\n\
8795With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008796With optional end, stop comparing S at that position.\n\
8797prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008798
8799static PyObject *
8800unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00008801 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008802{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008803 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008804 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008805 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008806 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008807 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008808
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008809 if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
Benjamin Peterson29060642009-01-31 22:14:21 +00008810 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
8811 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008812 if (PyTuple_Check(subobj)) {
8813 Py_ssize_t i;
8814 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
8815 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +00008816 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008817 if (substring == NULL)
8818 return NULL;
8819 result = tailmatch(self, substring, start, end, -1);
8820 Py_DECREF(substring);
8821 if (result) {
8822 Py_RETURN_TRUE;
8823 }
8824 }
8825 /* nothing matched */
8826 Py_RETURN_FALSE;
8827 }
8828 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008829 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008830 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008831 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008832 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008833 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008834}
8835
8836
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008837PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008838 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008839\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00008840Return True if S ends with the specified suffix, False otherwise.\n\
8841With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008842With optional end, stop comparing S at that position.\n\
8843suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008844
8845static PyObject *
8846unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00008847 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008848{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008849 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008850 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008851 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008852 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008853 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008854
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008855 if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
Benjamin Peterson29060642009-01-31 22:14:21 +00008856 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
8857 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008858 if (PyTuple_Check(subobj)) {
8859 Py_ssize_t i;
8860 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
8861 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +00008862 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008863 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008864 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008865 result = tailmatch(self, substring, start, end, +1);
8866 Py_DECREF(substring);
8867 if (result) {
8868 Py_RETURN_TRUE;
8869 }
8870 }
8871 Py_RETURN_FALSE;
8872 }
8873 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008874 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008875 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008876
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008877 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008878 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008879 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008880}
8881
Eric Smith8c663262007-08-25 02:26:07 +00008882#include "stringlib/string_format.h"
8883
8884PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008885 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +00008886\n\
8887");
8888
Eric Smith4a7d76d2008-05-30 18:10:19 +00008889static PyObject *
8890unicode__format__(PyObject* self, PyObject* args)
8891{
8892 PyObject *format_spec;
8893
8894 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
8895 return NULL;
8896
8897 return _PyUnicode_FormatAdvanced(self,
8898 PyUnicode_AS_UNICODE(format_spec),
8899 PyUnicode_GET_SIZE(format_spec));
8900}
8901
Eric Smith8c663262007-08-25 02:26:07 +00008902PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008903 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +00008904\n\
8905");
8906
8907static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +00008908unicode__sizeof__(PyUnicodeObject *v)
8909{
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00008910 return PyLong_FromSsize_t(sizeof(PyUnicodeObject) +
8911 sizeof(Py_UNICODE) * (v->length + 1));
Georg Brandlc28e1fa2008-06-10 19:20:26 +00008912}
8913
8914PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008915 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00008916
8917static PyObject *
Guido van Rossum5d9113d2003-01-29 17:58:45 +00008918unicode_getnewargs(PyUnicodeObject *v)
8919{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008920 return Py_BuildValue("(u#)", v->str, v->length);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00008921}
8922
8923
Guido van Rossumd57fd912000-03-10 22:53:23 +00008924static PyMethodDef unicode_methods[] = {
8925
8926 /* Order is according to common usage: often used methods should
8927 appear first, since lookup is done sequentially. */
8928
Benjamin Peterson308d6372009-09-18 21:42:35 +00008929 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008930 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
8931 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008932 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008933 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
8934 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
8935 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
8936 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
8937 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
8938 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
8939 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00008940 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008941 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
8942 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
8943 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008944 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008945 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
8946 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
8947 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008948 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00008949 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008950 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008951 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008952 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
8953 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
8954 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
8955 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
8956 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
8957 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
8958 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
8959 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
8960 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
8961 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
8962 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
8963 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
8964 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
8965 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +00008966 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +00008967 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008968 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +00008969 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +00008970 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +00008971 {"maketrans", (PyCFunction) unicode_maketrans,
8972 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +00008973 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +00008974#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008975 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +00008976#endif
8977
8978#if 0
8979 /* This one is just used for debugging the implementation. */
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008980 {"freelistsize", (PyCFunction) unicode_freelistsize, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +00008981#endif
8982
Benjamin Peterson14339b62009-01-31 16:36:08 +00008983 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +00008984 {NULL, NULL}
8985};
8986
Neil Schemenauerce30bc92002-11-18 16:10:18 +00008987static PyObject *
8988unicode_mod(PyObject *v, PyObject *w)
8989{
Benjamin Peterson29060642009-01-31 22:14:21 +00008990 if (!PyUnicode_Check(v)) {
8991 Py_INCREF(Py_NotImplemented);
8992 return Py_NotImplemented;
8993 }
8994 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +00008995}
8996
8997static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008998 0, /*nb_add*/
8999 0, /*nb_subtract*/
9000 0, /*nb_multiply*/
9001 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +00009002};
9003
Guido van Rossumd57fd912000-03-10 22:53:23 +00009004static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009005 (lenfunc) unicode_length, /* sq_length */
9006 PyUnicode_Concat, /* sq_concat */
9007 (ssizeargfunc) unicode_repeat, /* sq_repeat */
9008 (ssizeargfunc) unicode_getitem, /* sq_item */
9009 0, /* sq_slice */
9010 0, /* sq_ass_item */
9011 0, /* sq_ass_slice */
9012 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009013};
9014
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009015static PyObject*
9016unicode_subscript(PyUnicodeObject* self, PyObject* item)
9017{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009018 if (PyIndex_Check(item)) {
9019 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009020 if (i == -1 && PyErr_Occurred())
9021 return NULL;
9022 if (i < 0)
Martin v. Löwisdea59e52006-01-05 10:00:36 +00009023 i += PyUnicode_GET_SIZE(self);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009024 return unicode_getitem(self, i);
9025 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00009026 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009027 Py_UNICODE* source_buf;
9028 Py_UNICODE* result_buf;
9029 PyObject* result;
9030
Martin v. Löwisdea59e52006-01-05 10:00:36 +00009031 if (PySlice_GetIndicesEx((PySliceObject*)item, PyUnicode_GET_SIZE(self),
Benjamin Peterson29060642009-01-31 22:14:21 +00009032 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009033 return NULL;
9034 }
9035
9036 if (slicelength <= 0) {
9037 return PyUnicode_FromUnicode(NULL, 0);
Thomas Woutersed03b412007-08-28 21:37:11 +00009038 } else if (start == 0 && step == 1 && slicelength == self->length &&
9039 PyUnicode_CheckExact(self)) {
9040 Py_INCREF(self);
9041 return (PyObject *)self;
9042 } else if (step == 1) {
9043 return PyUnicode_FromUnicode(self->str + start, slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009044 } else {
9045 source_buf = PyUnicode_AS_UNICODE((PyObject*)self);
Christian Heimesb186d002008-03-18 15:15:01 +00009046 result_buf = (Py_UNICODE *)PyObject_MALLOC(slicelength*
9047 sizeof(Py_UNICODE));
Benjamin Peterson14339b62009-01-31 16:36:08 +00009048
Benjamin Peterson29060642009-01-31 22:14:21 +00009049 if (result_buf == NULL)
9050 return PyErr_NoMemory();
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009051
9052 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
9053 result_buf[i] = source_buf[cur];
9054 }
Tim Petersced69f82003-09-16 20:30:58 +00009055
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009056 result = PyUnicode_FromUnicode(result_buf, slicelength);
Christian Heimesb186d002008-03-18 15:15:01 +00009057 PyObject_FREE(result_buf);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009058 return result;
9059 }
9060 } else {
9061 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
9062 return NULL;
9063 }
9064}
9065
9066static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009067 (lenfunc)unicode_length, /* mp_length */
9068 (binaryfunc)unicode_subscript, /* mp_subscript */
9069 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00009070};
9071
Guido van Rossumd57fd912000-03-10 22:53:23 +00009072
Guido van Rossumd57fd912000-03-10 22:53:23 +00009073/* Helpers for PyUnicode_Format() */
9074
9075static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00009076getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009077{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009078 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009079 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009080 (*p_argidx)++;
9081 if (arglen < 0)
9082 return args;
9083 else
9084 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009085 }
9086 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009087 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009088 return NULL;
9089}
9090
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009091/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009092
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009093static PyObject *
9094formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009095{
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009096 char *p;
9097 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009098 double x;
Tim Petersced69f82003-09-16 20:30:58 +00009099
Guido van Rossumd57fd912000-03-10 22:53:23 +00009100 x = PyFloat_AsDouble(v);
9101 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009102 return NULL;
9103
Guido van Rossumd57fd912000-03-10 22:53:23 +00009104 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009105 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +00009106
Eric Smith0923d1d2009-04-16 20:16:10 +00009107 p = PyOS_double_to_string(x, type, prec,
9108 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009109 if (p == NULL)
9110 return NULL;
9111 result = PyUnicode_FromStringAndSize(p, strlen(p));
Eric Smith0923d1d2009-04-16 20:16:10 +00009112 PyMem_Free(p);
9113 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009114}
9115
Tim Peters38fd5b62000-09-21 05:43:11 +00009116static PyObject*
9117formatlong(PyObject *val, int flags, int prec, int type)
9118{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009119 char *buf;
9120 int len;
9121 PyObject *str; /* temporary string object. */
9122 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +00009123
Benjamin Peterson14339b62009-01-31 16:36:08 +00009124 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
9125 if (!str)
9126 return NULL;
9127 result = PyUnicode_FromStringAndSize(buf, len);
9128 Py_DECREF(str);
9129 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +00009130}
9131
Guido van Rossumd57fd912000-03-10 22:53:23 +00009132static int
9133formatchar(Py_UNICODE *buf,
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009134 size_t buflen,
9135 PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009136{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00009137 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009138 if (PyUnicode_Check(v)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009139 if (PyUnicode_GET_SIZE(v) == 1) {
9140 buf[0] = PyUnicode_AS_UNICODE(v)[0];
9141 buf[1] = '\0';
9142 return 1;
9143 }
9144#ifndef Py_UNICODE_WIDE
9145 if (PyUnicode_GET_SIZE(v) == 2) {
9146 /* Decode a valid surrogate pair */
9147 int c0 = PyUnicode_AS_UNICODE(v)[0];
9148 int c1 = PyUnicode_AS_UNICODE(v)[1];
9149 if (0xD800 <= c0 && c0 <= 0xDBFF &&
9150 0xDC00 <= c1 && c1 <= 0xDFFF) {
9151 buf[0] = c0;
9152 buf[1] = c1;
9153 buf[2] = '\0';
9154 return 2;
9155 }
9156 }
9157#endif
9158 goto onError;
9159 }
9160 else {
9161 /* Integer input truncated to a character */
9162 long x;
9163 x = PyLong_AsLong(v);
9164 if (x == -1 && PyErr_Occurred())
9165 goto onError;
9166
9167 if (x < 0 || x > 0x10ffff) {
9168 PyErr_SetString(PyExc_OverflowError,
9169 "%c arg not in range(0x110000)");
9170 return -1;
9171 }
9172
9173#ifndef Py_UNICODE_WIDE
9174 if (x > 0xffff) {
9175 x -= 0x10000;
9176 buf[0] = (Py_UNICODE)(0xD800 | (x >> 10));
9177 buf[1] = (Py_UNICODE)(0xDC00 | (x & 0x3FF));
9178 return 2;
9179 }
9180#endif
9181 buf[0] = (Py_UNICODE) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009182 buf[1] = '\0';
9183 return 1;
9184 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00009185
Benjamin Peterson29060642009-01-31 22:14:21 +00009186 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009187 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009188 "%c requires int or char");
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009189 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009190}
9191
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009192/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009193 FORMATBUFLEN is the length of the buffer in which chars are formatted.
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009194*/
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009195#define FORMATBUFLEN (size_t)10
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009196
Guido van Rossumd57fd912000-03-10 22:53:23 +00009197PyObject *PyUnicode_Format(PyObject *format,
Benjamin Peterson29060642009-01-31 22:14:21 +00009198 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009199{
9200 Py_UNICODE *fmt, *res;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009201 Py_ssize_t fmtcnt, rescnt, reslen, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009202 int args_owned = 0;
9203 PyUnicodeObject *result = NULL;
9204 PyObject *dict = NULL;
9205 PyObject *uformat;
Tim Petersced69f82003-09-16 20:30:58 +00009206
Guido van Rossumd57fd912000-03-10 22:53:23 +00009207 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009208 PyErr_BadInternalCall();
9209 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009210 }
9211 uformat = PyUnicode_FromObject(format);
Fred Drakee4315f52000-05-09 19:53:39 +00009212 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009213 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009214 fmt = PyUnicode_AS_UNICODE(uformat);
9215 fmtcnt = PyUnicode_GET_SIZE(uformat);
9216
9217 reslen = rescnt = fmtcnt + 100;
9218 result = _PyUnicode_New(reslen);
9219 if (result == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009220 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009221 res = PyUnicode_AS_UNICODE(result);
9222
9223 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009224 arglen = PyTuple_Size(args);
9225 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009226 }
9227 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009228 arglen = -1;
9229 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009230 }
Christian Heimes90aa7642007-12-19 02:45:37 +00009231 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +00009232 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +00009233 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009234
9235 while (--fmtcnt >= 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009236 if (*fmt != '%') {
9237 if (--rescnt < 0) {
9238 rescnt = fmtcnt + 100;
9239 reslen += rescnt;
9240 if (_PyUnicode_Resize(&result, reslen) < 0)
9241 goto onError;
9242 res = PyUnicode_AS_UNICODE(result) + reslen - rescnt;
9243 --rescnt;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009244 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009245 *res++ = *fmt++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009246 }
9247 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009248 /* Got a format specifier */
9249 int flags = 0;
9250 Py_ssize_t width = -1;
9251 int prec = -1;
9252 Py_UNICODE c = '\0';
9253 Py_UNICODE fill;
9254 int isnumok;
9255 PyObject *v = NULL;
9256 PyObject *temp = NULL;
9257 Py_UNICODE *pbuf;
9258 Py_UNICODE sign;
9259 Py_ssize_t len;
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009260 Py_UNICODE formatbuf[FORMATBUFLEN]; /* For formatchar() */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009261
Benjamin Peterson29060642009-01-31 22:14:21 +00009262 fmt++;
9263 if (*fmt == '(') {
9264 Py_UNICODE *keystart;
9265 Py_ssize_t keylen;
9266 PyObject *key;
9267 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +00009268
Benjamin Peterson29060642009-01-31 22:14:21 +00009269 if (dict == NULL) {
9270 PyErr_SetString(PyExc_TypeError,
9271 "format requires a mapping");
9272 goto onError;
9273 }
9274 ++fmt;
9275 --fmtcnt;
9276 keystart = fmt;
9277 /* Skip over balanced parentheses */
9278 while (pcount > 0 && --fmtcnt >= 0) {
9279 if (*fmt == ')')
9280 --pcount;
9281 else if (*fmt == '(')
9282 ++pcount;
9283 fmt++;
9284 }
9285 keylen = fmt - keystart - 1;
9286 if (fmtcnt < 0 || pcount > 0) {
9287 PyErr_SetString(PyExc_ValueError,
9288 "incomplete format key");
9289 goto onError;
9290 }
9291#if 0
9292 /* keys are converted to strings using UTF-8 and
9293 then looked up since Python uses strings to hold
9294 variables names etc. in its namespaces and we
9295 wouldn't want to break common idioms. */
9296 key = PyUnicode_EncodeUTF8(keystart,
9297 keylen,
9298 NULL);
9299#else
9300 key = PyUnicode_FromUnicode(keystart, keylen);
9301#endif
9302 if (key == NULL)
9303 goto onError;
9304 if (args_owned) {
9305 Py_DECREF(args);
9306 args_owned = 0;
9307 }
9308 args = PyObject_GetItem(dict, key);
9309 Py_DECREF(key);
9310 if (args == NULL) {
9311 goto onError;
9312 }
9313 args_owned = 1;
9314 arglen = -1;
9315 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009316 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009317 while (--fmtcnt >= 0) {
9318 switch (c = *fmt++) {
9319 case '-': flags |= F_LJUST; continue;
9320 case '+': flags |= F_SIGN; continue;
9321 case ' ': flags |= F_BLANK; continue;
9322 case '#': flags |= F_ALT; continue;
9323 case '0': flags |= F_ZERO; continue;
9324 }
9325 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009326 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009327 if (c == '*') {
9328 v = getnextarg(args, arglen, &argidx);
9329 if (v == NULL)
9330 goto onError;
9331 if (!PyLong_Check(v)) {
9332 PyErr_SetString(PyExc_TypeError,
9333 "* wants int");
9334 goto onError;
9335 }
9336 width = PyLong_AsLong(v);
9337 if (width == -1 && PyErr_Occurred())
9338 goto onError;
9339 if (width < 0) {
9340 flags |= F_LJUST;
9341 width = -width;
9342 }
9343 if (--fmtcnt >= 0)
9344 c = *fmt++;
9345 }
9346 else if (c >= '0' && c <= '9') {
9347 width = c - '0';
9348 while (--fmtcnt >= 0) {
9349 c = *fmt++;
9350 if (c < '0' || c > '9')
9351 break;
9352 if ((width*10) / 10 != width) {
9353 PyErr_SetString(PyExc_ValueError,
9354 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009355 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00009356 }
9357 width = width*10 + (c - '0');
9358 }
9359 }
9360 if (c == '.') {
9361 prec = 0;
9362 if (--fmtcnt >= 0)
9363 c = *fmt++;
9364 if (c == '*') {
9365 v = getnextarg(args, arglen, &argidx);
9366 if (v == NULL)
9367 goto onError;
9368 if (!PyLong_Check(v)) {
9369 PyErr_SetString(PyExc_TypeError,
9370 "* wants int");
9371 goto onError;
9372 }
9373 prec = PyLong_AsLong(v);
9374 if (prec == -1 && PyErr_Occurred())
9375 goto onError;
9376 if (prec < 0)
9377 prec = 0;
9378 if (--fmtcnt >= 0)
9379 c = *fmt++;
9380 }
9381 else if (c >= '0' && c <= '9') {
9382 prec = c - '0';
9383 while (--fmtcnt >= 0) {
Stefan Krah99212f62010-07-19 17:58:26 +00009384 c = *fmt++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009385 if (c < '0' || c > '9')
9386 break;
9387 if ((prec*10) / 10 != prec) {
9388 PyErr_SetString(PyExc_ValueError,
9389 "prec too big");
9390 goto onError;
9391 }
9392 prec = prec*10 + (c - '0');
9393 }
9394 }
9395 } /* prec */
9396 if (fmtcnt >= 0) {
9397 if (c == 'h' || c == 'l' || c == 'L') {
9398 if (--fmtcnt >= 0)
9399 c = *fmt++;
9400 }
9401 }
9402 if (fmtcnt < 0) {
9403 PyErr_SetString(PyExc_ValueError,
9404 "incomplete format");
9405 goto onError;
9406 }
9407 if (c != '%') {
9408 v = getnextarg(args, arglen, &argidx);
9409 if (v == NULL)
9410 goto onError;
9411 }
9412 sign = 0;
9413 fill = ' ';
9414 switch (c) {
9415
9416 case '%':
9417 pbuf = formatbuf;
9418 /* presume that buffer length is at least 1 */
9419 pbuf[0] = '%';
9420 len = 1;
9421 break;
9422
9423 case 's':
9424 case 'r':
9425 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +00009426 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +00009427 temp = v;
9428 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009429 }
9430 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009431 if (c == 's')
9432 temp = PyObject_Str(v);
9433 else if (c == 'r')
9434 temp = PyObject_Repr(v);
9435 else
9436 temp = PyObject_ASCII(v);
9437 if (temp == NULL)
9438 goto onError;
9439 if (PyUnicode_Check(temp))
9440 /* nothing to do */;
9441 else {
9442 Py_DECREF(temp);
9443 PyErr_SetString(PyExc_TypeError,
9444 "%s argument has non-string str()");
9445 goto onError;
9446 }
9447 }
9448 pbuf = PyUnicode_AS_UNICODE(temp);
9449 len = PyUnicode_GET_SIZE(temp);
9450 if (prec >= 0 && len > prec)
9451 len = prec;
9452 break;
9453
9454 case 'i':
9455 case 'd':
9456 case 'u':
9457 case 'o':
9458 case 'x':
9459 case 'X':
9460 if (c == 'i')
9461 c = 'd';
9462 isnumok = 0;
9463 if (PyNumber_Check(v)) {
9464 PyObject *iobj=NULL;
9465
9466 if (PyLong_Check(v)) {
9467 iobj = v;
9468 Py_INCREF(iobj);
9469 }
9470 else {
9471 iobj = PyNumber_Long(v);
9472 }
9473 if (iobj!=NULL) {
9474 if (PyLong_Check(iobj)) {
9475 isnumok = 1;
9476 temp = formatlong(iobj, flags, prec, c);
9477 Py_DECREF(iobj);
9478 if (!temp)
9479 goto onError;
9480 pbuf = PyUnicode_AS_UNICODE(temp);
9481 len = PyUnicode_GET_SIZE(temp);
9482 sign = 1;
9483 }
9484 else {
9485 Py_DECREF(iobj);
9486 }
9487 }
9488 }
9489 if (!isnumok) {
9490 PyErr_Format(PyExc_TypeError,
9491 "%%%c format: a number is required, "
9492 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
9493 goto onError;
9494 }
9495 if (flags & F_ZERO)
9496 fill = '0';
9497 break;
9498
9499 case 'e':
9500 case 'E':
9501 case 'f':
9502 case 'F':
9503 case 'g':
9504 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009505 temp = formatfloat(v, flags, prec, c);
9506 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +00009507 goto onError;
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009508 pbuf = PyUnicode_AS_UNICODE(temp);
9509 len = PyUnicode_GET_SIZE(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +00009510 sign = 1;
9511 if (flags & F_ZERO)
9512 fill = '0';
9513 break;
9514
9515 case 'c':
9516 pbuf = formatbuf;
9517 len = formatchar(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), v);
9518 if (len < 0)
9519 goto onError;
9520 break;
9521
9522 default:
9523 PyErr_Format(PyExc_ValueError,
9524 "unsupported format character '%c' (0x%x) "
9525 "at index %zd",
9526 (31<=c && c<=126) ? (char)c : '?',
9527 (int)c,
9528 (Py_ssize_t)(fmt - 1 -
9529 PyUnicode_AS_UNICODE(uformat)));
9530 goto onError;
9531 }
9532 if (sign) {
9533 if (*pbuf == '-' || *pbuf == '+') {
9534 sign = *pbuf++;
9535 len--;
9536 }
9537 else if (flags & F_SIGN)
9538 sign = '+';
9539 else if (flags & F_BLANK)
9540 sign = ' ';
9541 else
9542 sign = 0;
9543 }
9544 if (width < len)
9545 width = len;
9546 if (rescnt - (sign != 0) < width) {
9547 reslen -= rescnt;
9548 rescnt = width + fmtcnt + 100;
9549 reslen += rescnt;
9550 if (reslen < 0) {
9551 Py_XDECREF(temp);
9552 PyErr_NoMemory();
9553 goto onError;
9554 }
9555 if (_PyUnicode_Resize(&result, reslen) < 0) {
9556 Py_XDECREF(temp);
9557 goto onError;
9558 }
9559 res = PyUnicode_AS_UNICODE(result)
9560 + reslen - rescnt;
9561 }
9562 if (sign) {
9563 if (fill != ' ')
9564 *res++ = sign;
9565 rescnt--;
9566 if (width > len)
9567 width--;
9568 }
9569 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
9570 assert(pbuf[0] == '0');
9571 assert(pbuf[1] == c);
9572 if (fill != ' ') {
9573 *res++ = *pbuf++;
9574 *res++ = *pbuf++;
9575 }
9576 rescnt -= 2;
9577 width -= 2;
9578 if (width < 0)
9579 width = 0;
9580 len -= 2;
9581 }
9582 if (width > len && !(flags & F_LJUST)) {
9583 do {
9584 --rescnt;
9585 *res++ = fill;
9586 } while (--width > len);
9587 }
9588 if (fill == ' ') {
9589 if (sign)
9590 *res++ = sign;
9591 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
9592 assert(pbuf[0] == '0');
9593 assert(pbuf[1] == c);
9594 *res++ = *pbuf++;
9595 *res++ = *pbuf++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009596 }
9597 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009598 Py_UNICODE_COPY(res, pbuf, len);
9599 res += len;
9600 rescnt -= len;
9601 while (--width >= len) {
9602 --rescnt;
9603 *res++ = ' ';
9604 }
9605 if (dict && (argidx < arglen) && c != '%') {
9606 PyErr_SetString(PyExc_TypeError,
9607 "not all arguments converted during string formatting");
Thomas Woutersa96affe2006-03-12 00:29:36 +00009608 Py_XDECREF(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +00009609 goto onError;
9610 }
9611 Py_XDECREF(temp);
9612 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009613 } /* until end */
9614 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009615 PyErr_SetString(PyExc_TypeError,
9616 "not all arguments converted during string formatting");
9617 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009618 }
9619
Thomas Woutersa96affe2006-03-12 00:29:36 +00009620 if (_PyUnicode_Resize(&result, reslen - rescnt) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009621 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009622 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009623 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009624 }
9625 Py_DECREF(uformat);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009626 return (PyObject *)result;
9627
Benjamin Peterson29060642009-01-31 22:14:21 +00009628 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009629 Py_XDECREF(result);
9630 Py_DECREF(uformat);
9631 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009632 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009633 }
9634 return NULL;
9635}
9636
Jeremy Hylton938ace62002-07-17 16:30:39 +00009637static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +00009638unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
9639
Tim Peters6d6c1a32001-08-02 04:15:00 +00009640static PyObject *
9641unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9642{
Benjamin Peterson29060642009-01-31 22:14:21 +00009643 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009644 static char *kwlist[] = {"object", "encoding", "errors", 0};
9645 char *encoding = NULL;
9646 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00009647
Benjamin Peterson14339b62009-01-31 16:36:08 +00009648 if (type != &PyUnicode_Type)
9649 return unicode_subtype_new(type, args, kwds);
9650 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +00009651 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009652 return NULL;
9653 if (x == NULL)
9654 return (PyObject *)_PyUnicode_New(0);
9655 if (encoding == NULL && errors == NULL)
9656 return PyObject_Str(x);
9657 else
Benjamin Peterson29060642009-01-31 22:14:21 +00009658 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +00009659}
9660
Guido van Rossume023fe02001-08-30 03:12:59 +00009661static PyObject *
9662unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9663{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009664 PyUnicodeObject *tmp, *pnew;
9665 Py_ssize_t n;
Guido van Rossume023fe02001-08-30 03:12:59 +00009666
Benjamin Peterson14339b62009-01-31 16:36:08 +00009667 assert(PyType_IsSubtype(type, &PyUnicode_Type));
9668 tmp = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
9669 if (tmp == NULL)
9670 return NULL;
9671 assert(PyUnicode_Check(tmp));
9672 pnew = (PyUnicodeObject *) type->tp_alloc(type, n = tmp->length);
9673 if (pnew == NULL) {
9674 Py_DECREF(tmp);
9675 return NULL;
9676 }
9677 pnew->str = (Py_UNICODE*) PyObject_MALLOC(sizeof(Py_UNICODE) * (n+1));
9678 if (pnew->str == NULL) {
9679 _Py_ForgetReference((PyObject *)pnew);
9680 PyObject_Del(pnew);
9681 Py_DECREF(tmp);
9682 return PyErr_NoMemory();
9683 }
9684 Py_UNICODE_COPY(pnew->str, tmp->str, n+1);
9685 pnew->length = n;
9686 pnew->hash = tmp->hash;
9687 Py_DECREF(tmp);
9688 return (PyObject *)pnew;
Guido van Rossume023fe02001-08-30 03:12:59 +00009689}
9690
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009691PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +00009692 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00009693\n\
Collin Winterd474ce82007-08-07 19:42:11 +00009694Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +00009695encoding defaults to the current default string encoding.\n\
9696errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00009697
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009698static PyObject *unicode_iter(PyObject *seq);
9699
Guido van Rossumd57fd912000-03-10 22:53:23 +00009700PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00009701 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +00009702 "str", /* tp_name */
9703 sizeof(PyUnicodeObject), /* tp_size */
9704 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009705 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009706 (destructor)unicode_dealloc, /* tp_dealloc */
9707 0, /* tp_print */
9708 0, /* tp_getattr */
9709 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00009710 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009711 unicode_repr, /* tp_repr */
9712 &unicode_as_number, /* tp_as_number */
9713 &unicode_as_sequence, /* tp_as_sequence */
9714 &unicode_as_mapping, /* tp_as_mapping */
9715 (hashfunc) unicode_hash, /* tp_hash*/
9716 0, /* tp_call*/
9717 (reprfunc) unicode_str, /* tp_str */
9718 PyObject_GenericGetAttr, /* tp_getattro */
9719 0, /* tp_setattro */
9720 0, /* tp_as_buffer */
9721 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +00009722 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009723 unicode_doc, /* tp_doc */
9724 0, /* tp_traverse */
9725 0, /* tp_clear */
9726 PyUnicode_RichCompare, /* tp_richcompare */
9727 0, /* tp_weaklistoffset */
9728 unicode_iter, /* tp_iter */
9729 0, /* tp_iternext */
9730 unicode_methods, /* tp_methods */
9731 0, /* tp_members */
9732 0, /* tp_getset */
9733 &PyBaseObject_Type, /* tp_base */
9734 0, /* tp_dict */
9735 0, /* tp_descr_get */
9736 0, /* tp_descr_set */
9737 0, /* tp_dictoffset */
9738 0, /* tp_init */
9739 0, /* tp_alloc */
9740 unicode_new, /* tp_new */
9741 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009742};
9743
9744/* Initialize the Unicode implementation */
9745
Thomas Wouters78890102000-07-22 19:25:51 +00009746void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009747{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009748 int i;
9749
Thomas Wouters477c8d52006-05-27 19:21:47 +00009750 /* XXX - move this array to unicodectype.c ? */
9751 Py_UNICODE linebreak[] = {
9752 0x000A, /* LINE FEED */
9753 0x000D, /* CARRIAGE RETURN */
9754 0x001C, /* FILE SEPARATOR */
9755 0x001D, /* GROUP SEPARATOR */
9756 0x001E, /* RECORD SEPARATOR */
9757 0x0085, /* NEXT LINE */
9758 0x2028, /* LINE SEPARATOR */
9759 0x2029, /* PARAGRAPH SEPARATOR */
9760 };
9761
Fred Drakee4315f52000-05-09 19:53:39 +00009762 /* Init the implementation */
Christian Heimes2202f872008-02-06 14:31:34 +00009763 free_list = NULL;
9764 numfree = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009765 unicode_empty = _PyUnicode_New(0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009766 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00009767 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009768
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009769 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00009770 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +00009771 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009772 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +00009773
9774 /* initialize the linebreak bloom filter */
9775 bloom_linebreak = make_bloom_mask(
9776 linebreak, sizeof(linebreak) / sizeof(linebreak[0])
9777 );
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009778
9779 PyType_Ready(&EncodingMapType);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009780}
9781
9782/* Finalize the Unicode implementation */
9783
Christian Heimesa156e092008-02-16 07:38:31 +00009784int
9785PyUnicode_ClearFreeList(void)
9786{
9787 int freelist_size = numfree;
9788 PyUnicodeObject *u;
9789
9790 for (u = free_list; u != NULL;) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009791 PyUnicodeObject *v = u;
9792 u = *(PyUnicodeObject **)u;
9793 if (v->str)
9794 PyObject_DEL(v->str);
9795 Py_XDECREF(v->defenc);
9796 PyObject_Del(v);
9797 numfree--;
Christian Heimesa156e092008-02-16 07:38:31 +00009798 }
9799 free_list = NULL;
9800 assert(numfree == 0);
9801 return freelist_size;
9802}
9803
Guido van Rossumd57fd912000-03-10 22:53:23 +00009804void
Thomas Wouters78890102000-07-22 19:25:51 +00009805_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009806{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009807 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009808
Guido van Rossum4ae8ef82000-10-03 18:09:04 +00009809 Py_XDECREF(unicode_empty);
9810 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +00009811
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009812 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009813 if (unicode_latin1[i]) {
9814 Py_DECREF(unicode_latin1[i]);
9815 unicode_latin1[i] = NULL;
9816 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009817 }
Christian Heimesa156e092008-02-16 07:38:31 +00009818 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +00009819}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00009820
Walter Dörwald16807132007-05-25 13:52:07 +00009821void
9822PyUnicode_InternInPlace(PyObject **p)
9823{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009824 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
9825 PyObject *t;
9826 if (s == NULL || !PyUnicode_Check(s))
9827 Py_FatalError(
9828 "PyUnicode_InternInPlace: unicode strings only please!");
9829 /* If it's a subclass, we don't really know what putting
9830 it in the interned dict might do. */
9831 if (!PyUnicode_CheckExact(s))
9832 return;
9833 if (PyUnicode_CHECK_INTERNED(s))
9834 return;
9835 if (interned == NULL) {
9836 interned = PyDict_New();
9837 if (interned == NULL) {
9838 PyErr_Clear(); /* Don't leave an exception */
9839 return;
9840 }
9841 }
9842 /* It might be that the GetItem call fails even
9843 though the key is present in the dictionary,
9844 namely when this happens during a stack overflow. */
9845 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +00009846 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009847 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +00009848
Benjamin Peterson29060642009-01-31 22:14:21 +00009849 if (t) {
9850 Py_INCREF(t);
9851 Py_DECREF(*p);
9852 *p = t;
9853 return;
9854 }
Walter Dörwald16807132007-05-25 13:52:07 +00009855
Benjamin Peterson14339b62009-01-31 16:36:08 +00009856 PyThreadState_GET()->recursion_critical = 1;
9857 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
9858 PyErr_Clear();
9859 PyThreadState_GET()->recursion_critical = 0;
9860 return;
9861 }
9862 PyThreadState_GET()->recursion_critical = 0;
9863 /* The two references in interned are not counted by refcnt.
9864 The deallocator will take care of this */
9865 Py_REFCNT(s) -= 2;
9866 PyUnicode_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +00009867}
9868
9869void
9870PyUnicode_InternImmortal(PyObject **p)
9871{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009872 PyUnicode_InternInPlace(p);
9873 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
9874 PyUnicode_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
9875 Py_INCREF(*p);
9876 }
Walter Dörwald16807132007-05-25 13:52:07 +00009877}
9878
9879PyObject *
9880PyUnicode_InternFromString(const char *cp)
9881{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009882 PyObject *s = PyUnicode_FromString(cp);
9883 if (s == NULL)
9884 return NULL;
9885 PyUnicode_InternInPlace(&s);
9886 return s;
Walter Dörwald16807132007-05-25 13:52:07 +00009887}
9888
9889void _Py_ReleaseInternedUnicodeStrings(void)
9890{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009891 PyObject *keys;
9892 PyUnicodeObject *s;
9893 Py_ssize_t i, n;
9894 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +00009895
Benjamin Peterson14339b62009-01-31 16:36:08 +00009896 if (interned == NULL || !PyDict_Check(interned))
9897 return;
9898 keys = PyDict_Keys(interned);
9899 if (keys == NULL || !PyList_Check(keys)) {
9900 PyErr_Clear();
9901 return;
9902 }
Walter Dörwald16807132007-05-25 13:52:07 +00009903
Benjamin Peterson14339b62009-01-31 16:36:08 +00009904 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
9905 detector, interned unicode strings are not forcibly deallocated;
9906 rather, we give them their stolen references back, and then clear
9907 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +00009908
Benjamin Peterson14339b62009-01-31 16:36:08 +00009909 n = PyList_GET_SIZE(keys);
9910 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +00009911 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009912 for (i = 0; i < n; i++) {
9913 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
9914 switch (s->state) {
9915 case SSTATE_NOT_INTERNED:
9916 /* XXX Shouldn't happen */
9917 break;
9918 case SSTATE_INTERNED_IMMORTAL:
9919 Py_REFCNT(s) += 1;
9920 immortal_size += s->length;
9921 break;
9922 case SSTATE_INTERNED_MORTAL:
9923 Py_REFCNT(s) += 2;
9924 mortal_size += s->length;
9925 break;
9926 default:
9927 Py_FatalError("Inconsistent interned string state.");
9928 }
9929 s->state = SSTATE_NOT_INTERNED;
9930 }
9931 fprintf(stderr, "total size of all interned strings: "
9932 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
9933 "mortal/immortal\n", mortal_size, immortal_size);
9934 Py_DECREF(keys);
9935 PyDict_Clear(interned);
9936 Py_DECREF(interned);
9937 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +00009938}
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009939
9940
9941/********************* Unicode Iterator **************************/
9942
9943typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009944 PyObject_HEAD
9945 Py_ssize_t it_index;
9946 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009947} unicodeiterobject;
9948
9949static void
9950unicodeiter_dealloc(unicodeiterobject *it)
9951{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009952 _PyObject_GC_UNTRACK(it);
9953 Py_XDECREF(it->it_seq);
9954 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009955}
9956
9957static int
9958unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
9959{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009960 Py_VISIT(it->it_seq);
9961 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009962}
9963
9964static PyObject *
9965unicodeiter_next(unicodeiterobject *it)
9966{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009967 PyUnicodeObject *seq;
9968 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009969
Benjamin Peterson14339b62009-01-31 16:36:08 +00009970 assert(it != NULL);
9971 seq = it->it_seq;
9972 if (seq == NULL)
9973 return NULL;
9974 assert(PyUnicode_Check(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009975
Benjamin Peterson14339b62009-01-31 16:36:08 +00009976 if (it->it_index < PyUnicode_GET_SIZE(seq)) {
9977 item = PyUnicode_FromUnicode(
Benjamin Peterson29060642009-01-31 22:14:21 +00009978 PyUnicode_AS_UNICODE(seq)+it->it_index, 1);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009979 if (item != NULL)
9980 ++it->it_index;
9981 return item;
9982 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009983
Benjamin Peterson14339b62009-01-31 16:36:08 +00009984 Py_DECREF(seq);
9985 it->it_seq = NULL;
9986 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009987}
9988
9989static PyObject *
9990unicodeiter_len(unicodeiterobject *it)
9991{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009992 Py_ssize_t len = 0;
9993 if (it->it_seq)
9994 len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index;
9995 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009996}
9997
9998PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
9999
10000static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010001 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000010002 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000010003 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010004};
10005
10006PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010007 PyVarObject_HEAD_INIT(&PyType_Type, 0)
10008 "str_iterator", /* tp_name */
10009 sizeof(unicodeiterobject), /* tp_basicsize */
10010 0, /* tp_itemsize */
10011 /* methods */
10012 (destructor)unicodeiter_dealloc, /* tp_dealloc */
10013 0, /* tp_print */
10014 0, /* tp_getattr */
10015 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000010016 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000010017 0, /* tp_repr */
10018 0, /* tp_as_number */
10019 0, /* tp_as_sequence */
10020 0, /* tp_as_mapping */
10021 0, /* tp_hash */
10022 0, /* tp_call */
10023 0, /* tp_str */
10024 PyObject_GenericGetAttr, /* tp_getattro */
10025 0, /* tp_setattro */
10026 0, /* tp_as_buffer */
10027 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
10028 0, /* tp_doc */
10029 (traverseproc)unicodeiter_traverse, /* tp_traverse */
10030 0, /* tp_clear */
10031 0, /* tp_richcompare */
10032 0, /* tp_weaklistoffset */
10033 PyObject_SelfIter, /* tp_iter */
10034 (iternextfunc)unicodeiter_next, /* tp_iternext */
10035 unicodeiter_methods, /* tp_methods */
10036 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010037};
10038
10039static PyObject *
10040unicode_iter(PyObject *seq)
10041{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010042 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010043
Benjamin Peterson14339b62009-01-31 16:36:08 +000010044 if (!PyUnicode_Check(seq)) {
10045 PyErr_BadInternalCall();
10046 return NULL;
10047 }
10048 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
10049 if (it == NULL)
10050 return NULL;
10051 it->it_index = 0;
10052 Py_INCREF(seq);
10053 it->it_seq = (PyUnicodeObject *)seq;
10054 _PyObject_GC_TRACK(it);
10055 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000010056}
10057
Martin v. Löwis5b222132007-06-10 09:51:05 +000010058size_t
10059Py_UNICODE_strlen(const Py_UNICODE *u)
10060{
10061 int res = 0;
10062 while(*u++)
10063 res++;
10064 return res;
10065}
10066
10067Py_UNICODE*
10068Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
10069{
10070 Py_UNICODE *u = s1;
10071 while ((*u++ = *s2++));
10072 return s1;
10073}
10074
10075Py_UNICODE*
10076Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
10077{
10078 Py_UNICODE *u = s1;
10079 while ((*u++ = *s2++))
10080 if (n-- == 0)
10081 break;
10082 return s1;
10083}
10084
Victor Stinnerc4eb7652010-09-01 23:43:50 +000010085Py_UNICODE*
10086Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
10087{
10088 Py_UNICODE *u1 = s1;
10089 u1 += Py_UNICODE_strlen(u1);
10090 Py_UNICODE_strcpy(u1, s2);
10091 return s1;
10092}
10093
Martin v. Löwis5b222132007-06-10 09:51:05 +000010094int
10095Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
10096{
10097 while (*s1 && *s2 && *s1 == *s2)
10098 s1++, s2++;
10099 if (*s1 && *s2)
10100 return (*s1 < *s2) ? -1 : +1;
10101 if (*s1)
10102 return 1;
10103 if (*s2)
10104 return -1;
10105 return 0;
10106}
10107
Victor Stinneref8d95c2010-08-16 22:03:11 +000010108int
10109Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
10110{
10111 register Py_UNICODE u1, u2;
10112 for (; n != 0; n--) {
10113 u1 = *s1;
10114 u2 = *s2;
10115 if (u1 != u2)
10116 return (u1 < u2) ? -1 : +1;
10117 if (u1 == '\0')
10118 return 0;
10119 s1++;
10120 s2++;
10121 }
10122 return 0;
10123}
10124
Martin v. Löwis5b222132007-06-10 09:51:05 +000010125Py_UNICODE*
10126Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
10127{
10128 const Py_UNICODE *p;
10129 for (p = s; *p; p++)
10130 if (*p == c)
10131 return (Py_UNICODE*)p;
10132 return NULL;
10133}
10134
Victor Stinner331ea922010-08-10 16:37:20 +000010135Py_UNICODE*
10136Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
10137{
10138 const Py_UNICODE *p;
10139 p = s + Py_UNICODE_strlen(s);
10140 while (p != s) {
10141 p--;
10142 if (*p == c)
10143 return (Py_UNICODE*)p;
10144 }
10145 return NULL;
10146}
10147
Victor Stinner71133ff2010-09-01 23:43:53 +000010148Py_UNICODE*
Victor Stinner46408602010-09-03 16:18:00 +000010149PyUnicode_AsUnicodeCopy(PyObject *object)
Victor Stinner71133ff2010-09-01 23:43:53 +000010150{
10151 PyUnicodeObject *unicode = (PyUnicodeObject *)object;
10152 Py_UNICODE *copy;
10153 Py_ssize_t size;
10154
10155 /* Ensure we won't overflow the size. */
10156 if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
10157 PyErr_NoMemory();
10158 return NULL;
10159 }
10160 size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
10161 size *= sizeof(Py_UNICODE);
10162 copy = PyMem_Malloc(size);
10163 if (copy == NULL) {
10164 PyErr_NoMemory();
10165 return NULL;
10166 }
10167 memcpy(copy, PyUnicode_AS_UNICODE(unicode), size);
10168 return copy;
10169}
Martin v. Löwis5b222132007-06-10 09:51:05 +000010170
Georg Brandl66c221e2010-10-14 07:04:07 +000010171/* A _string module, to export formatter_parser and formatter_field_name_split
10172 to the string.Formatter class implemented in Python. */
10173
10174static PyMethodDef _string_methods[] = {
10175 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
10176 METH_O, PyDoc_STR("split the argument as a field name")},
10177 {"formatter_parser", (PyCFunction) formatter_parser,
10178 METH_O, PyDoc_STR("parse the argument as a format string")},
10179 {NULL, NULL}
10180};
10181
10182static struct PyModuleDef _string_module = {
10183 PyModuleDef_HEAD_INIT,
10184 "_string",
10185 PyDoc_STR("string helper module"),
10186 0,
10187 _string_methods,
10188 NULL,
10189 NULL,
10190 NULL,
10191 NULL
10192};
10193
10194PyMODINIT_FUNC
10195PyInit__string(void)
10196{
10197 return PyModule_Create(&_string_module);
10198}
10199
10200
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010201#ifdef __cplusplus
10202}
10203#endif