blob: 47e0933174aacc1e3ee4a791372e355002a047d0 [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
Fred Drakee4315f52000-05-09 19:53:39 +0000117/* Default encoding to use and assume when NULL is passed as encoding
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000118 parameter; it is fixed to "utf-8". Always use the
Guido van Rossum00bc0e02007-10-15 02:52:41 +0000119 PyUnicode_GetDefaultEncoding() API to access this global.
120
Alexandre Vassalotti3d2fd7f2007-10-16 00:26:33 +0000121 Don't forget to alter Py_FileSystemDefaultEncoding if you change the
Guido van Rossum00bc0e02007-10-15 02:52:41 +0000122 hard coded default!
123*/
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000124static const char unicode_default_encoding[] = "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +0000125
Christian Heimes190d79e2008-01-30 11:58:22 +0000126/* Fast detection of the most frequent whitespace characters */
127const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000128 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000129/* case 0x0009: * HORIZONTAL TABULATION */
130/* case 0x000A: * LINE FEED */
131/* case 0x000B: * VERTICAL TABULATION */
132/* case 0x000C: * FORM FEED */
133/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000134 0, 1, 1, 1, 1, 1, 0, 0,
135 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000136/* case 0x001C: * FILE SEPARATOR */
137/* case 0x001D: * GROUP SEPARATOR */
138/* case 0x001E: * RECORD SEPARATOR */
139/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000140 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000141/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000142 1, 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
Benjamin Peterson14339b62009-01-31 16:36:08 +0000147 0, 0, 0, 0, 0, 0, 0, 0,
148 0, 0, 0, 0, 0, 0, 0, 0,
149 0, 0, 0, 0, 0, 0, 0, 0,
150 0, 0, 0, 0, 0, 0, 0, 0,
151 0, 0, 0, 0, 0, 0, 0, 0,
152 0, 0, 0, 0, 0, 0, 0, 0,
153 0, 0, 0, 0, 0, 0, 0, 0,
154 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000155};
156
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000157static PyObject *unicode_encode_call_errorhandler(const char *errors,
158 PyObject **errorHandler,const char *encoding, const char *reason,
159 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
160 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
161
Christian Heimes190d79e2008-01-30 11:58:22 +0000162/* Same for linebreaks */
163static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000164 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000165/* 0x000A, * LINE FEED */
166/* 0x000D, * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000167 0, 0, 1, 0, 0, 1, 0, 0,
168 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000169/* 0x001C, * FILE SEPARATOR */
170/* 0x001D, * GROUP SEPARATOR */
171/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000172 0, 0, 0, 0, 1, 1, 1, 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,
176 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000177
Benjamin Peterson14339b62009-01-31 16:36:08 +0000178 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,
185 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000186};
187
188
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000189Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000190PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000191{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000192#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000193 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000194#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000195 /* This is actually an illegal character, so it should
196 not be passed to unichr. */
197 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000198#endif
199}
200
Thomas Wouters477c8d52006-05-27 19:21:47 +0000201/* --- Bloom Filters ----------------------------------------------------- */
202
203/* stuff to implement simple "bloom filters" for Unicode characters.
204 to keep things simple, we use a single bitmask, using the least 5
205 bits from each unicode characters as the bit index. */
206
207/* the linebreak mask is set up by Unicode_Init below */
208
209#define BLOOM_MASK unsigned long
210
211static BLOOM_MASK bloom_linebreak;
212
213#define BLOOM(mask, ch) ((mask & (1 << ((ch) & 0x1F))))
214
Benjamin Peterson29060642009-01-31 22:14:21 +0000215#define BLOOM_LINEBREAK(ch) \
216 ((ch) < 128U ? ascii_linebreak[(ch)] : \
217 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000218
219Py_LOCAL_INLINE(BLOOM_MASK) make_bloom_mask(Py_UNICODE* ptr, Py_ssize_t len)
220{
221 /* calculate simple bloom-style bitmask for a given unicode string */
222
223 long mask;
224 Py_ssize_t i;
225
226 mask = 0;
227 for (i = 0; i < len; i++)
228 mask |= (1 << (ptr[i] & 0x1F));
229
230 return mask;
231}
232
233Py_LOCAL_INLINE(int) unicode_member(Py_UNICODE chr, Py_UNICODE* set, Py_ssize_t setlen)
234{
235 Py_ssize_t i;
236
237 for (i = 0; i < setlen; i++)
238 if (set[i] == chr)
239 return 1;
240
241 return 0;
242}
243
Benjamin Peterson29060642009-01-31 22:14:21 +0000244#define BLOOM_MEMBER(mask, chr, set, setlen) \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000245 BLOOM(mask, chr) && unicode_member(chr, set, setlen)
246
Guido van Rossumd57fd912000-03-10 22:53:23 +0000247/* --- Unicode Object ----------------------------------------------------- */
248
249static
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000250int unicode_resize(register PyUnicodeObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +0000251 Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000252{
253 void *oldstr;
Tim Petersced69f82003-09-16 20:30:58 +0000254
Guido van Rossumfd4b9572000-04-10 13:51:10 +0000255 /* Shortcut if there's nothing much to do. */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000256 if (unicode->length == length)
Benjamin Peterson29060642009-01-31 22:14:21 +0000257 goto reset;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000258
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000259 /* Resizing shared object (unicode_empty or single character
260 objects) in-place is not allowed. Use PyUnicode_Resize()
261 instead ! */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000262
Benjamin Peterson14339b62009-01-31 16:36:08 +0000263 if (unicode == unicode_empty ||
Benjamin Peterson29060642009-01-31 22:14:21 +0000264 (unicode->length == 1 &&
265 unicode->str[0] < 256U &&
266 unicode_latin1[unicode->str[0]] == unicode)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +0000267 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson142957c2008-07-04 19:55:29 +0000268 "can't resize shared str objects");
Guido van Rossumd57fd912000-03-10 22:53:23 +0000269 return -1;
270 }
271
Thomas Wouters477c8d52006-05-27 19:21:47 +0000272 /* We allocate one more byte to make sure the string is Ux0000 terminated.
273 The overallocation is also used by fastsearch, which assumes that it's
274 safe to look at str[length] (without making any assumptions about what
275 it contains). */
276
Guido van Rossumd57fd912000-03-10 22:53:23 +0000277 oldstr = unicode->str;
Christian Heimesb186d002008-03-18 15:15:01 +0000278 unicode->str = PyObject_REALLOC(unicode->str,
Benjamin Peterson29060642009-01-31 22:14:21 +0000279 sizeof(Py_UNICODE) * (length + 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000280 if (!unicode->str) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000281 unicode->str = (Py_UNICODE *)oldstr;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000282 PyErr_NoMemory();
283 return -1;
284 }
285 unicode->str[length] = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000286 unicode->length = length;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000287
Benjamin Peterson29060642009-01-31 22:14:21 +0000288 reset:
Guido van Rossumd57fd912000-03-10 22:53:23 +0000289 /* Reset the object caches */
Marc-André Lemburgbff879c2000-08-03 18:46:08 +0000290 if (unicode->defenc) {
291 Py_DECREF(unicode->defenc);
292 unicode->defenc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000293 }
294 unicode->hash = -1;
Tim Petersced69f82003-09-16 20:30:58 +0000295
Guido van Rossumd57fd912000-03-10 22:53:23 +0000296 return 0;
297}
298
299/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000300 Ux0000 terminated; some code (e.g. new_identifier)
301 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000302
303 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000304 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000305
306*/
307
308static
Martin v. Löwis18e16552006-02-15 17:27:45 +0000309PyUnicodeObject *_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000310{
311 register PyUnicodeObject *unicode;
312
Thomas Wouters477c8d52006-05-27 19:21:47 +0000313 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000314 if (length == 0 && unicode_empty != NULL) {
315 Py_INCREF(unicode_empty);
316 return unicode_empty;
317 }
318
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000319 /* Ensure we won't overflow the size. */
320 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
321 return (PyUnicodeObject *)PyErr_NoMemory();
322 }
323
Guido van Rossumd57fd912000-03-10 22:53:23 +0000324 /* Unicode freelist & memory allocation */
Christian Heimes2202f872008-02-06 14:31:34 +0000325 if (free_list) {
326 unicode = free_list;
327 free_list = *(PyUnicodeObject **)unicode;
328 numfree--;
Benjamin Peterson29060642009-01-31 22:14:21 +0000329 if (unicode->str) {
330 /* Keep-Alive optimization: we only upsize the buffer,
331 never downsize it. */
332 if ((unicode->length < length) &&
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +0000333 unicode_resize(unicode, length) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000334 PyObject_DEL(unicode->str);
335 unicode->str = NULL;
336 }
Benjamin Peterson14339b62009-01-31 16:36:08 +0000337 }
Guido van Rossumad98db12001-06-14 17:52:02 +0000338 else {
Benjamin Peterson29060642009-01-31 22:14:21 +0000339 size_t new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
340 unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
Guido van Rossumad98db12001-06-14 17:52:02 +0000341 }
342 PyObject_INIT(unicode, &PyUnicode_Type);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000343 }
344 else {
Benjamin Peterson29060642009-01-31 22:14:21 +0000345 size_t new_size;
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000346 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000347 if (unicode == NULL)
348 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +0000349 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
350 unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000351 }
352
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000353 if (!unicode->str) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000354 PyErr_NoMemory();
355 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000356 }
Jeremy Hyltond8082792003-09-16 19:41:39 +0000357 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000358 * the caller fails before initializing str -- unicode_resize()
359 * reads str[0], and the Keep-Alive optimization can keep memory
360 * allocated for str alive across a call to unicode_dealloc(unicode).
361 * We don't want unicode_resize to read uninitialized memory in
362 * that case.
363 */
Jeremy Hyltond8082792003-09-16 19:41:39 +0000364 unicode->str[0] = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000365 unicode->str[length] = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000366 unicode->length = length;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000367 unicode->hash = -1;
Walter Dörwald16807132007-05-25 13:52:07 +0000368 unicode->state = 0;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +0000369 unicode->defenc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000370 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000371
Benjamin Peterson29060642009-01-31 22:14:21 +0000372 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000373 /* XXX UNREF/NEWREF interface should be more symmetrical */
374 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000375 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000376 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000377 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000378}
379
380static
Guido van Rossum9475a232001-10-05 20:51:39 +0000381void unicode_dealloc(register PyUnicodeObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000382{
Walter Dörwald16807132007-05-25 13:52:07 +0000383 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000384 case SSTATE_NOT_INTERNED:
385 break;
Walter Dörwald16807132007-05-25 13:52:07 +0000386
Benjamin Peterson29060642009-01-31 22:14:21 +0000387 case SSTATE_INTERNED_MORTAL:
388 /* revive dead object temporarily for DelItem */
389 Py_REFCNT(unicode) = 3;
390 if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
391 Py_FatalError(
392 "deletion of interned string failed");
393 break;
Walter Dörwald16807132007-05-25 13:52:07 +0000394
Benjamin Peterson29060642009-01-31 22:14:21 +0000395 case SSTATE_INTERNED_IMMORTAL:
396 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +0000397
Benjamin Peterson29060642009-01-31 22:14:21 +0000398 default:
399 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +0000400 }
401
Guido van Rossum604ddf82001-12-06 20:03:56 +0000402 if (PyUnicode_CheckExact(unicode) &&
Benjamin Peterson29060642009-01-31 22:14:21 +0000403 numfree < PyUnicode_MAXFREELIST) {
Guido van Rossumfd4b9572000-04-10 13:51:10 +0000404 /* Keep-Alive optimization */
Benjamin Peterson29060642009-01-31 22:14:21 +0000405 if (unicode->length >= KEEPALIVE_SIZE_LIMIT) {
406 PyObject_DEL(unicode->str);
407 unicode->str = NULL;
408 unicode->length = 0;
409 }
410 if (unicode->defenc) {
411 Py_DECREF(unicode->defenc);
412 unicode->defenc = NULL;
413 }
414 /* Add to free list */
Christian Heimes2202f872008-02-06 14:31:34 +0000415 *(PyUnicodeObject **)unicode = free_list;
416 free_list = unicode;
417 numfree++;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000418 }
419 else {
Benjamin Peterson29060642009-01-31 22:14:21 +0000420 PyObject_DEL(unicode->str);
421 Py_XDECREF(unicode->defenc);
422 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000423 }
424}
425
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000426static
427int _PyUnicode_Resize(PyUnicodeObject **unicode, Py_ssize_t length)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000428{
429 register PyUnicodeObject *v;
430
431 /* Argument checks */
432 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000433 PyErr_BadInternalCall();
434 return -1;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000435 }
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000436 v = *unicode;
Christian Heimes90aa7642007-12-19 02:45:37 +0000437 if (v == NULL || !PyUnicode_Check(v) || Py_REFCNT(v) != 1 || length < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000438 PyErr_BadInternalCall();
439 return -1;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000440 }
441
442 /* Resizing unicode_empty and single character objects is not
443 possible since these are being shared. We simply return a fresh
444 copy with the same Unicode content. */
Tim Petersced69f82003-09-16 20:30:58 +0000445 if (v->length != length &&
Benjamin Peterson29060642009-01-31 22:14:21 +0000446 (v == unicode_empty || v->length == 1)) {
447 PyUnicodeObject *w = _PyUnicode_New(length);
448 if (w == NULL)
449 return -1;
450 Py_UNICODE_COPY(w->str, v->str,
451 length < v->length ? length : v->length);
452 Py_DECREF(*unicode);
453 *unicode = w;
454 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000455 }
456
457 /* Note that we don't have to modify *unicode for unshared Unicode
458 objects, since we can modify them in-place. */
459 return unicode_resize(v, length);
460}
461
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000462int PyUnicode_Resize(PyObject **unicode, Py_ssize_t length)
463{
464 return _PyUnicode_Resize((PyUnicodeObject **)unicode, length);
465}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000466
Guido van Rossumd57fd912000-03-10 22:53:23 +0000467PyObject *PyUnicode_FromUnicode(const Py_UNICODE *u,
Benjamin Peterson29060642009-01-31 22:14:21 +0000468 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000469{
470 PyUnicodeObject *unicode;
471
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000472 /* If the Unicode data is known at construction time, we can apply
473 some optimizations which share commonly used objects. */
474 if (u != NULL) {
475
Benjamin Peterson29060642009-01-31 22:14:21 +0000476 /* Optimization for empty strings */
477 if (size == 0 && unicode_empty != NULL) {
478 Py_INCREF(unicode_empty);
479 return (PyObject *)unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000480 }
Benjamin Peterson29060642009-01-31 22:14:21 +0000481
482 /* Single character Unicode objects in the Latin-1 range are
483 shared when using this constructor */
484 if (size == 1 && *u < 256) {
485 unicode = unicode_latin1[*u];
486 if (!unicode) {
487 unicode = _PyUnicode_New(1);
488 if (!unicode)
489 return NULL;
490 unicode->str[0] = *u;
491 unicode_latin1[*u] = unicode;
492 }
493 Py_INCREF(unicode);
494 return (PyObject *)unicode;
495 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000496 }
Tim Petersced69f82003-09-16 20:30:58 +0000497
Guido van Rossumd57fd912000-03-10 22:53:23 +0000498 unicode = _PyUnicode_New(size);
499 if (!unicode)
500 return NULL;
501
502 /* Copy the Unicode data into the new object */
503 if (u != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +0000504 Py_UNICODE_COPY(unicode->str, u, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000505
506 return (PyObject *)unicode;
507}
508
Walter Dörwaldd2034312007-05-18 16:29:38 +0000509PyObject *PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000510{
511 PyUnicodeObject *unicode;
Christian Heimes33fe8092008-04-13 13:53:33 +0000512
Benjamin Peterson14339b62009-01-31 16:36:08 +0000513 if (size < 0) {
514 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +0000515 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +0000516 return NULL;
517 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000518
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000519 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +0000520 some optimizations which share commonly used objects.
521 Also, this means the input must be UTF-8, so fall back to the
522 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000523 if (u != NULL) {
524
Benjamin Peterson29060642009-01-31 22:14:21 +0000525 /* Optimization for empty strings */
526 if (size == 0 && unicode_empty != NULL) {
527 Py_INCREF(unicode_empty);
528 return (PyObject *)unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000529 }
Benjamin Peterson29060642009-01-31 22:14:21 +0000530
531 /* Single characters are shared when using this constructor.
532 Restrict to ASCII, since the input must be UTF-8. */
533 if (size == 1 && Py_CHARMASK(*u) < 128) {
534 unicode = unicode_latin1[Py_CHARMASK(*u)];
535 if (!unicode) {
536 unicode = _PyUnicode_New(1);
537 if (!unicode)
538 return NULL;
539 unicode->str[0] = Py_CHARMASK(*u);
540 unicode_latin1[Py_CHARMASK(*u)] = unicode;
541 }
542 Py_INCREF(unicode);
543 return (PyObject *)unicode;
544 }
Martin v. Löwis9c121062007-08-05 20:26:11 +0000545
546 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000547 }
548
Walter Dörwald55507312007-05-18 13:12:10 +0000549 unicode = _PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000550 if (!unicode)
551 return NULL;
552
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000553 return (PyObject *)unicode;
554}
555
Walter Dörwaldd2034312007-05-18 16:29:38 +0000556PyObject *PyUnicode_FromString(const char *u)
557{
558 size_t size = strlen(u);
559 if (size > PY_SSIZE_T_MAX) {
560 PyErr_SetString(PyExc_OverflowError, "input too long");
561 return NULL;
562 }
563
564 return PyUnicode_FromStringAndSize(u, size);
565}
566
Guido van Rossumd57fd912000-03-10 22:53:23 +0000567#ifdef HAVE_WCHAR_H
568
Mark Dickinson081dfee2009-03-18 14:47:41 +0000569#if (Py_UNICODE_SIZE == 2) && defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4)
570# define CONVERT_WCHAR_TO_SURROGATES
571#endif
572
573#ifdef CONVERT_WCHAR_TO_SURROGATES
574
575/* Here sizeof(wchar_t) is 4 but Py_UNICODE_SIZE == 2, so we need
576 to convert from UTF32 to UTF16. */
577
578PyObject *PyUnicode_FromWideChar(register const wchar_t *w,
579 Py_ssize_t size)
580{
581 PyUnicodeObject *unicode;
582 register Py_ssize_t i;
583 Py_ssize_t alloc;
584 const wchar_t *orig_w;
585
586 if (w == NULL) {
587 if (size == 0)
588 return PyUnicode_FromStringAndSize(NULL, 0);
589 PyErr_BadInternalCall();
590 return NULL;
591 }
592
593 if (size == -1) {
594 size = wcslen(w);
595 }
596
597 alloc = size;
598 orig_w = w;
599 for (i = size; i > 0; i--) {
600 if (*w > 0xFFFF)
601 alloc++;
602 w++;
603 }
604 w = orig_w;
605 unicode = _PyUnicode_New(alloc);
606 if (!unicode)
607 return NULL;
608
609 /* Copy the wchar_t data into the new object */
610 {
611 register Py_UNICODE *u;
612 u = PyUnicode_AS_UNICODE(unicode);
613 for (i = size; i > 0; i--) {
614 if (*w > 0xFFFF) {
615 wchar_t ordinal = *w++;
616 ordinal -= 0x10000;
617 *u++ = 0xD800 | (ordinal >> 10);
618 *u++ = 0xDC00 | (ordinal & 0x3FF);
619 }
620 else
621 *u++ = *w++;
622 }
623 }
624 return (PyObject *)unicode;
625}
626
627#else
628
Guido van Rossumd57fd912000-03-10 22:53:23 +0000629PyObject *PyUnicode_FromWideChar(register const wchar_t *w,
Benjamin Peterson29060642009-01-31 22:14:21 +0000630 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000631{
632 PyUnicodeObject *unicode;
633
634 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +0000635 if (size == 0)
636 return PyUnicode_FromStringAndSize(NULL, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +0000637 PyErr_BadInternalCall();
638 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000639 }
640
Martin v. Löwis790465f2008-04-05 20:41:37 +0000641 if (size == -1) {
642 size = wcslen(w);
643 }
644
Guido van Rossumd57fd912000-03-10 22:53:23 +0000645 unicode = _PyUnicode_New(size);
646 if (!unicode)
647 return NULL;
648
649 /* Copy the wchar_t data into the new object */
650#ifdef HAVE_USABLE_WCHAR_T
651 memcpy(unicode->str, w, size * sizeof(wchar_t));
Tim Petersced69f82003-09-16 20:30:58 +0000652#else
Guido van Rossumd57fd912000-03-10 22:53:23 +0000653 {
Benjamin Peterson29060642009-01-31 22:14:21 +0000654 register Py_UNICODE *u;
655 register Py_ssize_t i;
656 u = PyUnicode_AS_UNICODE(unicode);
657 for (i = size; i > 0; i--)
658 *u++ = *w++;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000659 }
660#endif
661
662 return (PyObject *)unicode;
663}
664
Mark Dickinson081dfee2009-03-18 14:47:41 +0000665#endif /* CONVERT_WCHAR_TO_SURROGATES */
666
667#undef CONVERT_WCHAR_TO_SURROGATES
668
Walter Dörwald346737f2007-05-31 10:44:43 +0000669static void
670makefmt(char *fmt, int longflag, int size_tflag, int zeropad, int width, int precision, char c)
671{
Benjamin Peterson14339b62009-01-31 16:36:08 +0000672 *fmt++ = '%';
673 if (width) {
674 if (zeropad)
675 *fmt++ = '0';
676 fmt += sprintf(fmt, "%d", width);
677 }
678 if (precision)
679 fmt += sprintf(fmt, ".%d", precision);
680 if (longflag)
681 *fmt++ = 'l';
682 else if (size_tflag) {
683 char *f = PY_FORMAT_SIZE_T;
684 while (*f)
685 *fmt++ = *f++;
686 }
687 *fmt++ = c;
688 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +0000689}
690
Walter Dörwaldd2034312007-05-18 16:29:38 +0000691#define appendstring(string) {for (copy = string;*copy;) *s++ = *copy++;}
692
693PyObject *
694PyUnicode_FromFormatV(const char *format, va_list vargs)
695{
Benjamin Peterson14339b62009-01-31 16:36:08 +0000696 va_list count;
697 Py_ssize_t callcount = 0;
698 PyObject **callresults = NULL;
699 PyObject **callresult = NULL;
700 Py_ssize_t n = 0;
701 int width = 0;
702 int precision = 0;
703 int zeropad;
704 const char* f;
705 Py_UNICODE *s;
706 PyObject *string;
707 /* used by sprintf */
708 char buffer[21];
709 /* use abuffer instead of buffer, if we need more space
710 * (which can happen if there's a format specifier with width). */
711 char *abuffer = NULL;
712 char *realbuffer;
713 Py_ssize_t abuffersize = 0;
714 char fmt[60]; /* should be enough for %0width.precisionld */
715 const char *copy;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000716
717#ifdef VA_LIST_IS_ARRAY
Benjamin Peterson14339b62009-01-31 16:36:08 +0000718 Py_MEMCPY(count, vargs, sizeof(va_list));
Walter Dörwaldd2034312007-05-18 16:29:38 +0000719#else
720#ifdef __va_copy
Benjamin Peterson14339b62009-01-31 16:36:08 +0000721 __va_copy(count, vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +0000722#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000723 count = vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000724#endif
725#endif
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000726 /* step 1: count the number of %S/%R/%A/%s format specifications
727 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
728 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
729 * result in an array) */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000730 for (f = format; *f; f++) {
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000731 if (*f == '%') {
732 if (*(f+1)=='%')
733 continue;
734 if (*(f+1)=='S' || *(f+1)=='R' || *(f+1)=='A')
735 ++callcount;
736 while (ISDIGIT((unsigned)*f))
737 width = (width*10) + *f++ - '0';
738 while (*++f && *f != '%' && !ISALPHA((unsigned)*f))
739 ;
740 if (*f == 's')
741 ++callcount;
742 }
Benjamin Peterson14339b62009-01-31 16:36:08 +0000743 }
744 /* step 2: allocate memory for the results of
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000745 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000746 if (callcount) {
747 callresults = PyObject_Malloc(sizeof(PyObject *)*callcount);
748 if (!callresults) {
749 PyErr_NoMemory();
750 return NULL;
751 }
752 callresult = callresults;
753 }
754 /* step 3: figure out how large a buffer we need */
755 for (f = format; *f; f++) {
756 if (*f == '%') {
757 const char* p = f;
758 width = 0;
759 while (ISDIGIT((unsigned)*f))
760 width = (width*10) + *f++ - '0';
761 while (*++f && *f != '%' && !ISALPHA((unsigned)*f))
762 ;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000763
Benjamin Peterson14339b62009-01-31 16:36:08 +0000764 /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
765 * they don't affect the amount of space we reserve.
766 */
767 if ((*f == 'l' || *f == 'z') &&
Benjamin Peterson29060642009-01-31 22:14:21 +0000768 (f[1] == 'd' || f[1] == 'u'))
769 ++f;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000770
Benjamin Peterson14339b62009-01-31 16:36:08 +0000771 switch (*f) {
772 case 'c':
773 (void)va_arg(count, int);
774 /* fall through... */
775 case '%':
776 n++;
777 break;
778 case 'd': case 'u': case 'i': case 'x':
779 (void) va_arg(count, int);
780 /* 20 bytes is enough to hold a 64-bit
781 integer. Decimal takes the most space.
782 This isn't enough for octal.
783 If a width is specified we need more
784 (which we allocate later). */
785 if (width < 20)
786 width = 20;
787 n += width;
788 if (abuffersize < width)
789 abuffersize = width;
790 break;
791 case 's':
792 {
793 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +0000794 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000795 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
796 if (!str)
797 goto fail;
798 n += PyUnicode_GET_SIZE(str);
799 /* Remember the str and switch to the next slot */
800 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000801 break;
802 }
803 case 'U':
804 {
805 PyObject *obj = va_arg(count, PyObject *);
806 assert(obj && PyUnicode_Check(obj));
807 n += PyUnicode_GET_SIZE(obj);
808 break;
809 }
810 case 'V':
811 {
812 PyObject *obj = va_arg(count, PyObject *);
813 const char *str = va_arg(count, const char *);
814 assert(obj || str);
815 assert(!obj || PyUnicode_Check(obj));
816 if (obj)
817 n += PyUnicode_GET_SIZE(obj);
818 else
819 n += strlen(str);
820 break;
821 }
822 case 'S':
823 {
824 PyObject *obj = va_arg(count, PyObject *);
825 PyObject *str;
826 assert(obj);
827 str = PyObject_Str(obj);
828 if (!str)
829 goto fail;
830 n += PyUnicode_GET_SIZE(str);
831 /* Remember the str and switch to the next slot */
832 *callresult++ = str;
833 break;
834 }
835 case 'R':
836 {
837 PyObject *obj = va_arg(count, PyObject *);
838 PyObject *repr;
839 assert(obj);
840 repr = PyObject_Repr(obj);
841 if (!repr)
842 goto fail;
843 n += PyUnicode_GET_SIZE(repr);
844 /* Remember the repr and switch to the next slot */
845 *callresult++ = repr;
846 break;
847 }
848 case 'A':
849 {
850 PyObject *obj = va_arg(count, PyObject *);
851 PyObject *ascii;
852 assert(obj);
853 ascii = PyObject_ASCII(obj);
854 if (!ascii)
855 goto fail;
856 n += PyUnicode_GET_SIZE(ascii);
857 /* Remember the repr and switch to the next slot */
858 *callresult++ = ascii;
859 break;
860 }
861 case 'p':
862 (void) va_arg(count, int);
863 /* maximum 64-bit pointer representation:
864 * 0xffffffffffffffff
865 * so 19 characters is enough.
866 * XXX I count 18 -- what's the extra for?
867 */
868 n += 19;
869 break;
870 default:
871 /* if we stumble upon an unknown
872 formatting code, copy the rest of
873 the format string to the output
874 string. (we cannot just skip the
875 code, since there's no way to know
876 what's in the argument list) */
877 n += strlen(p);
878 goto expand;
879 }
880 } else
881 n++;
882 }
Benjamin Peterson29060642009-01-31 22:14:21 +0000883 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +0000884 if (abuffersize > 20) {
885 abuffer = PyObject_Malloc(abuffersize);
886 if (!abuffer) {
887 PyErr_NoMemory();
888 goto fail;
889 }
890 realbuffer = abuffer;
891 }
892 else
893 realbuffer = buffer;
894 /* step 4: fill the buffer */
895 /* Since we've analyzed how much space we need for the worst case,
896 we don't have to resize the string.
897 There can be no errors beyond this point. */
898 string = PyUnicode_FromUnicode(NULL, n);
899 if (!string)
900 goto fail;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000901
Benjamin Peterson14339b62009-01-31 16:36:08 +0000902 s = PyUnicode_AS_UNICODE(string);
903 callresult = callresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000904
Benjamin Peterson14339b62009-01-31 16:36:08 +0000905 for (f = format; *f; f++) {
906 if (*f == '%') {
907 const char* p = f++;
908 int longflag = 0;
909 int size_tflag = 0;
910 zeropad = (*f == '0');
911 /* parse the width.precision part */
912 width = 0;
913 while (ISDIGIT((unsigned)*f))
914 width = (width*10) + *f++ - '0';
915 precision = 0;
916 if (*f == '.') {
917 f++;
918 while (ISDIGIT((unsigned)*f))
919 precision = (precision*10) + *f++ - '0';
920 }
921 /* handle the long flag, but only for %ld and %lu.
922 others can be added when necessary. */
923 if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) {
924 longflag = 1;
925 ++f;
926 }
927 /* handle the size_t flag. */
928 if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
929 size_tflag = 1;
930 ++f;
931 }
Walter Dörwaldd2034312007-05-18 16:29:38 +0000932
Benjamin Peterson14339b62009-01-31 16:36:08 +0000933 switch (*f) {
934 case 'c':
935 *s++ = va_arg(vargs, int);
936 break;
937 case 'd':
938 makefmt(fmt, longflag, size_tflag, zeropad, width, precision, 'd');
939 if (longflag)
940 sprintf(realbuffer, fmt, va_arg(vargs, long));
941 else if (size_tflag)
942 sprintf(realbuffer, fmt, va_arg(vargs, Py_ssize_t));
943 else
944 sprintf(realbuffer, fmt, va_arg(vargs, int));
945 appendstring(realbuffer);
946 break;
947 case 'u':
948 makefmt(fmt, longflag, size_tflag, zeropad, width, precision, 'u');
949 if (longflag)
950 sprintf(realbuffer, fmt, va_arg(vargs, unsigned long));
951 else if (size_tflag)
952 sprintf(realbuffer, fmt, va_arg(vargs, size_t));
953 else
954 sprintf(realbuffer, fmt, va_arg(vargs, unsigned int));
955 appendstring(realbuffer);
956 break;
957 case 'i':
958 makefmt(fmt, 0, 0, zeropad, width, precision, 'i');
959 sprintf(realbuffer, fmt, va_arg(vargs, int));
960 appendstring(realbuffer);
961 break;
962 case 'x':
963 makefmt(fmt, 0, 0, zeropad, width, precision, 'x');
964 sprintf(realbuffer, fmt, va_arg(vargs, int));
965 appendstring(realbuffer);
966 break;
967 case 's':
968 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000969 /* unused, since we already have the result */
970 (void) va_arg(vargs, char *);
971 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(*callresult),
972 PyUnicode_GET_SIZE(*callresult));
973 s += PyUnicode_GET_SIZE(*callresult);
974 /* We're done with the unicode()/repr() => forget it */
975 Py_DECREF(*callresult);
976 /* switch to next unicode()/repr() result */
977 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000978 break;
979 }
980 case 'U':
981 {
982 PyObject *obj = va_arg(vargs, PyObject *);
983 Py_ssize_t size = PyUnicode_GET_SIZE(obj);
984 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size);
985 s += size;
986 break;
987 }
988 case 'V':
989 {
990 PyObject *obj = va_arg(vargs, PyObject *);
991 const char *str = va_arg(vargs, const char *);
992 if (obj) {
993 Py_ssize_t size = PyUnicode_GET_SIZE(obj);
994 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size);
995 s += size;
996 } else {
997 appendstring(str);
998 }
999 break;
1000 }
1001 case 'S':
1002 case 'R':
1003 {
1004 Py_UNICODE *ucopy;
1005 Py_ssize_t usize;
1006 Py_ssize_t upos;
1007 /* unused, since we already have the result */
1008 (void) va_arg(vargs, PyObject *);
1009 ucopy = PyUnicode_AS_UNICODE(*callresult);
1010 usize = PyUnicode_GET_SIZE(*callresult);
1011 for (upos = 0; upos<usize;)
1012 *s++ = ucopy[upos++];
1013 /* We're done with the unicode()/repr() => forget it */
1014 Py_DECREF(*callresult);
1015 /* switch to next unicode()/repr() result */
1016 ++callresult;
1017 break;
1018 }
1019 case 'p':
1020 sprintf(buffer, "%p", va_arg(vargs, void*));
1021 /* %p is ill-defined: ensure leading 0x. */
1022 if (buffer[1] == 'X')
1023 buffer[1] = 'x';
1024 else if (buffer[1] != 'x') {
1025 memmove(buffer+2, buffer, strlen(buffer)+1);
1026 buffer[0] = '0';
1027 buffer[1] = 'x';
1028 }
1029 appendstring(buffer);
1030 break;
1031 case '%':
1032 *s++ = '%';
1033 break;
1034 default:
1035 appendstring(p);
1036 goto end;
1037 }
1038 } else
1039 *s++ = *f;
1040 }
Walter Dörwaldd2034312007-05-18 16:29:38 +00001041
Benjamin Peterson29060642009-01-31 22:14:21 +00001042 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001043 if (callresults)
1044 PyObject_Free(callresults);
1045 if (abuffer)
1046 PyObject_Free(abuffer);
1047 PyUnicode_Resize(&string, s - PyUnicode_AS_UNICODE(string));
1048 return string;
Benjamin Peterson29060642009-01-31 22:14:21 +00001049 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001050 if (callresults) {
1051 PyObject **callresult2 = callresults;
1052 while (callresult2 < callresult) {
1053 Py_DECREF(*callresult2);
1054 ++callresult2;
1055 }
1056 PyObject_Free(callresults);
1057 }
1058 if (abuffer)
1059 PyObject_Free(abuffer);
1060 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001061}
1062
1063#undef appendstring
1064
1065PyObject *
1066PyUnicode_FromFormat(const char *format, ...)
1067{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001068 PyObject* ret;
1069 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001070
1071#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00001072 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001073#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00001074 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001075#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001076 ret = PyUnicode_FromFormatV(format, vargs);
1077 va_end(vargs);
1078 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001079}
1080
Martin v. Löwis18e16552006-02-15 17:27:45 +00001081Py_ssize_t PyUnicode_AsWideChar(PyUnicodeObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00001082 wchar_t *w,
1083 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001084{
1085 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001086 PyErr_BadInternalCall();
1087 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001088 }
Marc-André Lemburga9cadcd2004-11-22 13:02:31 +00001089
1090 /* If possible, try to copy the 0-termination as well */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001091 if (size > PyUnicode_GET_SIZE(unicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00001092 size = PyUnicode_GET_SIZE(unicode) + 1;
Marc-André Lemburga9cadcd2004-11-22 13:02:31 +00001093
Guido van Rossumd57fd912000-03-10 22:53:23 +00001094#ifdef HAVE_USABLE_WCHAR_T
1095 memcpy(w, unicode->str, size * sizeof(wchar_t));
1096#else
1097 {
Benjamin Peterson29060642009-01-31 22:14:21 +00001098 register Py_UNICODE *u;
1099 register Py_ssize_t i;
1100 u = PyUnicode_AS_UNICODE(unicode);
1101 for (i = size; i > 0; i--)
1102 *w++ = *u++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001103 }
1104#endif
1105
Marc-André Lemburga9cadcd2004-11-22 13:02:31 +00001106 if (size > PyUnicode_GET_SIZE(unicode))
1107 return PyUnicode_GET_SIZE(unicode);
1108 else
Benjamin Peterson29060642009-01-31 22:14:21 +00001109 return size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001110}
1111
1112#endif
1113
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001114PyObject *PyUnicode_FromOrdinal(int ordinal)
1115{
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001116 Py_UNICODE s[2];
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001117
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001118 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001119 PyErr_SetString(PyExc_ValueError,
1120 "chr() arg not in range(0x110000)");
1121 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001122 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001123
1124#ifndef Py_UNICODE_WIDE
1125 if (ordinal > 0xffff) {
1126 ordinal -= 0x10000;
1127 s[0] = 0xD800 | (ordinal >> 10);
1128 s[1] = 0xDC00 | (ordinal & 0x3FF);
1129 return PyUnicode_FromUnicode(s, 2);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001130 }
1131#endif
1132
Hye-Shik Chang40574832004-04-06 07:24:51 +00001133 s[0] = (Py_UNICODE)ordinal;
1134 return PyUnicode_FromUnicode(s, 1);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001135}
1136
Guido van Rossumd57fd912000-03-10 22:53:23 +00001137PyObject *PyUnicode_FromObject(register PyObject *obj)
1138{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001139 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00001140 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001141 if (PyUnicode_CheckExact(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001142 Py_INCREF(obj);
1143 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001144 }
1145 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001146 /* For a Unicode subtype that's not a Unicode object,
1147 return a true Unicode object with the same data. */
1148 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(obj),
1149 PyUnicode_GET_SIZE(obj));
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001150 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001151 PyErr_Format(PyExc_TypeError,
1152 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00001153 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001154 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001155}
1156
1157PyObject *PyUnicode_FromEncodedObject(register PyObject *obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00001158 const char *encoding,
1159 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001160{
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00001161 const char *s = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001162 Py_ssize_t len;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001163 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00001164
Guido van Rossumd57fd912000-03-10 22:53:23 +00001165 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001166 PyErr_BadInternalCall();
1167 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001168 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001169
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001170 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001171 PyErr_SetString(PyExc_TypeError,
1172 "decoding str is not supported");
1173 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001174 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001175
1176 /* Coerce object */
Christian Heimes72b710a2008-05-26 13:28:38 +00001177 if (PyBytes_Check(obj)) {
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001178 s = PyBytes_AS_STRING(obj);
1179 len = PyBytes_GET_SIZE(obj);
1180 }
1181 else if (PyByteArray_Check(obj)) {
1182 s = PyByteArray_AS_STRING(obj);
1183 len = PyByteArray_GET_SIZE(obj);
1184 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001185 else if (PyObject_AsCharBuffer(obj, &s, &len)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001186 /* Overwrite the error message with something more useful in
1187 case of a TypeError. */
1188 if (PyErr_ExceptionMatches(PyExc_TypeError))
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001189 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001190 "coercing to str: need string or buffer, "
1191 "%.80s found",
1192 Py_TYPE(obj)->tp_name);
1193 goto onError;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00001194 }
Tim Petersced69f82003-09-16 20:30:58 +00001195
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001196 /* Convert to Unicode */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001197 if (len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001198 Py_INCREF(unicode_empty);
1199 v = (PyObject *)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001200 }
Tim Petersced69f82003-09-16 20:30:58 +00001201 else
Benjamin Peterson29060642009-01-31 22:14:21 +00001202 v = PyUnicode_Decode(s, len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00001203
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001204 return v;
1205
Benjamin Peterson29060642009-01-31 22:14:21 +00001206 onError:
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001207 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001208}
1209
1210PyObject *PyUnicode_Decode(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00001211 Py_ssize_t size,
1212 const char *encoding,
1213 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001214{
1215 PyObject *buffer = NULL, *unicode;
Guido van Rossumbe801ac2007-10-08 03:32:34 +00001216 Py_buffer info;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001217 char lower[20]; /* Enough for any encoding name we recognize */
1218 char *l;
1219 const char *e;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001220
1221 if (encoding == NULL)
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001222 encoding = PyUnicode_GetDefaultEncoding();
1223
1224 /* Convert encoding to lower case and replace '_' with '-' in order to
1225 catch e.g. UTF_8 */
1226 e = encoding;
1227 l = lower;
1228 while (*e && l < &lower[(sizeof lower) - 2]) {
1229 if (ISUPPER(*e)) {
1230 *l++ = TOLOWER(*e++);
1231 }
1232 else if (*e == '_') {
1233 *l++ = '-';
1234 e++;
1235 }
1236 else {
1237 *l++ = *e++;
1238 }
1239 }
1240 *l = '\0';
Fred Drakee4315f52000-05-09 19:53:39 +00001241
1242 /* Shortcuts for common default encodings */
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001243 if (strcmp(lower, "utf-8") == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001244 return PyUnicode_DecodeUTF8(s, size, errors);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001245 else if ((strcmp(lower, "latin-1") == 0) ||
1246 (strcmp(lower, "iso-8859-1") == 0))
Fred Drakee4315f52000-05-09 19:53:39 +00001247 return PyUnicode_DecodeLatin1(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001248#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001249 else if (strcmp(lower, "mbcs") == 0)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001250 return PyUnicode_DecodeMBCS(s, size, errors);
1251#endif
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001252 else if (strcmp(lower, "ascii") == 0)
Fred Drakee4315f52000-05-09 19:53:39 +00001253 return PyUnicode_DecodeASCII(s, size, errors);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001254 else if (strcmp(lower, "utf-16") == 0)
1255 return PyUnicode_DecodeUTF16(s, size, errors, 0);
1256 else if (strcmp(lower, "utf-32") == 0)
1257 return PyUnicode_DecodeUTF32(s, size, errors, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001258
1259 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00001260 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00001261 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00001262 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00001263 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001264 if (buffer == NULL)
1265 goto onError;
1266 unicode = PyCodec_Decode(buffer, encoding, errors);
1267 if (unicode == NULL)
1268 goto onError;
1269 if (!PyUnicode_Check(unicode)) {
1270 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001271 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00001272 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001273 Py_DECREF(unicode);
1274 goto onError;
1275 }
1276 Py_DECREF(buffer);
1277 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00001278
Benjamin Peterson29060642009-01-31 22:14:21 +00001279 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001280 Py_XDECREF(buffer);
1281 return NULL;
1282}
1283
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001284PyObject *PyUnicode_AsDecodedObject(PyObject *unicode,
1285 const char *encoding,
1286 const char *errors)
1287{
1288 PyObject *v;
1289
1290 if (!PyUnicode_Check(unicode)) {
1291 PyErr_BadArgument();
1292 goto onError;
1293 }
1294
1295 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001296 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001297
1298 /* Decode via the codec registry */
1299 v = PyCodec_Decode(unicode, encoding, errors);
1300 if (v == NULL)
1301 goto onError;
1302 return v;
1303
Benjamin Peterson29060642009-01-31 22:14:21 +00001304 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001305 return NULL;
1306}
1307
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001308PyObject *PyUnicode_AsDecodedUnicode(PyObject *unicode,
1309 const char *encoding,
1310 const char *errors)
1311{
1312 PyObject *v;
1313
1314 if (!PyUnicode_Check(unicode)) {
1315 PyErr_BadArgument();
1316 goto onError;
1317 }
1318
1319 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001320 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001321
1322 /* Decode via the codec registry */
1323 v = PyCodec_Decode(unicode, encoding, errors);
1324 if (v == NULL)
1325 goto onError;
1326 if (!PyUnicode_Check(v)) {
1327 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001328 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001329 Py_TYPE(v)->tp_name);
1330 Py_DECREF(v);
1331 goto onError;
1332 }
1333 return v;
1334
Benjamin Peterson29060642009-01-31 22:14:21 +00001335 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001336 return NULL;
1337}
1338
Guido van Rossumd57fd912000-03-10 22:53:23 +00001339PyObject *PyUnicode_Encode(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00001340 Py_ssize_t size,
1341 const char *encoding,
1342 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001343{
1344 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00001345
Guido van Rossumd57fd912000-03-10 22:53:23 +00001346 unicode = PyUnicode_FromUnicode(s, size);
1347 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001348 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001349 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
1350 Py_DECREF(unicode);
1351 return v;
1352}
1353
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001354PyObject *PyUnicode_AsEncodedObject(PyObject *unicode,
1355 const char *encoding,
1356 const char *errors)
1357{
1358 PyObject *v;
1359
1360 if (!PyUnicode_Check(unicode)) {
1361 PyErr_BadArgument();
1362 goto onError;
1363 }
1364
1365 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001366 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001367
1368 /* Encode via the codec registry */
1369 v = PyCodec_Encode(unicode, encoding, errors);
1370 if (v == NULL)
1371 goto onError;
1372 return v;
1373
Benjamin Peterson29060642009-01-31 22:14:21 +00001374 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001375 return NULL;
1376}
1377
Guido van Rossumd57fd912000-03-10 22:53:23 +00001378PyObject *PyUnicode_AsEncodedString(PyObject *unicode,
1379 const char *encoding,
1380 const char *errors)
1381{
1382 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00001383
Guido van Rossumd57fd912000-03-10 22:53:23 +00001384 if (!PyUnicode_Check(unicode)) {
1385 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001386 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001387 }
Fred Drakee4315f52000-05-09 19:53:39 +00001388
Tim Petersced69f82003-09-16 20:30:58 +00001389 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001390 encoding = PyUnicode_GetDefaultEncoding();
Fred Drakee4315f52000-05-09 19:53:39 +00001391
1392 /* Shortcuts for common default encodings */
1393 if (errors == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001394 if (strcmp(encoding, "utf-8") == 0)
1395 return PyUnicode_AsUTF8String(unicode);
1396 else if (strcmp(encoding, "latin-1") == 0)
1397 return PyUnicode_AsLatin1String(unicode);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001398#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Benjamin Peterson29060642009-01-31 22:14:21 +00001399 else if (strcmp(encoding, "mbcs") == 0)
1400 return PyUnicode_AsMBCSString(unicode);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001401#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00001402 else if (strcmp(encoding, "ascii") == 0)
1403 return PyUnicode_AsASCIIString(unicode);
Christian Heimes6a27efa2008-10-30 21:48:26 +00001404 /* During bootstrap, we may need to find the encodings
1405 package, to load the file system encoding, and require the
1406 file system encoding in order to load the encodings
1407 package.
1408
1409 Break out of this dependency by assuming that the path to
1410 the encodings module is ASCII-only. XXX could try wcstombs
1411 instead, if the file system encoding is the locale's
1412 encoding. */
1413 else if (Py_FileSystemDefaultEncoding &&
1414 strcmp(encoding, Py_FileSystemDefaultEncoding) == 0 &&
1415 !PyThreadState_GET()->interp->codecs_initialized)
Benjamin Peterson29060642009-01-31 22:14:21 +00001416 return PyUnicode_AsASCIIString(unicode);
Fred Drakee4315f52000-05-09 19:53:39 +00001417 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001418
1419 /* Encode via the codec registry */
1420 v = PyCodec_Encode(unicode, encoding, errors);
1421 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001422 return NULL;
1423
1424 /* The normal path */
1425 if (PyBytes_Check(v))
1426 return v;
1427
1428 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001429 if (PyByteArray_Check(v)) {
1430 char msg[100];
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001431 PyObject *b;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001432 PyOS_snprintf(msg, sizeof(msg),
1433 "encoder %s returned buffer instead of bytes",
1434 encoding);
1435 if (PyErr_WarnEx(PyExc_RuntimeWarning, msg, 1) < 0) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001436 Py_DECREF(v);
1437 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001438 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001439
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001440 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
1441 Py_DECREF(v);
1442 return b;
1443 }
1444
1445 PyErr_Format(PyExc_TypeError,
1446 "encoder did not return a bytes object (type=%.400s)",
1447 Py_TYPE(v)->tp_name);
1448 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001449 return NULL;
1450}
1451
1452PyObject *PyUnicode_AsEncodedUnicode(PyObject *unicode,
1453 const char *encoding,
1454 const char *errors)
1455{
1456 PyObject *v;
1457
1458 if (!PyUnicode_Check(unicode)) {
1459 PyErr_BadArgument();
1460 goto onError;
1461 }
1462
1463 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001464 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001465
1466 /* Encode via the codec registry */
1467 v = PyCodec_Encode(unicode, encoding, errors);
1468 if (v == NULL)
1469 goto onError;
1470 if (!PyUnicode_Check(v)) {
1471 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001472 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001473 Py_TYPE(v)->tp_name);
1474 Py_DECREF(v);
1475 goto onError;
1476 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001477 return v;
Tim Petersced69f82003-09-16 20:30:58 +00001478
Benjamin Peterson29060642009-01-31 22:14:21 +00001479 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001480 return NULL;
1481}
1482
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001483PyObject *_PyUnicode_AsDefaultEncodedString(PyObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00001484 const char *errors)
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001485{
1486 PyObject *v = ((PyUnicodeObject *)unicode)->defenc;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001487 if (v)
1488 return v;
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001489 if (errors != NULL)
1490 Py_FatalError("non-NULL encoding in _PyUnicode_AsDefaultEncodedString");
Guido van Rossum98297ee2007-11-06 21:34:58 +00001491 v = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
Guido van Rossum06610092007-08-16 21:02:22 +00001492 PyUnicode_GET_SIZE(unicode),
1493 NULL);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001494 if (!v)
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001495 return NULL;
Guido van Rossume7a0d392007-07-12 07:53:00 +00001496 ((PyUnicodeObject *)unicode)->defenc = v;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001497 return v;
1498}
1499
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001500PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00001501PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001502 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00001503 return PyUnicode_DecodeFSDefaultAndSize(s, size);
1504}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001505
Christian Heimes5894ba72007-11-04 11:43:14 +00001506PyObject*
1507PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
1508{
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001509 /* During the early bootstrapping process, Py_FileSystemDefaultEncoding
1510 can be undefined. If it is case, decode using UTF-8. The following assumes
1511 that Py_FileSystemDefaultEncoding is set to a built-in encoding during the
1512 bootstrapping process where the codecs aren't ready yet.
1513 */
1514 if (Py_FileSystemDefaultEncoding) {
1515#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Christian Heimes5894ba72007-11-04 11:43:14 +00001516 if (strcmp(Py_FileSystemDefaultEncoding, "mbcs") == 0) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001517 return PyUnicode_DecodeMBCS(s, size, "replace");
1518 }
1519#elif defined(__APPLE__)
Christian Heimes5894ba72007-11-04 11:43:14 +00001520 if (strcmp(Py_FileSystemDefaultEncoding, "utf-8") == 0) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001521 return PyUnicode_DecodeUTF8(s, size, "replace");
1522 }
1523#endif
1524 return PyUnicode_Decode(s, size,
1525 Py_FileSystemDefaultEncoding,
1526 "replace");
1527 }
1528 else {
1529 return PyUnicode_DecodeUTF8(s, size, "replace");
1530 }
1531}
1532
Martin v. Löwis011e8422009-05-05 04:43:17 +00001533/* Convert the argument to a bytes object, according to the file
1534 system encoding */
1535
1536int
1537PyUnicode_FSConverter(PyObject* arg, void* addr)
1538{
1539 PyObject *output = NULL;
1540 Py_ssize_t size;
1541 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00001542 if (arg == NULL) {
1543 Py_DECREF(*(PyObject**)addr);
1544 return 1;
1545 }
Martin v. Löwis011e8422009-05-05 04:43:17 +00001546 if (PyBytes_Check(arg) || PyByteArray_Check(arg)) {
1547 output = arg;
1548 Py_INCREF(output);
1549 }
1550 else {
1551 arg = PyUnicode_FromObject(arg);
1552 if (!arg)
1553 return 0;
1554 output = PyUnicode_AsEncodedObject(arg,
1555 Py_FileSystemDefaultEncoding,
Martin v. Löwis43c57782009-05-10 08:15:24 +00001556 "surrogateescape");
Martin v. Löwis011e8422009-05-05 04:43:17 +00001557 Py_DECREF(arg);
1558 if (!output)
1559 return 0;
1560 if (!PyBytes_Check(output)) {
1561 Py_DECREF(output);
1562 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
1563 return 0;
1564 }
1565 }
1566 if (PyBytes_Check(output)) {
1567 size = PyBytes_GET_SIZE(output);
1568 data = PyBytes_AS_STRING(output);
1569 }
1570 else {
1571 size = PyByteArray_GET_SIZE(output);
1572 data = PyByteArray_AS_STRING(output);
1573 }
1574 if (size != strlen(data)) {
1575 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
1576 Py_DECREF(output);
1577 return 0;
1578 }
1579 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00001580 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00001581}
1582
1583
Martin v. Löwis5b222132007-06-10 09:51:05 +00001584char*
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001585_PyUnicode_AsStringAndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00001586{
Christian Heimesf3863112007-11-22 07:46:41 +00001587 PyObject *bytes;
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00001588 if (!PyUnicode_Check(unicode)) {
1589 PyErr_BadArgument();
1590 return NULL;
1591 }
Christian Heimesf3863112007-11-22 07:46:41 +00001592 bytes = _PyUnicode_AsDefaultEncodedString(unicode, NULL);
1593 if (bytes == NULL)
Martin v. Löwis5b222132007-06-10 09:51:05 +00001594 return NULL;
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001595 if (psize != NULL)
Christian Heimes72b710a2008-05-26 13:28:38 +00001596 *psize = PyBytes_GET_SIZE(bytes);
1597 return PyBytes_AS_STRING(bytes);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001598}
1599
1600char*
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001601_PyUnicode_AsString(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001602{
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001603 return _PyUnicode_AsStringAndSize(unicode, NULL);
Martin v. Löwis5b222132007-06-10 09:51:05 +00001604}
1605
Guido van Rossumd57fd912000-03-10 22:53:23 +00001606Py_UNICODE *PyUnicode_AsUnicode(PyObject *unicode)
1607{
1608 if (!PyUnicode_Check(unicode)) {
1609 PyErr_BadArgument();
1610 goto onError;
1611 }
1612 return PyUnicode_AS_UNICODE(unicode);
1613
Benjamin Peterson29060642009-01-31 22:14:21 +00001614 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001615 return NULL;
1616}
1617
Martin v. Löwis18e16552006-02-15 17:27:45 +00001618Py_ssize_t PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001619{
1620 if (!PyUnicode_Check(unicode)) {
1621 PyErr_BadArgument();
1622 goto onError;
1623 }
1624 return PyUnicode_GET_SIZE(unicode);
1625
Benjamin Peterson29060642009-01-31 22:14:21 +00001626 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001627 return -1;
1628}
1629
Thomas Wouters78890102000-07-22 19:25:51 +00001630const char *PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00001631{
1632 return unicode_default_encoding;
1633}
1634
1635int PyUnicode_SetDefaultEncoding(const char *encoding)
1636{
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001637 if (strcmp(encoding, unicode_default_encoding) != 0) {
1638 PyErr_Format(PyExc_ValueError,
1639 "Can only set default encoding to %s",
1640 unicode_default_encoding);
1641 return -1;
1642 }
Fred Drakee4315f52000-05-09 19:53:39 +00001643 return 0;
Fred Drakee4315f52000-05-09 19:53:39 +00001644}
1645
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001646/* error handling callback helper:
1647 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00001648 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001649 and adjust various state variables.
1650 return 0 on success, -1 on error
1651*/
1652
1653static
1654int unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00001655 const char *encoding, const char *reason,
1656 const char **input, const char **inend, Py_ssize_t *startinpos,
1657 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
1658 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001659{
Benjamin Peterson142957c2008-07-04 19:55:29 +00001660 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001661
1662 PyObject *restuple = NULL;
1663 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001664 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00001665 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001666 Py_ssize_t requiredsize;
1667 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001668 Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00001669 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001670 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001671 int res = -1;
1672
1673 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001674 *errorHandler = PyCodec_LookupError(errors);
1675 if (*errorHandler == NULL)
1676 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001677 }
1678
1679 if (*exceptionObject == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00001680 *exceptionObject = PyUnicodeDecodeError_Create(
Benjamin Peterson29060642009-01-31 22:14:21 +00001681 encoding, *input, *inend-*input, *startinpos, *endinpos, reason);
1682 if (*exceptionObject == NULL)
1683 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001684 }
1685 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00001686 if (PyUnicodeDecodeError_SetStart(*exceptionObject, *startinpos))
1687 goto onError;
1688 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, *endinpos))
1689 goto onError;
1690 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
1691 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001692 }
1693
1694 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
1695 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001696 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001697 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001698 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00001699 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001700 }
1701 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00001702 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00001703
1704 /* Copy back the bytes variables, which might have been modified by the
1705 callback */
1706 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
1707 if (!inputobj)
1708 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00001709 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001710 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00001711 }
Christian Heimes72b710a2008-05-26 13:28:38 +00001712 *input = PyBytes_AS_STRING(inputobj);
1713 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00001714 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00001715 /* we can DECREF safely, as the exception has another reference,
1716 so the object won't go away. */
1717 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00001718
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001719 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001720 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00001721 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001722 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
1723 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00001724 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001725
1726 /* need more space? (at least enough for what we
1727 have+the replacement+the rest of the string (starting
1728 at the new input position), so we won't have to check space
1729 when there are no errors in the rest of the string) */
1730 repptr = PyUnicode_AS_UNICODE(repunicode);
1731 repsize = PyUnicode_GET_SIZE(repunicode);
1732 requiredsize = *outpos + repsize + insize-newpos;
1733 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001734 if (requiredsize<2*outsize)
1735 requiredsize = 2*outsize;
1736 if (_PyUnicode_Resize(output, requiredsize) < 0)
1737 goto onError;
1738 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001739 }
1740 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00001741 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001742 Py_UNICODE_COPY(*outptr, repptr, repsize);
1743 *outptr += repsize;
1744 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00001745
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001746 /* we made it! */
1747 res = 0;
1748
Benjamin Peterson29060642009-01-31 22:14:21 +00001749 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001750 Py_XDECREF(restuple);
1751 return res;
1752}
1753
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001754/* --- UTF-7 Codec -------------------------------------------------------- */
1755
Antoine Pitrou244651a2009-05-04 18:56:13 +00001756/* See RFC2152 for details. We encode conservatively and decode liberally. */
1757
1758/* Three simple macros defining base-64. */
1759
1760/* Is c a base-64 character? */
1761
1762#define IS_BASE64(c) \
1763 (((c) >= 'A' && (c) <= 'Z') || \
1764 ((c) >= 'a' && (c) <= 'z') || \
1765 ((c) >= '0' && (c) <= '9') || \
1766 (c) == '+' || (c) == '/')
1767
1768/* given that c is a base-64 character, what is its base-64 value? */
1769
1770#define FROM_BASE64(c) \
1771 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
1772 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
1773 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
1774 (c) == '+' ? 62 : 63)
1775
1776/* What is the base-64 character of the bottom 6 bits of n? */
1777
1778#define TO_BASE64(n) \
1779 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
1780
1781/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
1782 * decoded as itself. We are permissive on decoding; the only ASCII
1783 * byte not decoding to itself is the + which begins a base64
1784 * string. */
1785
1786#define DECODE_DIRECT(c) \
1787 ((c) <= 127 && (c) != '+')
1788
1789/* The UTF-7 encoder treats ASCII characters differently according to
1790 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
1791 * the above). See RFC2152. This array identifies these different
1792 * sets:
1793 * 0 : "Set D"
1794 * alphanumeric and '(),-./:?
1795 * 1 : "Set O"
1796 * !"#$%&*;<=>@[]^_`{|}
1797 * 2 : "whitespace"
1798 * ht nl cr sp
1799 * 3 : special (must be base64 encoded)
1800 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
1801 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001802
Tim Petersced69f82003-09-16 20:30:58 +00001803static
Antoine Pitrou244651a2009-05-04 18:56:13 +00001804char utf7_category[128] = {
1805/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
1806 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
1807/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
1808 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
1809/* sp ! " # $ % & ' ( ) * + , - . / */
1810 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
1811/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1812 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
1813/* @ A B C D E F G H I J K L M N O */
1814 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1815/* P Q R S T U V W X Y Z [ \ ] ^ _ */
1816 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
1817/* ` a b c d e f g h i j k l m n o */
1818 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1819/* p q r s t u v w x y z { | } ~ del */
1820 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001821};
1822
Antoine Pitrou244651a2009-05-04 18:56:13 +00001823/* ENCODE_DIRECT: this character should be encoded as itself. The
1824 * answer depends on whether we are encoding set O as itself, and also
1825 * on whether we are encoding whitespace as itself. RFC2152 makes it
1826 * clear that the answers to these questions vary between
1827 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00001828
Antoine Pitrou244651a2009-05-04 18:56:13 +00001829#define ENCODE_DIRECT(c, directO, directWS) \
1830 ((c) < 128 && (c) > 0 && \
1831 ((utf7_category[(c)] == 0) || \
1832 (directWS && (utf7_category[(c)] == 2)) || \
1833 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001834
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001835PyObject *PyUnicode_DecodeUTF7(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00001836 Py_ssize_t size,
1837 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001838{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00001839 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
1840}
1841
Antoine Pitrou244651a2009-05-04 18:56:13 +00001842/* The decoder. The only state we preserve is our read position,
1843 * i.e. how many characters we have consumed. So if we end in the
1844 * middle of a shift sequence we have to back off the read position
1845 * and the output to the beginning of the sequence, otherwise we lose
1846 * all the shift state (seen bits, number of bits seen, high
1847 * surrogate). */
1848
Christian Heimes5d14c2b2007-11-20 23:38:09 +00001849PyObject *PyUnicode_DecodeUTF7Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00001850 Py_ssize_t size,
1851 const char *errors,
1852 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00001853{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001854 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001855 Py_ssize_t startinpos;
1856 Py_ssize_t endinpos;
1857 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001858 const char *e;
1859 PyUnicodeObject *unicode;
1860 Py_UNICODE *p;
1861 const char *errmsg = "";
1862 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00001863 Py_UNICODE *shiftOutStart;
1864 unsigned int base64bits = 0;
1865 unsigned long base64buffer = 0;
1866 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001867 PyObject *errorHandler = NULL;
1868 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001869
1870 unicode = _PyUnicode_New(size);
1871 if (!unicode)
1872 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00001873 if (size == 0) {
1874 if (consumed)
1875 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001876 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00001877 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001878
1879 p = unicode->str;
Antoine Pitrou244651a2009-05-04 18:56:13 +00001880 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001881 e = s + size;
1882
1883 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001884 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00001885 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00001886 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001887
Antoine Pitrou244651a2009-05-04 18:56:13 +00001888 if (inShift) { /* in a base-64 section */
1889 if (IS_BASE64(ch)) { /* consume a base-64 character */
1890 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
1891 base64bits += 6;
1892 s++;
1893 if (base64bits >= 16) {
1894 /* we have enough bits for a UTF-16 value */
1895 Py_UNICODE outCh = (Py_UNICODE)
1896 (base64buffer >> (base64bits-16));
1897 base64bits -= 16;
1898 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
1899 if (surrogate) {
1900 /* expecting a second surrogate */
1901 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
1902#ifdef Py_UNICODE_WIDE
1903 *p++ = (((surrogate & 0x3FF)<<10)
1904 | (outCh & 0x3FF)) + 0x10000;
1905#else
1906 *p++ = surrogate;
1907 *p++ = outCh;
1908#endif
1909 surrogate = 0;
1910 }
1911 else {
1912 surrogate = 0;
1913 errmsg = "second surrogate missing";
1914 goto utf7Error;
1915 }
1916 }
1917 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
1918 /* first surrogate */
1919 surrogate = outCh;
1920 }
1921 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
1922 errmsg = "unexpected second surrogate";
1923 goto utf7Error;
1924 }
1925 else {
1926 *p++ = outCh;
1927 }
1928 }
1929 }
1930 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001931 inShift = 0;
1932 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00001933 if (surrogate) {
1934 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00001935 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001936 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00001937 if (base64bits > 0) { /* left-over bits */
1938 if (base64bits >= 6) {
1939 /* We've seen at least one base-64 character */
1940 errmsg = "partial character in shift sequence";
1941 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001942 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00001943 else {
1944 /* Some bits remain; they should be zero */
1945 if (base64buffer != 0) {
1946 errmsg = "non-zero padding bits in shift sequence";
1947 goto utf7Error;
1948 }
1949 }
1950 }
1951 if (ch != '-') {
1952 /* '-' is absorbed; other terminating
1953 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001954 *p++ = ch;
1955 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001956 }
1957 }
1958 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001959 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00001960 s++; /* consume '+' */
1961 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001962 s++;
1963 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00001964 }
1965 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001966 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00001967 shiftOutStart = p;
1968 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001969 }
1970 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00001971 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001972 *p++ = ch;
1973 s++;
1974 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00001975 else {
1976 startinpos = s-starts;
1977 s++;
1978 errmsg = "unexpected special character";
1979 goto utf7Error;
1980 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001981 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00001982utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001983 outpos = p-PyUnicode_AS_UNICODE(unicode);
1984 endinpos = s-starts;
1985 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00001986 errors, &errorHandler,
1987 "utf7", errmsg,
1988 &starts, &e, &startinpos, &endinpos, &exc, &s,
1989 &unicode, &outpos, &p))
1990 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001991 }
1992
Antoine Pitrou244651a2009-05-04 18:56:13 +00001993 /* end of string */
1994
1995 if (inShift && !consumed) { /* in shift sequence, no more to follow */
1996 /* if we're in an inconsistent state, that's an error */
1997 if (surrogate ||
1998 (base64bits >= 6) ||
1999 (base64bits > 0 && base64buffer != 0)) {
2000 outpos = p-PyUnicode_AS_UNICODE(unicode);
2001 endinpos = size;
2002 if (unicode_decode_call_errorhandler(
2003 errors, &errorHandler,
2004 "utf7", "unterminated shift sequence",
2005 &starts, &e, &startinpos, &endinpos, &exc, &s,
2006 &unicode, &outpos, &p))
2007 goto onError;
2008 if (s < e)
2009 goto restart;
2010 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002011 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002012
2013 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002014 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00002015 if (inShift) {
2016 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002017 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002018 }
2019 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002020 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002021 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002022 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002023
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00002024 if (_PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002025 goto onError;
2026
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002027 Py_XDECREF(errorHandler);
2028 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002029 return (PyObject *)unicode;
2030
Benjamin Peterson29060642009-01-31 22:14:21 +00002031 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002032 Py_XDECREF(errorHandler);
2033 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002034 Py_DECREF(unicode);
2035 return NULL;
2036}
2037
2038
2039PyObject *PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002040 Py_ssize_t size,
Antoine Pitrou244651a2009-05-04 18:56:13 +00002041 int base64SetO,
2042 int base64WhiteSpace,
Benjamin Peterson29060642009-01-31 22:14:21 +00002043 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002044{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002045 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002046 /* It might be possible to tighten this worst case */
Antoine Pitrou244651a2009-05-04 18:56:13 +00002047 Py_ssize_t allocated = 5 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002048 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002049 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002050 unsigned int base64bits = 0;
2051 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002052 char * out;
2053 char * start;
2054
2055 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00002056 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002057
Antoine Pitrou244651a2009-05-04 18:56:13 +00002058 if (allocated / 5 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00002059 return PyErr_NoMemory();
2060
Antoine Pitrou244651a2009-05-04 18:56:13 +00002061 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002062 if (v == NULL)
2063 return NULL;
2064
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002065 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002066 for (;i < size; ++i) {
2067 Py_UNICODE ch = s[i];
2068
Antoine Pitrou244651a2009-05-04 18:56:13 +00002069 if (inShift) {
2070 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
2071 /* shifting out */
2072 if (base64bits) { /* output remaining bits */
2073 *out++ = TO_BASE64(base64buffer << (6-base64bits));
2074 base64buffer = 0;
2075 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002076 }
2077 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002078 /* Characters not in the BASE64 set implicitly unshift the sequence
2079 so no '-' is required, except if the character is itself a '-' */
2080 if (IS_BASE64(ch) || ch == '-') {
2081 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002082 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002083 *out++ = (char) ch;
2084 }
2085 else {
2086 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00002087 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002088 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002089 else { /* not in a shift sequence */
2090 if (ch == '+') {
2091 *out++ = '+';
2092 *out++ = '-';
2093 }
2094 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
2095 *out++ = (char) ch;
2096 }
2097 else {
2098 *out++ = '+';
2099 inShift = 1;
2100 goto encode_char;
2101 }
2102 }
2103 continue;
2104encode_char:
2105#ifdef Py_UNICODE_WIDE
2106 if (ch >= 0x10000) {
2107 /* code first surrogate */
2108 base64bits += 16;
2109 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
2110 while (base64bits >= 6) {
2111 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
2112 base64bits -= 6;
2113 }
2114 /* prepare second surrogate */
2115 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
2116 }
2117#endif
2118 base64bits += 16;
2119 base64buffer = (base64buffer << 16) | ch;
2120 while (base64bits >= 6) {
2121 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
2122 base64bits -= 6;
2123 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00002124 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002125 if (base64bits)
2126 *out++= TO_BASE64(base64buffer << (6-base64bits) );
2127 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002128 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002129 if (_PyBytes_Resize(&v, out - start) < 0)
2130 return NULL;
2131 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002132}
2133
Antoine Pitrou244651a2009-05-04 18:56:13 +00002134#undef IS_BASE64
2135#undef FROM_BASE64
2136#undef TO_BASE64
2137#undef DECODE_DIRECT
2138#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002139
Guido van Rossumd57fd912000-03-10 22:53:23 +00002140/* --- UTF-8 Codec -------------------------------------------------------- */
2141
Tim Petersced69f82003-09-16 20:30:58 +00002142static
Guido van Rossumd57fd912000-03-10 22:53:23 +00002143char utf8_code_length[256] = {
2144 /* Map UTF-8 encoded prefix byte to sequence length. zero means
2145 illegal prefix. see RFC 2279 for details */
2146 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2147 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2148 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2149 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2150 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2151 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2152 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2153 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2154 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2155 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2156 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2157 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2158 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2159 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2160 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2161 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 0, 0
2162};
2163
Guido van Rossumd57fd912000-03-10 22:53:23 +00002164PyObject *PyUnicode_DecodeUTF8(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002165 Py_ssize_t size,
2166 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002167{
Walter Dörwald69652032004-09-07 20:24:22 +00002168 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
2169}
2170
Antoine Pitrouab868312009-01-10 15:40:25 +00002171/* Mask to check or force alignment of a pointer to C 'long' boundaries */
2172#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
2173
2174/* Mask to quickly check whether a C 'long' contains a
2175 non-ASCII, UTF8-encoded char. */
2176#if (SIZEOF_LONG == 8)
2177# define ASCII_CHAR_MASK 0x8080808080808080L
2178#elif (SIZEOF_LONG == 4)
2179# define ASCII_CHAR_MASK 0x80808080L
2180#else
2181# error C 'long' size should be either 4 or 8!
2182#endif
2183
Walter Dörwald69652032004-09-07 20:24:22 +00002184PyObject *PyUnicode_DecodeUTF8Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002185 Py_ssize_t size,
2186 const char *errors,
2187 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00002188{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002189 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002190 int n;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002191 Py_ssize_t startinpos;
2192 Py_ssize_t endinpos;
2193 Py_ssize_t outpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00002194 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002195 PyUnicodeObject *unicode;
2196 Py_UNICODE *p;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002197 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002198 PyObject *errorHandler = NULL;
2199 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002200
2201 /* Note: size will always be longer than the resulting Unicode
2202 character count */
2203 unicode = _PyUnicode_New(size);
2204 if (!unicode)
2205 return NULL;
Walter Dörwald69652032004-09-07 20:24:22 +00002206 if (size == 0) {
2207 if (consumed)
2208 *consumed = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002209 return (PyObject *)unicode;
Walter Dörwald69652032004-09-07 20:24:22 +00002210 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002211
2212 /* Unpack UTF-8 encoded data */
2213 p = unicode->str;
2214 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00002215 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002216
2217 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002218 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002219
2220 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00002221 /* Fast path for runs of ASCII characters. Given that common UTF-8
2222 input will consist of an overwhelming majority of ASCII
2223 characters, we try to optimize for this case by checking
2224 as many characters as a C 'long' can contain.
2225 First, check if we can do an aligned read, as most CPUs have
2226 a penalty for unaligned reads.
2227 */
2228 if (!((size_t) s & LONG_PTR_MASK)) {
2229 /* Help register allocation */
2230 register const char *_s = s;
2231 register Py_UNICODE *_p = p;
2232 while (_s < aligned_end) {
2233 /* Read a whole long at a time (either 4 or 8 bytes),
2234 and do a fast unrolled copy if it only contains ASCII
2235 characters. */
2236 unsigned long data = *(unsigned long *) _s;
2237 if (data & ASCII_CHAR_MASK)
2238 break;
2239 _p[0] = (unsigned char) _s[0];
2240 _p[1] = (unsigned char) _s[1];
2241 _p[2] = (unsigned char) _s[2];
2242 _p[3] = (unsigned char) _s[3];
2243#if (SIZEOF_LONG == 8)
2244 _p[4] = (unsigned char) _s[4];
2245 _p[5] = (unsigned char) _s[5];
2246 _p[6] = (unsigned char) _s[6];
2247 _p[7] = (unsigned char) _s[7];
2248#endif
2249 _s += SIZEOF_LONG;
2250 _p += SIZEOF_LONG;
2251 }
2252 s = _s;
2253 p = _p;
2254 if (s == e)
2255 break;
2256 ch = (unsigned char)*s;
2257 }
2258 }
2259
2260 if (ch < 0x80) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002261 *p++ = (Py_UNICODE)ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002262 s++;
2263 continue;
2264 }
2265
2266 n = utf8_code_length[ch];
2267
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002268 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002269 if (consumed)
2270 break;
2271 else {
2272 errmsg = "unexpected end of data";
2273 startinpos = s-starts;
2274 endinpos = size;
2275 goto utf8Error;
2276 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002277 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002278
2279 switch (n) {
2280
2281 case 0:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002282 errmsg = "unexpected code byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002283 startinpos = s-starts;
2284 endinpos = startinpos+1;
2285 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002286
2287 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002288 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00002289 startinpos = s-starts;
2290 endinpos = startinpos+1;
2291 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002292
2293 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002294 if ((s[1] & 0xc0) != 0x80) {
2295 errmsg = "invalid data";
Benjamin Peterson29060642009-01-31 22:14:21 +00002296 startinpos = s-starts;
2297 endinpos = startinpos+2;
2298 goto utf8Error;
2299 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002300 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002301 if (ch < 0x80) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002302 startinpos = s-starts;
2303 endinpos = startinpos+2;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002304 errmsg = "illegal encoding";
Benjamin Peterson29060642009-01-31 22:14:21 +00002305 goto utf8Error;
2306 }
2307 else
2308 *p++ = (Py_UNICODE)ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002309 break;
2310
2311 case 3:
Tim Petersced69f82003-09-16 20:30:58 +00002312 if ((s[1] & 0xc0) != 0x80 ||
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002313 (s[2] & 0xc0) != 0x80) {
2314 errmsg = "invalid data";
Benjamin Peterson29060642009-01-31 22:14:21 +00002315 startinpos = s-starts;
2316 endinpos = startinpos+3;
2317 goto utf8Error;
2318 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002319 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002320 if (ch < 0x0800 || (ch >= 0xd800 && ch <= 0xDFFF)) {
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002321 errmsg = "illegal encoding";
Benjamin Peterson29060642009-01-31 22:14:21 +00002322 startinpos = s-starts;
2323 endinpos = startinpos+3;
2324 goto utf8Error;
2325 }
2326 else
2327 *p++ = (Py_UNICODE)ch;
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002328 break;
2329
2330 case 4:
2331 if ((s[1] & 0xc0) != 0x80 ||
2332 (s[2] & 0xc0) != 0x80 ||
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002333 (s[3] & 0xc0) != 0x80) {
2334 errmsg = "invalid data";
Benjamin Peterson29060642009-01-31 22:14:21 +00002335 startinpos = s-starts;
2336 endinpos = startinpos+4;
2337 goto utf8Error;
2338 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002339 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Benjamin Peterson29060642009-01-31 22:14:21 +00002340 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002341 /* validate and convert to UTF-16 */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002342 if ((ch < 0x10000) /* minimum value allowed for 4
Benjamin Peterson29060642009-01-31 22:14:21 +00002343 byte encoding */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002344 || (ch > 0x10ffff)) /* maximum value allowed for
Benjamin Peterson29060642009-01-31 22:14:21 +00002345 UTF-16 */
2346 {
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002347 errmsg = "illegal encoding";
Benjamin Peterson29060642009-01-31 22:14:21 +00002348 startinpos = s-starts;
2349 endinpos = startinpos+4;
2350 goto utf8Error;
2351 }
Fredrik Lundh8f455852001-06-27 18:59:43 +00002352#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00002353 *p++ = (Py_UNICODE)ch;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002354#else
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002355 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00002356
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002357 /* translate from 10000..10FFFF to 0..FFFF */
2358 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00002359
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002360 /* high surrogate = top 10 bits added to D800 */
2361 *p++ = (Py_UNICODE)(0xD800 + (ch >> 10));
Tim Petersced69f82003-09-16 20:30:58 +00002362
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002363 /* low surrogate = bottom 10 bits added to DC00 */
Fredrik Lundh45714e92001-06-26 16:39:36 +00002364 *p++ = (Py_UNICODE)(0xDC00 + (ch & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002365#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00002366 break;
2367
2368 default:
2369 /* Other sizes are only needed for UCS-4 */
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002370 errmsg = "unsupported Unicode code range";
Benjamin Peterson29060642009-01-31 22:14:21 +00002371 startinpos = s-starts;
2372 endinpos = startinpos+n;
2373 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002374 }
2375 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00002376 continue;
Tim Petersced69f82003-09-16 20:30:58 +00002377
Benjamin Peterson29060642009-01-31 22:14:21 +00002378 utf8Error:
2379 outpos = p-PyUnicode_AS_UNICODE(unicode);
2380 if (unicode_decode_call_errorhandler(
2381 errors, &errorHandler,
2382 "utf8", errmsg,
2383 &starts, &e, &startinpos, &endinpos, &exc, &s,
2384 &unicode, &outpos, &p))
2385 goto onError;
2386 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002387 }
Walter Dörwald69652032004-09-07 20:24:22 +00002388 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00002389 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002390
2391 /* Adjust length */
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00002392 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002393 goto onError;
2394
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002395 Py_XDECREF(errorHandler);
2396 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002397 return (PyObject *)unicode;
2398
Benjamin Peterson29060642009-01-31 22:14:21 +00002399 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002400 Py_XDECREF(errorHandler);
2401 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002402 Py_DECREF(unicode);
2403 return NULL;
2404}
2405
Antoine Pitrouab868312009-01-10 15:40:25 +00002406#undef ASCII_CHAR_MASK
2407
2408
Tim Peters602f7402002-04-27 18:03:26 +00002409/* Allocation strategy: if the string is short, convert into a stack buffer
2410 and allocate exactly as much space needed at the end. Else allocate the
2411 maximum possible needed (4 result bytes per Unicode character), and return
2412 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002413*/
Tim Peters7e3d9612002-04-21 03:26:37 +00002414PyObject *
2415PyUnicode_EncodeUTF8(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002416 Py_ssize_t size,
2417 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002418{
Tim Peters602f7402002-04-27 18:03:26 +00002419#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00002420
Guido van Rossum98297ee2007-11-06 21:34:58 +00002421 Py_ssize_t i; /* index into s of next input byte */
2422 PyObject *result; /* result string object */
2423 char *p; /* next free byte in output buffer */
2424 Py_ssize_t nallocated; /* number of result bytes allocated */
2425 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00002426 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002427 PyObject *errorHandler = NULL;
2428 PyObject *exc = NULL;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00002429
Tim Peters602f7402002-04-27 18:03:26 +00002430 assert(s != NULL);
2431 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002432
Tim Peters602f7402002-04-27 18:03:26 +00002433 if (size <= MAX_SHORT_UNICHARS) {
2434 /* Write into the stack buffer; nallocated can't overflow.
2435 * At the end, we'll allocate exactly as much heap space as it
2436 * turns out we need.
2437 */
2438 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002439 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00002440 p = stackbuf;
2441 }
2442 else {
2443 /* Overallocate on the heap, and give the excess back at the end. */
2444 nallocated = size * 4;
2445 if (nallocated / 4 != size) /* overflow! */
2446 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00002447 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002448 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00002449 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00002450 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00002451 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002452
Tim Peters602f7402002-04-27 18:03:26 +00002453 for (i = 0; i < size;) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002454 Py_UCS4 ch = s[i++];
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002455
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002456 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00002457 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002458 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002459
Guido van Rossumd57fd912000-03-10 22:53:23 +00002460 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00002461 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00002462 *p++ = (char)(0xc0 | (ch >> 6));
2463 *p++ = (char)(0x80 | (ch & 0x3f));
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002464 }
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002465 else {
Tim Peters602f7402002-04-27 18:03:26 +00002466 /* Encode UCS2 Unicode ordinals */
2467 if (ch < 0x10000) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002468#ifndef Py_UNICODE_WIDE
Tim Peters602f7402002-04-27 18:03:26 +00002469 /* Special case: check for high surrogate */
2470 if (0xD800 <= ch && ch <= 0xDBFF && i != size) {
2471 Py_UCS4 ch2 = s[i];
2472 /* Check for low surrogate and combine the two to
2473 form a UCS4 value */
2474 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002475 ch = ((ch - 0xD800) << 10 | (ch2 - 0xDC00)) + 0x10000;
Tim Peters602f7402002-04-27 18:03:26 +00002476 i++;
2477 goto encodeUCS4;
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002478 }
Tim Peters602f7402002-04-27 18:03:26 +00002479 /* Fall through: handles isolated high surrogates */
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002480 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002481#endif
2482 if (ch >= 0xd800 && ch <= 0xdfff) {
2483 Py_ssize_t newpos;
2484 PyObject *rep;
2485 char *prep;
2486 int k;
2487 rep = unicode_encode_call_errorhandler
2488 (errors, &errorHandler, "utf-8", "surrogates not allowed",
2489 s, size, &exc, i-1, i, &newpos);
2490 if (!rep)
2491 goto error;
2492 /* Implementation limitations: only support error handler that return
2493 bytes, and only support up to four replacement bytes. */
2494 if (!PyBytes_Check(rep)) {
2495 PyErr_SetString(PyExc_TypeError, "error handler should have returned bytes");
2496 Py_DECREF(rep);
2497 goto error;
2498 }
2499 if (PyBytes_Size(rep) > 4) {
2500 PyErr_SetString(PyExc_TypeError, "error handler returned too many bytes");
2501 Py_DECREF(rep);
2502 goto error;
2503 }
2504 prep = PyBytes_AsString(rep);
2505 for(k = PyBytes_Size(rep); k > 0; k--)
2506 *p++ = *prep++;
2507 Py_DECREF(rep);
2508 continue;
2509
2510 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002511 *p++ = (char)(0xe0 | (ch >> 12));
Tim Peters602f7402002-04-27 18:03:26 +00002512 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2513 *p++ = (char)(0x80 | (ch & 0x3f));
2514 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002515 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002516 encodeUCS4:
Tim Peters602f7402002-04-27 18:03:26 +00002517 /* Encode UCS4 Unicode ordinals */
2518 *p++ = (char)(0xf0 | (ch >> 18));
2519 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
2520 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2521 *p++ = (char)(0x80 | (ch & 0x3f));
2522 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002523 }
Tim Peters0eca65c2002-04-21 17:28:06 +00002524
Guido van Rossum98297ee2007-11-06 21:34:58 +00002525 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00002526 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002527 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00002528 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00002529 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00002530 }
2531 else {
Christian Heimesf3863112007-11-22 07:46:41 +00002532 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00002533 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00002534 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00002535 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00002536 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002537 Py_XDECREF(errorHandler);
2538 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002539 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002540 error:
2541 Py_XDECREF(errorHandler);
2542 Py_XDECREF(exc);
2543 Py_XDECREF(result);
2544 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002545
Tim Peters602f7402002-04-27 18:03:26 +00002546#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00002547}
2548
Guido van Rossumd57fd912000-03-10 22:53:23 +00002549PyObject *PyUnicode_AsUTF8String(PyObject *unicode)
2550{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002551 if (!PyUnicode_Check(unicode)) {
2552 PyErr_BadArgument();
2553 return NULL;
2554 }
Barry Warsaw2dd4abf2000-08-18 06:58:15 +00002555 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00002556 PyUnicode_GET_SIZE(unicode),
2557 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002558}
2559
Walter Dörwald41980ca2007-08-16 21:55:45 +00002560/* --- UTF-32 Codec ------------------------------------------------------- */
2561
2562PyObject *
2563PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002564 Py_ssize_t size,
2565 const char *errors,
2566 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00002567{
2568 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
2569}
2570
2571PyObject *
2572PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002573 Py_ssize_t size,
2574 const char *errors,
2575 int *byteorder,
2576 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00002577{
2578 const char *starts = s;
2579 Py_ssize_t startinpos;
2580 Py_ssize_t endinpos;
2581 Py_ssize_t outpos;
2582 PyUnicodeObject *unicode;
2583 Py_UNICODE *p;
2584#ifndef Py_UNICODE_WIDE
2585 int i, pairs;
2586#else
2587 const int pairs = 0;
2588#endif
2589 const unsigned char *q, *e;
2590 int bo = 0; /* assume native ordering by default */
2591 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00002592 /* Offsets from q for retrieving bytes in the right order. */
2593#ifdef BYTEORDER_IS_LITTLE_ENDIAN
2594 int iorder[] = {0, 1, 2, 3};
2595#else
2596 int iorder[] = {3, 2, 1, 0};
2597#endif
2598 PyObject *errorHandler = NULL;
2599 PyObject *exc = NULL;
Guido van Rossum8d991ed2007-08-17 15:41:00 +00002600 /* On narrow builds we split characters outside the BMP into two
2601 codepoints => count how much extra space we need. */
2602#ifndef Py_UNICODE_WIDE
2603 for (i = pairs = 0; i < size/4; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00002604 if (((Py_UCS4 *)s)[i] >= 0x10000)
2605 pairs++;
Guido van Rossum8d991ed2007-08-17 15:41:00 +00002606#endif
Walter Dörwald41980ca2007-08-16 21:55:45 +00002607
2608 /* This might be one to much, because of a BOM */
2609 unicode = _PyUnicode_New((size+3)/4+pairs);
2610 if (!unicode)
2611 return NULL;
2612 if (size == 0)
2613 return (PyObject *)unicode;
2614
2615 /* Unpack UTF-32 encoded data */
2616 p = unicode->str;
2617 q = (unsigned char *)s;
2618 e = q + size;
2619
2620 if (byteorder)
2621 bo = *byteorder;
2622
2623 /* Check for BOM marks (U+FEFF) in the input and adjust current
2624 byte order setting accordingly. In native mode, the leading BOM
2625 mark is skipped, in all other modes, it is copied to the output
2626 stream as-is (giving a ZWNBSP character). */
2627 if (bo == 0) {
2628 if (size >= 4) {
2629 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00002630 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00002631#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00002632 if (bom == 0x0000FEFF) {
2633 q += 4;
2634 bo = -1;
2635 }
2636 else if (bom == 0xFFFE0000) {
2637 q += 4;
2638 bo = 1;
2639 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00002640#else
Benjamin Peterson29060642009-01-31 22:14:21 +00002641 if (bom == 0x0000FEFF) {
2642 q += 4;
2643 bo = 1;
2644 }
2645 else if (bom == 0xFFFE0000) {
2646 q += 4;
2647 bo = -1;
2648 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00002649#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00002650 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00002651 }
2652
2653 if (bo == -1) {
2654 /* force LE */
2655 iorder[0] = 0;
2656 iorder[1] = 1;
2657 iorder[2] = 2;
2658 iorder[3] = 3;
2659 }
2660 else if (bo == 1) {
2661 /* force BE */
2662 iorder[0] = 3;
2663 iorder[1] = 2;
2664 iorder[2] = 1;
2665 iorder[3] = 0;
2666 }
2667
2668 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002669 Py_UCS4 ch;
2670 /* remaining bytes at the end? (size should be divisible by 4) */
2671 if (e-q<4) {
2672 if (consumed)
2673 break;
2674 errmsg = "truncated data";
2675 startinpos = ((const char *)q)-starts;
2676 endinpos = ((const char *)e)-starts;
2677 goto utf32Error;
2678 /* The remaining input chars are ignored if the callback
2679 chooses to skip the input */
2680 }
2681 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
2682 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00002683
Benjamin Peterson29060642009-01-31 22:14:21 +00002684 if (ch >= 0x110000)
2685 {
2686 errmsg = "codepoint not in range(0x110000)";
2687 startinpos = ((const char *)q)-starts;
2688 endinpos = startinpos+4;
2689 goto utf32Error;
2690 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00002691#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00002692 if (ch >= 0x10000)
2693 {
2694 *p++ = 0xD800 | ((ch-0x10000) >> 10);
2695 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
2696 }
2697 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00002698#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00002699 *p++ = ch;
2700 q += 4;
2701 continue;
2702 utf32Error:
2703 outpos = p-PyUnicode_AS_UNICODE(unicode);
2704 if (unicode_decode_call_errorhandler(
2705 errors, &errorHandler,
2706 "utf32", errmsg,
2707 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
2708 &unicode, &outpos, &p))
2709 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002710 }
2711
2712 if (byteorder)
2713 *byteorder = bo;
2714
2715 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00002716 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002717
2718 /* Adjust length */
2719 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
2720 goto onError;
2721
2722 Py_XDECREF(errorHandler);
2723 Py_XDECREF(exc);
2724 return (PyObject *)unicode;
2725
Benjamin Peterson29060642009-01-31 22:14:21 +00002726 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00002727 Py_DECREF(unicode);
2728 Py_XDECREF(errorHandler);
2729 Py_XDECREF(exc);
2730 return NULL;
2731}
2732
2733PyObject *
2734PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002735 Py_ssize_t size,
2736 const char *errors,
2737 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00002738{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002739 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002740 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00002741 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002742#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00002743 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002744#else
2745 const int pairs = 0;
2746#endif
2747 /* Offsets from p for storing byte pairs in the right order. */
2748#ifdef BYTEORDER_IS_LITTLE_ENDIAN
2749 int iorder[] = {0, 1, 2, 3};
2750#else
2751 int iorder[] = {3, 2, 1, 0};
2752#endif
2753
Benjamin Peterson29060642009-01-31 22:14:21 +00002754#define STORECHAR(CH) \
2755 do { \
2756 p[iorder[3]] = ((CH) >> 24) & 0xff; \
2757 p[iorder[2]] = ((CH) >> 16) & 0xff; \
2758 p[iorder[1]] = ((CH) >> 8) & 0xff; \
2759 p[iorder[0]] = (CH) & 0xff; \
2760 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00002761 } while(0)
2762
2763 /* In narrow builds we can output surrogate pairs as one codepoint,
2764 so we need less space. */
2765#ifndef Py_UNICODE_WIDE
2766 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00002767 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
2768 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
2769 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002770#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00002771 nsize = (size - pairs + (byteorder == 0));
2772 bytesize = nsize * 4;
2773 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00002774 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002775 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00002776 if (v == NULL)
2777 return NULL;
2778
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002779 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00002780 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00002781 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00002782 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002783 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002784
2785 if (byteorder == -1) {
2786 /* force LE */
2787 iorder[0] = 0;
2788 iorder[1] = 1;
2789 iorder[2] = 2;
2790 iorder[3] = 3;
2791 }
2792 else if (byteorder == 1) {
2793 /* force BE */
2794 iorder[0] = 3;
2795 iorder[1] = 2;
2796 iorder[2] = 1;
2797 iorder[3] = 0;
2798 }
2799
2800 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002801 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002802#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00002803 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
2804 Py_UCS4 ch2 = *s;
2805 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
2806 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
2807 s++;
2808 size--;
2809 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002810 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00002811#endif
2812 STORECHAR(ch);
2813 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002814
2815 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002816 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002817#undef STORECHAR
2818}
2819
2820PyObject *PyUnicode_AsUTF32String(PyObject *unicode)
2821{
2822 if (!PyUnicode_Check(unicode)) {
2823 PyErr_BadArgument();
2824 return NULL;
2825 }
2826 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00002827 PyUnicode_GET_SIZE(unicode),
2828 NULL,
2829 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00002830}
2831
Guido van Rossumd57fd912000-03-10 22:53:23 +00002832/* --- UTF-16 Codec ------------------------------------------------------- */
2833
Tim Peters772747b2001-08-09 22:21:55 +00002834PyObject *
2835PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002836 Py_ssize_t size,
2837 const char *errors,
2838 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002839{
Walter Dörwald69652032004-09-07 20:24:22 +00002840 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
2841}
2842
Antoine Pitrouab868312009-01-10 15:40:25 +00002843/* Two masks for fast checking of whether a C 'long' may contain
2844 UTF16-encoded surrogate characters. This is an efficient heuristic,
2845 assuming that non-surrogate characters with a code point >= 0x8000 are
2846 rare in most input.
2847 FAST_CHAR_MASK is used when the input is in native byte ordering,
2848 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00002849*/
Antoine Pitrouab868312009-01-10 15:40:25 +00002850#if (SIZEOF_LONG == 8)
2851# define FAST_CHAR_MASK 0x8000800080008000L
2852# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
2853#elif (SIZEOF_LONG == 4)
2854# define FAST_CHAR_MASK 0x80008000L
2855# define SWAPPED_FAST_CHAR_MASK 0x00800080L
2856#else
2857# error C 'long' size should be either 4 or 8!
2858#endif
2859
Walter Dörwald69652032004-09-07 20:24:22 +00002860PyObject *
2861PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002862 Py_ssize_t size,
2863 const char *errors,
2864 int *byteorder,
2865 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00002866{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002867 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002868 Py_ssize_t startinpos;
2869 Py_ssize_t endinpos;
2870 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002871 PyUnicodeObject *unicode;
2872 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00002873 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00002874 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00002875 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002876 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00002877 /* Offsets from q for retrieving byte pairs in the right order. */
2878#ifdef BYTEORDER_IS_LITTLE_ENDIAN
2879 int ihi = 1, ilo = 0;
2880#else
2881 int ihi = 0, ilo = 1;
2882#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002883 PyObject *errorHandler = NULL;
2884 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002885
2886 /* Note: size will always be longer than the resulting Unicode
2887 character count */
2888 unicode = _PyUnicode_New(size);
2889 if (!unicode)
2890 return NULL;
2891 if (size == 0)
2892 return (PyObject *)unicode;
2893
2894 /* Unpack UTF-16 encoded data */
2895 p = unicode->str;
Tim Peters772747b2001-08-09 22:21:55 +00002896 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00002897 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002898
2899 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00002900 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002901
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00002902 /* Check for BOM marks (U+FEFF) in the input and adjust current
2903 byte order setting accordingly. In native mode, the leading BOM
2904 mark is skipped, in all other modes, it is copied to the output
2905 stream as-is (giving a ZWNBSP character). */
2906 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00002907 if (size >= 2) {
2908 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00002909#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00002910 if (bom == 0xFEFF) {
2911 q += 2;
2912 bo = -1;
2913 }
2914 else if (bom == 0xFFFE) {
2915 q += 2;
2916 bo = 1;
2917 }
Tim Petersced69f82003-09-16 20:30:58 +00002918#else
Benjamin Peterson29060642009-01-31 22:14:21 +00002919 if (bom == 0xFEFF) {
2920 q += 2;
2921 bo = 1;
2922 }
2923 else if (bom == 0xFFFE) {
2924 q += 2;
2925 bo = -1;
2926 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00002927#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00002928 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00002929 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002930
Tim Peters772747b2001-08-09 22:21:55 +00002931 if (bo == -1) {
2932 /* force LE */
2933 ihi = 1;
2934 ilo = 0;
2935 }
2936 else if (bo == 1) {
2937 /* force BE */
2938 ihi = 0;
2939 ilo = 1;
2940 }
Antoine Pitrouab868312009-01-10 15:40:25 +00002941#ifdef BYTEORDER_IS_LITTLE_ENDIAN
2942 native_ordering = ilo < ihi;
2943#else
2944 native_ordering = ilo > ihi;
2945#endif
Tim Peters772747b2001-08-09 22:21:55 +00002946
Antoine Pitrouab868312009-01-10 15:40:25 +00002947 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00002948 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002949 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00002950 /* First check for possible aligned read of a C 'long'. Unaligned
2951 reads are more expensive, better to defer to another iteration. */
2952 if (!((size_t) q & LONG_PTR_MASK)) {
2953 /* Fast path for runs of non-surrogate chars. */
2954 register const unsigned char *_q = q;
2955 Py_UNICODE *_p = p;
2956 if (native_ordering) {
2957 /* Native ordering is simple: as long as the input cannot
2958 possibly contain a surrogate char, do an unrolled copy
2959 of several 16-bit code points to the target object.
2960 The non-surrogate check is done on several input bytes
2961 at a time (as many as a C 'long' can contain). */
2962 while (_q < aligned_end) {
2963 unsigned long data = * (unsigned long *) _q;
2964 if (data & FAST_CHAR_MASK)
2965 break;
2966 _p[0] = ((unsigned short *) _q)[0];
2967 _p[1] = ((unsigned short *) _q)[1];
2968#if (SIZEOF_LONG == 8)
2969 _p[2] = ((unsigned short *) _q)[2];
2970 _p[3] = ((unsigned short *) _q)[3];
2971#endif
2972 _q += SIZEOF_LONG;
2973 _p += SIZEOF_LONG / 2;
2974 }
2975 }
2976 else {
2977 /* Byteswapped ordering is similar, but we must decompose
2978 the copy bytewise, and take care of zero'ing out the
2979 upper bytes if the target object is in 32-bit units
2980 (that is, in UCS-4 builds). */
2981 while (_q < aligned_end) {
2982 unsigned long data = * (unsigned long *) _q;
2983 if (data & SWAPPED_FAST_CHAR_MASK)
2984 break;
2985 /* Zero upper bytes in UCS-4 builds */
2986#if (Py_UNICODE_SIZE > 2)
2987 _p[0] = 0;
2988 _p[1] = 0;
2989#if (SIZEOF_LONG == 8)
2990 _p[2] = 0;
2991 _p[3] = 0;
2992#endif
2993#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00002994 /* Issue #4916; UCS-4 builds on big endian machines must
2995 fill the two last bytes of each 4-byte unit. */
2996#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
2997# define OFF 2
2998#else
2999# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00003000#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00003001 ((unsigned char *) _p)[OFF + 1] = _q[0];
3002 ((unsigned char *) _p)[OFF + 0] = _q[1];
3003 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
3004 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
3005#if (SIZEOF_LONG == 8)
3006 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
3007 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
3008 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
3009 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
3010#endif
3011#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00003012 _q += SIZEOF_LONG;
3013 _p += SIZEOF_LONG / 2;
3014 }
3015 }
3016 p = _p;
3017 q = _q;
3018 if (q >= e)
3019 break;
3020 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003021 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003022
Benjamin Peterson14339b62009-01-31 16:36:08 +00003023 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00003024
3025 if (ch < 0xD800 || ch > 0xDFFF) {
3026 *p++ = ch;
3027 continue;
3028 }
3029
3030 /* UTF-16 code pair: */
3031 if (q > e) {
3032 errmsg = "unexpected end of data";
3033 startinpos = (((const char *)q) - 2) - starts;
3034 endinpos = ((const char *)e) + 1 - starts;
3035 goto utf16Error;
3036 }
3037 if (0xD800 <= ch && ch <= 0xDBFF) {
3038 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
3039 q += 2;
3040 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00003041#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003042 *p++ = ch;
3043 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003044#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003045 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003046#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003047 continue;
3048 }
3049 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003050 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00003051 startinpos = (((const char *)q)-4)-starts;
3052 endinpos = startinpos+2;
3053 goto utf16Error;
3054 }
3055
Benjamin Peterson14339b62009-01-31 16:36:08 +00003056 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003057 errmsg = "illegal encoding";
3058 startinpos = (((const char *)q)-2)-starts;
3059 endinpos = startinpos+2;
3060 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003061
Benjamin Peterson29060642009-01-31 22:14:21 +00003062 utf16Error:
3063 outpos = p - PyUnicode_AS_UNICODE(unicode);
3064 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00003065 errors,
3066 &errorHandler,
3067 "utf16", errmsg,
3068 &starts,
3069 (const char **)&e,
3070 &startinpos,
3071 &endinpos,
3072 &exc,
3073 (const char **)&q,
3074 &unicode,
3075 &outpos,
3076 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00003077 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003078 }
Antoine Pitrouab868312009-01-10 15:40:25 +00003079 /* remaining byte at the end? (size should be even) */
3080 if (e == q) {
3081 if (!consumed) {
3082 errmsg = "truncated data";
3083 startinpos = ((const char *)q) - starts;
3084 endinpos = ((const char *)e) + 1 - starts;
3085 outpos = p - PyUnicode_AS_UNICODE(unicode);
3086 if (unicode_decode_call_errorhandler(
3087 errors,
3088 &errorHandler,
3089 "utf16", errmsg,
3090 &starts,
3091 (const char **)&e,
3092 &startinpos,
3093 &endinpos,
3094 &exc,
3095 (const char **)&q,
3096 &unicode,
3097 &outpos,
3098 &p))
3099 goto onError;
3100 /* The remaining input chars are ignored if the callback
3101 chooses to skip the input */
3102 }
3103 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003104
3105 if (byteorder)
3106 *byteorder = bo;
3107
Walter Dörwald69652032004-09-07 20:24:22 +00003108 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00003109 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00003110
Guido van Rossumd57fd912000-03-10 22:53:23 +00003111 /* Adjust length */
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00003112 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003113 goto onError;
3114
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003115 Py_XDECREF(errorHandler);
3116 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003117 return (PyObject *)unicode;
3118
Benjamin Peterson29060642009-01-31 22:14:21 +00003119 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003120 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003121 Py_XDECREF(errorHandler);
3122 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003123 return NULL;
3124}
3125
Antoine Pitrouab868312009-01-10 15:40:25 +00003126#undef FAST_CHAR_MASK
3127#undef SWAPPED_FAST_CHAR_MASK
3128
Tim Peters772747b2001-08-09 22:21:55 +00003129PyObject *
3130PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003131 Py_ssize_t size,
3132 const char *errors,
3133 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003134{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003135 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00003136 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003137 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003138#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003139 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003140#else
3141 const int pairs = 0;
3142#endif
Tim Peters772747b2001-08-09 22:21:55 +00003143 /* Offsets from p for storing byte pairs in the right order. */
3144#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3145 int ihi = 1, ilo = 0;
3146#else
3147 int ihi = 0, ilo = 1;
3148#endif
3149
Benjamin Peterson29060642009-01-31 22:14:21 +00003150#define STORECHAR(CH) \
3151 do { \
3152 p[ihi] = ((CH) >> 8) & 0xff; \
3153 p[ilo] = (CH) & 0xff; \
3154 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00003155 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003156
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003157#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003158 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00003159 if (s[i] >= 0x10000)
3160 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003161#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003162 /* 2 * (size + pairs + (byteorder == 0)) */
3163 if (size > PY_SSIZE_T_MAX ||
3164 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00003165 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003166 nsize = size + pairs + (byteorder == 0);
3167 bytesize = nsize * 2;
3168 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003169 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003170 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003171 if (v == NULL)
3172 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003173
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003174 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003175 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003176 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00003177 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00003178 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00003179
3180 if (byteorder == -1) {
3181 /* force LE */
3182 ihi = 1;
3183 ilo = 0;
3184 }
3185 else if (byteorder == 1) {
3186 /* force BE */
3187 ihi = 0;
3188 ilo = 1;
3189 }
3190
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003191 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003192 Py_UNICODE ch = *s++;
3193 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003194#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003195 if (ch >= 0x10000) {
3196 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
3197 ch = 0xD800 | ((ch-0x10000) >> 10);
3198 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003199#endif
Tim Peters772747b2001-08-09 22:21:55 +00003200 STORECHAR(ch);
3201 if (ch2)
3202 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003203 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003204
3205 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003206 return v;
Tim Peters772747b2001-08-09 22:21:55 +00003207#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00003208}
3209
3210PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
3211{
3212 if (!PyUnicode_Check(unicode)) {
3213 PyErr_BadArgument();
3214 return NULL;
3215 }
3216 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003217 PyUnicode_GET_SIZE(unicode),
3218 NULL,
3219 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003220}
3221
3222/* --- Unicode Escape Codec ----------------------------------------------- */
3223
Fredrik Lundh06d12682001-01-24 07:59:11 +00003224static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00003225
Guido van Rossumd57fd912000-03-10 22:53:23 +00003226PyObject *PyUnicode_DecodeUnicodeEscape(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003227 Py_ssize_t size,
3228 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003229{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003230 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003231 Py_ssize_t startinpos;
3232 Py_ssize_t endinpos;
3233 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003234 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003235 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003236 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003237 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003238 char* message;
3239 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003240 PyObject *errorHandler = NULL;
3241 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003242
Guido van Rossumd57fd912000-03-10 22:53:23 +00003243 /* Escaped strings will always be longer than the resulting
3244 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003245 length after conversion to the true value.
3246 (but if the error callback returns a long replacement string
3247 we'll have to allocate more space) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003248 v = _PyUnicode_New(size);
3249 if (v == NULL)
3250 goto onError;
3251 if (size == 0)
3252 return (PyObject *)v;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003253
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003254 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003255 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003256
Guido van Rossumd57fd912000-03-10 22:53:23 +00003257 while (s < end) {
3258 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00003259 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003260 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003261
3262 /* Non-escape characters are interpreted as Unicode ordinals */
3263 if (*s != '\\') {
Fredrik Lundhccc74732001-02-18 22:13:49 +00003264 *p++ = (unsigned char) *s++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003265 continue;
3266 }
3267
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003268 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003269 /* \ - Escapes */
3270 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003271 c = *s++;
3272 if (s > end)
3273 c = '\0'; /* Invalid after \ */
3274 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003275
Benjamin Peterson29060642009-01-31 22:14:21 +00003276 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003277 case '\n': break;
3278 case '\\': *p++ = '\\'; break;
3279 case '\'': *p++ = '\''; break;
3280 case '\"': *p++ = '\"'; break;
3281 case 'b': *p++ = '\b'; break;
3282 case 'f': *p++ = '\014'; break; /* FF */
3283 case 't': *p++ = '\t'; break;
3284 case 'n': *p++ = '\n'; break;
3285 case 'r': *p++ = '\r'; break;
3286 case 'v': *p++ = '\013'; break; /* VT */
3287 case 'a': *p++ = '\007'; break; /* BEL, not classic C */
3288
Benjamin Peterson29060642009-01-31 22:14:21 +00003289 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003290 case '0': case '1': case '2': case '3':
3291 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003292 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003293 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003294 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003295 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003296 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00003297 }
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003298 *p++ = x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003299 break;
3300
Benjamin Peterson29060642009-01-31 22:14:21 +00003301 /* hex escapes */
3302 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003303 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003304 digits = 2;
3305 message = "truncated \\xXX escape";
3306 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003307
Benjamin Peterson29060642009-01-31 22:14:21 +00003308 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003309 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003310 digits = 4;
3311 message = "truncated \\uXXXX escape";
3312 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003313
Benjamin Peterson29060642009-01-31 22:14:21 +00003314 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00003315 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003316 digits = 8;
3317 message = "truncated \\UXXXXXXXX escape";
3318 hexescape:
3319 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003320 outpos = p-PyUnicode_AS_UNICODE(v);
3321 if (s+digits>end) {
3322 endinpos = size;
3323 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003324 errors, &errorHandler,
3325 "unicodeescape", "end of string in escape sequence",
3326 &starts, &end, &startinpos, &endinpos, &exc, &s,
3327 &v, &outpos, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003328 goto onError;
3329 goto nextByte;
3330 }
3331 for (i = 0; i < digits; ++i) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00003332 c = (unsigned char) s[i];
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003333 if (!ISXDIGIT(c)) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003334 endinpos = (s+i+1)-starts;
3335 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003336 errors, &errorHandler,
3337 "unicodeescape", message,
3338 &starts, &end, &startinpos, &endinpos, &exc, &s,
3339 &v, &outpos, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00003340 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003341 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00003342 }
3343 chr = (chr<<4) & ~0xF;
3344 if (c >= '0' && c <= '9')
3345 chr += c - '0';
3346 else if (c >= 'a' && c <= 'f')
3347 chr += 10 + c - 'a';
3348 else
3349 chr += 10 + c - 'A';
3350 }
3351 s += i;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00003352 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003353 /* _decoding_error will have already written into the
3354 target buffer. */
3355 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003356 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00003357 /* when we get here, chr is a 32-bit unicode character */
3358 if (chr <= 0xffff)
3359 /* UCS-2 character */
3360 *p++ = (Py_UNICODE) chr;
3361 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00003362 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00003363 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00003364#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003365 *p++ = chr;
3366#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00003367 chr -= 0x10000L;
3368 *p++ = 0xD800 + (Py_UNICODE) (chr >> 10);
Fredrik Lundh45714e92001-06-26 16:39:36 +00003369 *p++ = 0xDC00 + (Py_UNICODE) (chr & 0x03FF);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003370#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00003371 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003372 endinpos = s-starts;
3373 outpos = p-PyUnicode_AS_UNICODE(v);
3374 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003375 errors, &errorHandler,
3376 "unicodeescape", "illegal Unicode character",
3377 &starts, &end, &startinpos, &endinpos, &exc, &s,
3378 &v, &outpos, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00003379 goto onError;
3380 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00003381 break;
3382
Benjamin Peterson29060642009-01-31 22:14:21 +00003383 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00003384 case 'N':
3385 message = "malformed \\N character escape";
3386 if (ucnhash_CAPI == NULL) {
3387 /* load the unicode data module */
Benjamin Petersonb173f782009-05-05 22:31:58 +00003388 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00003389 if (ucnhash_CAPI == NULL)
3390 goto ucnhashError;
3391 }
3392 if (*s == '{') {
3393 const char *start = s+1;
3394 /* look for the closing brace */
3395 while (*s != '}' && s < end)
3396 s++;
3397 if (s > start && s < end && *s == '}') {
3398 /* found a name. look it up in the unicode database */
3399 message = "unknown Unicode character name";
3400 s++;
Martin v. Löwis480f1bb2006-03-09 23:38:20 +00003401 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1), &chr))
Fredrik Lundhccc74732001-02-18 22:13:49 +00003402 goto store;
3403 }
3404 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003405 endinpos = s-starts;
3406 outpos = p-PyUnicode_AS_UNICODE(v);
3407 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003408 errors, &errorHandler,
3409 "unicodeescape", message,
3410 &starts, &end, &startinpos, &endinpos, &exc, &s,
3411 &v, &outpos, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00003412 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003413 break;
3414
3415 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00003416 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003417 message = "\\ at end of string";
3418 s--;
3419 endinpos = s-starts;
3420 outpos = p-PyUnicode_AS_UNICODE(v);
3421 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003422 errors, &errorHandler,
3423 "unicodeescape", message,
3424 &starts, &end, &startinpos, &endinpos, &exc, &s,
3425 &v, &outpos, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00003426 goto onError;
3427 }
3428 else {
3429 *p++ = '\\';
3430 *p++ = (unsigned char)s[-1];
3431 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00003432 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003433 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003434 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003435 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003436 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003437 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003438 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00003439 Py_XDECREF(errorHandler);
3440 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003441 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00003442
Benjamin Peterson29060642009-01-31 22:14:21 +00003443 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00003444 PyErr_SetString(
3445 PyExc_UnicodeError,
3446 "\\N escapes not supported (can't load unicodedata module)"
3447 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003448 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003449 Py_XDECREF(errorHandler);
3450 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00003451 return NULL;
3452
Benjamin Peterson29060642009-01-31 22:14:21 +00003453 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003454 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003455 Py_XDECREF(errorHandler);
3456 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003457 return NULL;
3458}
3459
3460/* Return a Unicode-Escape string version of the Unicode object.
3461
3462 If quotes is true, the string is enclosed in u"" or u'' quotes as
3463 appropriate.
3464
3465*/
3466
Thomas Wouters477c8d52006-05-27 19:21:47 +00003467Py_LOCAL_INLINE(const Py_UNICODE *) findchar(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003468 Py_ssize_t size,
3469 Py_UNICODE ch)
Thomas Wouters477c8d52006-05-27 19:21:47 +00003470{
3471 /* like wcschr, but doesn't stop at NULL characters */
3472
3473 while (size-- > 0) {
3474 if (*s == ch)
3475 return s;
3476 s++;
3477 }
3478
3479 return NULL;
3480}
Barry Warsaw51ac5802000-03-20 16:36:48 +00003481
Walter Dörwald79e913e2007-05-12 11:08:06 +00003482static const char *hexdigits = "0123456789abcdef";
3483
3484PyObject *PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003485 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003486{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003487 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003488 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003489
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003490#ifdef Py_UNICODE_WIDE
3491 const Py_ssize_t expandsize = 10;
3492#else
3493 const Py_ssize_t expandsize = 6;
3494#endif
3495
Thomas Wouters89f507f2006-12-13 04:49:30 +00003496 /* XXX(nnorwitz): rather than over-allocating, it would be
3497 better to choose a different scheme. Perhaps scan the
3498 first N-chars of the string and allocate based on that size.
3499 */
3500 /* Initial allocation is based on the longest-possible unichr
3501 escape.
3502
3503 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
3504 unichr, so in this case it's the longest unichr escape. In
3505 narrow (UTF-16) builds this is five chars per source unichr
3506 since there are two unichrs in the surrogate pair, so in narrow
3507 (UTF-16) builds it's not the longest unichr escape.
3508
3509 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
3510 so in the narrow (UTF-16) build case it's the longest unichr
3511 escape.
3512 */
3513
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003514 if (size == 0)
3515 return PyBytes_FromStringAndSize(NULL, 0);
3516
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003517 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003518 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003519
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003520 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00003521 2
3522 + expandsize*size
3523 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003524 if (repr == NULL)
3525 return NULL;
3526
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003527 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003528
Guido van Rossumd57fd912000-03-10 22:53:23 +00003529 while (size-- > 0) {
3530 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00003531
Walter Dörwald79e913e2007-05-12 11:08:06 +00003532 /* Escape backslashes */
3533 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003534 *p++ = '\\';
3535 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00003536 continue;
Tim Petersced69f82003-09-16 20:30:58 +00003537 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00003538
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00003539#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003540 /* Map 21-bit characters to '\U00xxxxxx' */
3541 else if (ch >= 0x10000) {
3542 *p++ = '\\';
3543 *p++ = 'U';
Walter Dörwald79e913e2007-05-12 11:08:06 +00003544 *p++ = hexdigits[(ch >> 28) & 0x0000000F];
3545 *p++ = hexdigits[(ch >> 24) & 0x0000000F];
3546 *p++ = hexdigits[(ch >> 20) & 0x0000000F];
3547 *p++ = hexdigits[(ch >> 16) & 0x0000000F];
3548 *p++ = hexdigits[(ch >> 12) & 0x0000000F];
3549 *p++ = hexdigits[(ch >> 8) & 0x0000000F];
3550 *p++ = hexdigits[(ch >> 4) & 0x0000000F];
3551 *p++ = hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00003552 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003553 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00003554#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003555 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
3556 else if (ch >= 0xD800 && ch < 0xDC00) {
3557 Py_UNICODE ch2;
3558 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00003559
Benjamin Peterson29060642009-01-31 22:14:21 +00003560 ch2 = *s++;
3561 size--;
3562 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
3563 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
3564 *p++ = '\\';
3565 *p++ = 'U';
3566 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
3567 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
3568 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
3569 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
3570 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
3571 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
3572 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
3573 *p++ = hexdigits[ucs & 0x0000000F];
3574 continue;
3575 }
3576 /* Fall through: isolated surrogates are copied as-is */
3577 s--;
3578 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003579 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00003580#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00003581
Guido van Rossumd57fd912000-03-10 22:53:23 +00003582 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00003583 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003584 *p++ = '\\';
3585 *p++ = 'u';
Walter Dörwald79e913e2007-05-12 11:08:06 +00003586 *p++ = hexdigits[(ch >> 12) & 0x000F];
3587 *p++ = hexdigits[(ch >> 8) & 0x000F];
3588 *p++ = hexdigits[(ch >> 4) & 0x000F];
3589 *p++ = hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00003590 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00003591
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00003592 /* Map special whitespace to '\t', \n', '\r' */
3593 else if (ch == '\t') {
3594 *p++ = '\\';
3595 *p++ = 't';
3596 }
3597 else if (ch == '\n') {
3598 *p++ = '\\';
3599 *p++ = 'n';
3600 }
3601 else if (ch == '\r') {
3602 *p++ = '\\';
3603 *p++ = 'r';
3604 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00003605
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00003606 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00003607 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003608 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00003609 *p++ = 'x';
Walter Dörwald79e913e2007-05-12 11:08:06 +00003610 *p++ = hexdigits[(ch >> 4) & 0x000F];
3611 *p++ = hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00003612 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00003613
Guido van Rossumd57fd912000-03-10 22:53:23 +00003614 /* Copy everything else as-is */
3615 else
3616 *p++ = (char) ch;
3617 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003618
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003619 assert(p - PyBytes_AS_STRING(repr) > 0);
3620 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
3621 return NULL;
3622 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003623}
3624
Alexandre Vassalotti2056bed2008-12-27 19:46:35 +00003625PyObject *PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003626{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00003627 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003628 if (!PyUnicode_Check(unicode)) {
3629 PyErr_BadArgument();
3630 return NULL;
3631 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00003632 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
3633 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00003634 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003635}
3636
3637/* --- Raw Unicode Escape Codec ------------------------------------------- */
3638
3639PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003640 Py_ssize_t size,
3641 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003642{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003643 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003644 Py_ssize_t startinpos;
3645 Py_ssize_t endinpos;
3646 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003647 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003648 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003649 const char *end;
3650 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003651 PyObject *errorHandler = NULL;
3652 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00003653
Guido van Rossumd57fd912000-03-10 22:53:23 +00003654 /* Escaped strings will always be longer than the resulting
3655 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003656 length after conversion to the true value. (But decoding error
3657 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003658 v = _PyUnicode_New(size);
3659 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003660 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003661 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003662 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003663 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003664 end = s + size;
3665 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003666 unsigned char c;
3667 Py_UCS4 x;
3668 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003669 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003670
Benjamin Peterson29060642009-01-31 22:14:21 +00003671 /* Non-escape characters are interpreted as Unicode ordinals */
3672 if (*s != '\\') {
3673 *p++ = (unsigned char)*s++;
3674 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003675 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003676 startinpos = s-starts;
3677
3678 /* \u-escapes are only interpreted iff the number of leading
3679 backslashes if odd */
3680 bs = s;
3681 for (;s < end;) {
3682 if (*s != '\\')
3683 break;
3684 *p++ = (unsigned char)*s++;
3685 }
3686 if (((s - bs) & 1) == 0 ||
3687 s >= end ||
3688 (*s != 'u' && *s != 'U')) {
3689 continue;
3690 }
3691 p--;
3692 count = *s=='u' ? 4 : 8;
3693 s++;
3694
3695 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
3696 outpos = p-PyUnicode_AS_UNICODE(v);
3697 for (x = 0, i = 0; i < count; ++i, ++s) {
3698 c = (unsigned char)*s;
3699 if (!ISXDIGIT(c)) {
3700 endinpos = s-starts;
3701 if (unicode_decode_call_errorhandler(
3702 errors, &errorHandler,
3703 "rawunicodeescape", "truncated \\uXXXX",
3704 &starts, &end, &startinpos, &endinpos, &exc, &s,
3705 &v, &outpos, &p))
3706 goto onError;
3707 goto nextByte;
3708 }
3709 x = (x<<4) & ~0xF;
3710 if (c >= '0' && c <= '9')
3711 x += c - '0';
3712 else if (c >= 'a' && c <= 'f')
3713 x += 10 + c - 'a';
3714 else
3715 x += 10 + c - 'A';
3716 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00003717 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00003718 /* UCS-2 character */
3719 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00003720 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003721 /* UCS-4 character. Either store directly, or as
3722 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00003723#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003724 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00003725#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003726 x -= 0x10000L;
3727 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
3728 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00003729#endif
3730 } else {
3731 endinpos = s-starts;
3732 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003733 if (unicode_decode_call_errorhandler(
3734 errors, &errorHandler,
3735 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00003736 &starts, &end, &startinpos, &endinpos, &exc, &s,
3737 &v, &outpos, &p))
3738 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003739 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003740 nextByte:
3741 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003742 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003743 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003744 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003745 Py_XDECREF(errorHandler);
3746 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003747 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00003748
Benjamin Peterson29060642009-01-31 22:14:21 +00003749 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003750 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003751 Py_XDECREF(errorHandler);
3752 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003753 return NULL;
3754}
3755
3756PyObject *PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003757 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003758{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003759 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003760 char *p;
3761 char *q;
3762
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003763#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003764 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003765#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003766 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003767#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00003768
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003769 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003770 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00003771
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003772 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003773 if (repr == NULL)
3774 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00003775 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003776 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003777
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003778 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003779 while (size-- > 0) {
3780 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003781#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003782 /* Map 32-bit characters to '\Uxxxxxxxx' */
3783 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003784 *p++ = '\\';
3785 *p++ = 'U';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00003786 *p++ = hexdigits[(ch >> 28) & 0xf];
3787 *p++ = hexdigits[(ch >> 24) & 0xf];
3788 *p++ = hexdigits[(ch >> 20) & 0xf];
3789 *p++ = hexdigits[(ch >> 16) & 0xf];
3790 *p++ = hexdigits[(ch >> 12) & 0xf];
3791 *p++ = hexdigits[(ch >> 8) & 0xf];
3792 *p++ = hexdigits[(ch >> 4) & 0xf];
3793 *p++ = hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00003794 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003795 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00003796#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003797 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
3798 if (ch >= 0xD800 && ch < 0xDC00) {
3799 Py_UNICODE ch2;
3800 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00003801
Benjamin Peterson29060642009-01-31 22:14:21 +00003802 ch2 = *s++;
3803 size--;
3804 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
3805 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
3806 *p++ = '\\';
3807 *p++ = 'U';
3808 *p++ = hexdigits[(ucs >> 28) & 0xf];
3809 *p++ = hexdigits[(ucs >> 24) & 0xf];
3810 *p++ = hexdigits[(ucs >> 20) & 0xf];
3811 *p++ = hexdigits[(ucs >> 16) & 0xf];
3812 *p++ = hexdigits[(ucs >> 12) & 0xf];
3813 *p++ = hexdigits[(ucs >> 8) & 0xf];
3814 *p++ = hexdigits[(ucs >> 4) & 0xf];
3815 *p++ = hexdigits[ucs & 0xf];
3816 continue;
3817 }
3818 /* Fall through: isolated surrogates are copied as-is */
3819 s--;
3820 size++;
3821 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003822#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003823 /* Map 16-bit characters to '\uxxxx' */
3824 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003825 *p++ = '\\';
3826 *p++ = 'u';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00003827 *p++ = hexdigits[(ch >> 12) & 0xf];
3828 *p++ = hexdigits[(ch >> 8) & 0xf];
3829 *p++ = hexdigits[(ch >> 4) & 0xf];
3830 *p++ = hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00003831 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003832 /* Copy everything else as-is */
3833 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00003834 *p++ = (char) ch;
3835 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003836 size = p - q;
3837
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003838 assert(size > 0);
3839 if (_PyBytes_Resize(&repr, size) < 0)
3840 return NULL;
3841 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003842}
3843
3844PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
3845{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00003846 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003847 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00003848 PyErr_BadArgument();
3849 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003850 }
Walter Dörwald711005d2007-05-12 12:03:26 +00003851 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
3852 PyUnicode_GET_SIZE(unicode));
3853
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00003854 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003855}
3856
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003857/* --- Unicode Internal Codec ------------------------------------------- */
3858
3859PyObject *_PyUnicode_DecodeUnicodeInternal(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003860 Py_ssize_t size,
3861 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003862{
3863 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003864 Py_ssize_t startinpos;
3865 Py_ssize_t endinpos;
3866 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003867 PyUnicodeObject *v;
3868 Py_UNICODE *p;
3869 const char *end;
3870 const char *reason;
3871 PyObject *errorHandler = NULL;
3872 PyObject *exc = NULL;
3873
Neal Norwitzd43069c2006-01-08 01:12:10 +00003874#ifdef Py_UNICODE_WIDE
3875 Py_UNICODE unimax = PyUnicode_GetMax();
3876#endif
3877
Thomas Wouters89f507f2006-12-13 04:49:30 +00003878 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003879 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
3880 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003881 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003882 if (PyUnicode_GetSize((PyObject *)v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003883 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003884 p = PyUnicode_AS_UNICODE(v);
3885 end = s + size;
3886
3887 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00003888 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003889 /* We have to sanity check the raw data, otherwise doom looms for
3890 some malformed UCS-4 data. */
3891 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00003892#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003893 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00003894#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003895 end-s < Py_UNICODE_SIZE
3896 )
Benjamin Peterson29060642009-01-31 22:14:21 +00003897 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003898 startinpos = s - starts;
3899 if (end-s < Py_UNICODE_SIZE) {
3900 endinpos = end-starts;
3901 reason = "truncated input";
3902 }
3903 else {
3904 endinpos = s - starts + Py_UNICODE_SIZE;
3905 reason = "illegal code point (> 0x10FFFF)";
3906 }
3907 outpos = p - PyUnicode_AS_UNICODE(v);
3908 if (unicode_decode_call_errorhandler(
3909 errors, &errorHandler,
3910 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00003911 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00003912 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003913 goto onError;
3914 }
3915 }
3916 else {
3917 p++;
3918 s += Py_UNICODE_SIZE;
3919 }
3920 }
3921
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003922 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003923 goto onError;
3924 Py_XDECREF(errorHandler);
3925 Py_XDECREF(exc);
3926 return (PyObject *)v;
3927
Benjamin Peterson29060642009-01-31 22:14:21 +00003928 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003929 Py_XDECREF(v);
3930 Py_XDECREF(errorHandler);
3931 Py_XDECREF(exc);
3932 return NULL;
3933}
3934
Guido van Rossumd57fd912000-03-10 22:53:23 +00003935/* --- Latin-1 Codec ------------------------------------------------------ */
3936
3937PyObject *PyUnicode_DecodeLatin1(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003938 Py_ssize_t size,
3939 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003940{
3941 PyUnicodeObject *v;
3942 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00003943 const char *e, *unrolled_end;
Tim Petersced69f82003-09-16 20:30:58 +00003944
Guido van Rossumd57fd912000-03-10 22:53:23 +00003945 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003946 if (size == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003947 Py_UNICODE r = *(unsigned char*)s;
3948 return PyUnicode_FromUnicode(&r, 1);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00003949 }
3950
Guido van Rossumd57fd912000-03-10 22:53:23 +00003951 v = _PyUnicode_New(size);
3952 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003953 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003954 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003955 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003956 p = PyUnicode_AS_UNICODE(v);
Antoine Pitrouab868312009-01-10 15:40:25 +00003957 e = s + size;
3958 /* Unrolling the copy makes it much faster by reducing the looping
3959 overhead. This is similar to what many memcpy() implementations do. */
3960 unrolled_end = e - 4;
3961 while (s < unrolled_end) {
3962 p[0] = (unsigned char) s[0];
3963 p[1] = (unsigned char) s[1];
3964 p[2] = (unsigned char) s[2];
3965 p[3] = (unsigned char) s[3];
3966 s += 4;
3967 p += 4;
3968 }
3969 while (s < e)
3970 *p++ = (unsigned char) *s++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003971 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00003972
Benjamin Peterson29060642009-01-31 22:14:21 +00003973 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003974 Py_XDECREF(v);
3975 return NULL;
3976}
3977
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003978/* create or adjust a UnicodeEncodeError */
3979static void make_encode_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00003980 const char *encoding,
3981 const Py_UNICODE *unicode, Py_ssize_t size,
3982 Py_ssize_t startpos, Py_ssize_t endpos,
3983 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003984{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003985 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003986 *exceptionObject = PyUnicodeEncodeError_Create(
3987 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003988 }
3989 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00003990 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
3991 goto onError;
3992 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
3993 goto onError;
3994 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
3995 goto onError;
3996 return;
3997 onError:
3998 Py_DECREF(*exceptionObject);
3999 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004000 }
4001}
4002
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004003/* raises a UnicodeEncodeError */
4004static void raise_encode_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004005 const char *encoding,
4006 const Py_UNICODE *unicode, Py_ssize_t size,
4007 Py_ssize_t startpos, Py_ssize_t endpos,
4008 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004009{
4010 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004011 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004012 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004013 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004014}
4015
4016/* error handling callback helper:
4017 build arguments, call the callback and check the arguments,
4018 put the result into newpos and return the replacement string, which
4019 has to be freed by the caller */
4020static PyObject *unicode_encode_call_errorhandler(const char *errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00004021 PyObject **errorHandler,
4022 const char *encoding, const char *reason,
4023 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
4024 Py_ssize_t startpos, Py_ssize_t endpos,
4025 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004026{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004027 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004028
4029 PyObject *restuple;
4030 PyObject *resunicode;
4031
4032 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004033 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004034 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004035 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004036 }
4037
4038 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004039 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004040 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004041 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004042
4043 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00004044 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004045 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004046 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004047 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004048 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004049 Py_DECREF(restuple);
4050 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004051 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004052 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00004053 &resunicode, newpos)) {
4054 Py_DECREF(restuple);
4055 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004056 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004057 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
4058 PyErr_SetString(PyExc_TypeError, &argparse[3]);
4059 Py_DECREF(restuple);
4060 return NULL;
4061 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004062 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004063 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004064 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004065 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
4066 Py_DECREF(restuple);
4067 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004068 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004069 Py_INCREF(resunicode);
4070 Py_DECREF(restuple);
4071 return resunicode;
4072}
4073
4074static PyObject *unicode_encode_ucs1(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004075 Py_ssize_t size,
4076 const char *errors,
4077 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004078{
4079 /* output object */
4080 PyObject *res;
4081 /* pointers to the beginning and end+1 of input */
4082 const Py_UNICODE *startp = p;
4083 const Py_UNICODE *endp = p + size;
4084 /* pointer to the beginning of the unencodable characters */
4085 /* const Py_UNICODE *badp = NULL; */
4086 /* pointer into the output */
4087 char *str;
4088 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00004089 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004090 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
4091 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004092 PyObject *errorHandler = NULL;
4093 PyObject *exc = NULL;
4094 /* the following variable is used for caching string comparisons
4095 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
4096 int known_errorHandler = -1;
4097
4098 /* allocate enough for a simple encoding without
4099 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00004100 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00004101 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004102 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004103 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00004104 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004105 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004106 ressize = size;
4107
4108 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004109 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004110
Benjamin Peterson29060642009-01-31 22:14:21 +00004111 /* can we encode this? */
4112 if (c<limit) {
4113 /* no overflow check, because we know that the space is enough */
4114 *str++ = (char)c;
4115 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004116 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004117 else {
4118 Py_ssize_t unicodepos = p-startp;
4119 Py_ssize_t requiredsize;
4120 PyObject *repunicode;
4121 Py_ssize_t repsize;
4122 Py_ssize_t newpos;
4123 Py_ssize_t respos;
4124 Py_UNICODE *uni2;
4125 /* startpos for collecting unencodable chars */
4126 const Py_UNICODE *collstart = p;
4127 const Py_UNICODE *collend = p;
4128 /* find all unecodable characters */
4129 while ((collend < endp) && ((*collend)>=limit))
4130 ++collend;
4131 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
4132 if (known_errorHandler==-1) {
4133 if ((errors==NULL) || (!strcmp(errors, "strict")))
4134 known_errorHandler = 1;
4135 else if (!strcmp(errors, "replace"))
4136 known_errorHandler = 2;
4137 else if (!strcmp(errors, "ignore"))
4138 known_errorHandler = 3;
4139 else if (!strcmp(errors, "xmlcharrefreplace"))
4140 known_errorHandler = 4;
4141 else
4142 known_errorHandler = 0;
4143 }
4144 switch (known_errorHandler) {
4145 case 1: /* strict */
4146 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
4147 goto onError;
4148 case 2: /* replace */
4149 while (collstart++<collend)
4150 *str++ = '?'; /* fall through */
4151 case 3: /* ignore */
4152 p = collend;
4153 break;
4154 case 4: /* xmlcharrefreplace */
4155 respos = str - PyBytes_AS_STRING(res);
4156 /* determine replacement size (temporarily (mis)uses p) */
4157 for (p = collstart, repsize = 0; p < collend; ++p) {
4158 if (*p<10)
4159 repsize += 2+1+1;
4160 else if (*p<100)
4161 repsize += 2+2+1;
4162 else if (*p<1000)
4163 repsize += 2+3+1;
4164 else if (*p<10000)
4165 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00004166#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004167 else
4168 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00004169#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004170 else if (*p<100000)
4171 repsize += 2+5+1;
4172 else if (*p<1000000)
4173 repsize += 2+6+1;
4174 else
4175 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004176#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004177 }
4178 requiredsize = respos+repsize+(endp-collend);
4179 if (requiredsize > ressize) {
4180 if (requiredsize<2*ressize)
4181 requiredsize = 2*ressize;
4182 if (_PyBytes_Resize(&res, requiredsize))
4183 goto onError;
4184 str = PyBytes_AS_STRING(res) + respos;
4185 ressize = requiredsize;
4186 }
4187 /* generate replacement (temporarily (mis)uses p) */
4188 for (p = collstart; p < collend; ++p) {
4189 str += sprintf(str, "&#%d;", (int)*p);
4190 }
4191 p = collend;
4192 break;
4193 default:
4194 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
4195 encoding, reason, startp, size, &exc,
4196 collstart-startp, collend-startp, &newpos);
4197 if (repunicode == NULL)
4198 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004199 if (PyBytes_Check(repunicode)) {
4200 /* Directly copy bytes result to output. */
4201 repsize = PyBytes_Size(repunicode);
4202 if (repsize > 1) {
4203 /* Make room for all additional bytes. */
4204 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
4205 Py_DECREF(repunicode);
4206 goto onError;
4207 }
4208 ressize += repsize-1;
4209 }
4210 memcpy(str, PyBytes_AsString(repunicode), repsize);
4211 str += repsize;
4212 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004213 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00004214 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004215 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004216 /* need more space? (at least enough for what we
4217 have+the replacement+the rest of the string, so
4218 we won't have to check space for encodable characters) */
4219 respos = str - PyBytes_AS_STRING(res);
4220 repsize = PyUnicode_GET_SIZE(repunicode);
4221 requiredsize = respos+repsize+(endp-collend);
4222 if (requiredsize > ressize) {
4223 if (requiredsize<2*ressize)
4224 requiredsize = 2*ressize;
4225 if (_PyBytes_Resize(&res, requiredsize)) {
4226 Py_DECREF(repunicode);
4227 goto onError;
4228 }
4229 str = PyBytes_AS_STRING(res) + respos;
4230 ressize = requiredsize;
4231 }
4232 /* check if there is anything unencodable in the replacement
4233 and copy it to the output */
4234 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
4235 c = *uni2;
4236 if (c >= limit) {
4237 raise_encode_exception(&exc, encoding, startp, size,
4238 unicodepos, unicodepos+1, reason);
4239 Py_DECREF(repunicode);
4240 goto onError;
4241 }
4242 *str = (char)c;
4243 }
4244 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004245 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00004246 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004247 }
4248 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004249 /* Resize if we allocated to much */
4250 size = str - PyBytes_AS_STRING(res);
4251 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00004252 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004253 if (_PyBytes_Resize(&res, size) < 0)
4254 goto onError;
4255 }
4256
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004257 Py_XDECREF(errorHandler);
4258 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004259 return res;
4260
4261 onError:
4262 Py_XDECREF(res);
4263 Py_XDECREF(errorHandler);
4264 Py_XDECREF(exc);
4265 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004266}
4267
Guido van Rossumd57fd912000-03-10 22:53:23 +00004268PyObject *PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004269 Py_ssize_t size,
4270 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004271{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004272 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004273}
4274
4275PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
4276{
4277 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004278 PyErr_BadArgument();
4279 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004280 }
4281 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004282 PyUnicode_GET_SIZE(unicode),
4283 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004284}
4285
4286/* --- 7-bit ASCII Codec -------------------------------------------------- */
4287
Guido van Rossumd57fd912000-03-10 22:53:23 +00004288PyObject *PyUnicode_DecodeASCII(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004289 Py_ssize_t size,
4290 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004291{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004292 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004293 PyUnicodeObject *v;
4294 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004295 Py_ssize_t startinpos;
4296 Py_ssize_t endinpos;
4297 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004298 const char *e;
4299 PyObject *errorHandler = NULL;
4300 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00004301
Guido van Rossumd57fd912000-03-10 22:53:23 +00004302 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004303 if (size == 1 && *(unsigned char*)s < 128) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004304 Py_UNICODE r = *(unsigned char*)s;
4305 return PyUnicode_FromUnicode(&r, 1);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004306 }
Tim Petersced69f82003-09-16 20:30:58 +00004307
Guido van Rossumd57fd912000-03-10 22:53:23 +00004308 v = _PyUnicode_New(size);
4309 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004310 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004311 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004312 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004313 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004314 e = s + size;
4315 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004316 register unsigned char c = (unsigned char)*s;
4317 if (c < 128) {
4318 *p++ = c;
4319 ++s;
4320 }
4321 else {
4322 startinpos = s-starts;
4323 endinpos = startinpos + 1;
4324 outpos = p - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
4325 if (unicode_decode_call_errorhandler(
4326 errors, &errorHandler,
4327 "ascii", "ordinal not in range(128)",
4328 &starts, &e, &startinpos, &endinpos, &exc, &s,
4329 &v, &outpos, &p))
4330 goto onError;
4331 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004332 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00004333 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00004334 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
4335 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004336 Py_XDECREF(errorHandler);
4337 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004338 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004339
Benjamin Peterson29060642009-01-31 22:14:21 +00004340 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004341 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004342 Py_XDECREF(errorHandler);
4343 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004344 return NULL;
4345}
4346
Guido van Rossumd57fd912000-03-10 22:53:23 +00004347PyObject *PyUnicode_EncodeASCII(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004348 Py_ssize_t size,
4349 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004350{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004351 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004352}
4353
4354PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
4355{
4356 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004357 PyErr_BadArgument();
4358 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004359 }
4360 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004361 PyUnicode_GET_SIZE(unicode),
4362 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004363}
4364
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004365#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004366
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004367/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004368
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00004369#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004370#define NEED_RETRY
4371#endif
4372
4373/* XXX This code is limited to "true" double-byte encodings, as
4374 a) it assumes an incomplete character consists of a single byte, and
4375 b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
Benjamin Peterson29060642009-01-31 22:14:21 +00004376 encodings, see IsDBCSLeadByteEx documentation. */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004377
4378static int is_dbcs_lead_byte(const char *s, int offset)
4379{
4380 const char *curr = s + offset;
4381
4382 if (IsDBCSLeadByte(*curr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004383 const char *prev = CharPrev(s, curr);
4384 return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004385 }
4386 return 0;
4387}
4388
4389/*
4390 * Decode MBCS string into unicode object. If 'final' is set, converts
4391 * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
4392 */
4393static int decode_mbcs(PyUnicodeObject **v,
Benjamin Peterson29060642009-01-31 22:14:21 +00004394 const char *s, /* MBCS string */
4395 int size, /* sizeof MBCS string */
4396 int final)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004397{
4398 Py_UNICODE *p;
4399 Py_ssize_t n = 0;
4400 int usize = 0;
4401
4402 assert(size >= 0);
4403
4404 /* Skip trailing lead-byte unless 'final' is set */
4405 if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
Benjamin Peterson29060642009-01-31 22:14:21 +00004406 --size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004407
4408 /* First get the size of the result */
4409 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004410 usize = MultiByteToWideChar(CP_ACP, 0, s, size, NULL, 0);
4411 if (usize == 0) {
4412 PyErr_SetFromWindowsErrWithFilename(0, NULL);
4413 return -1;
4414 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004415 }
4416
4417 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004418 /* Create unicode object */
4419 *v = _PyUnicode_New(usize);
4420 if (*v == NULL)
4421 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004422 }
4423 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004424 /* Extend unicode object */
4425 n = PyUnicode_GET_SIZE(*v);
4426 if (_PyUnicode_Resize(v, n + usize) < 0)
4427 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004428 }
4429
4430 /* Do the conversion */
4431 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004432 p = PyUnicode_AS_UNICODE(*v) + n;
4433 if (0 == MultiByteToWideChar(CP_ACP, 0, s, size, p, usize)) {
4434 PyErr_SetFromWindowsErrWithFilename(0, NULL);
4435 return -1;
4436 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004437 }
4438
4439 return size;
4440}
4441
4442PyObject *PyUnicode_DecodeMBCSStateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004443 Py_ssize_t size,
4444 const char *errors,
4445 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004446{
4447 PyUnicodeObject *v = NULL;
4448 int done;
4449
4450 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004451 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004452
4453#ifdef NEED_RETRY
4454 retry:
4455 if (size > INT_MAX)
Benjamin Peterson29060642009-01-31 22:14:21 +00004456 done = decode_mbcs(&v, s, INT_MAX, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004457 else
4458#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004459 done = decode_mbcs(&v, s, (int)size, !consumed);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004460
4461 if (done < 0) {
4462 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00004463 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004464 }
4465
4466 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004467 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004468
4469#ifdef NEED_RETRY
4470 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004471 s += done;
4472 size -= done;
4473 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004474 }
4475#endif
4476
4477 return (PyObject *)v;
4478}
4479
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004480PyObject *PyUnicode_DecodeMBCS(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004481 Py_ssize_t size,
4482 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004483{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004484 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
4485}
4486
4487/*
4488 * Convert unicode into string object (MBCS).
4489 * Returns 0 if succeed, -1 otherwise.
4490 */
4491static int encode_mbcs(PyObject **repr,
Benjamin Peterson29060642009-01-31 22:14:21 +00004492 const Py_UNICODE *p, /* unicode */
4493 int size) /* size of unicode */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004494{
4495 int mbcssize = 0;
4496 Py_ssize_t n = 0;
4497
4498 assert(size >= 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004499
4500 /* First get the size of the result */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004501 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004502 mbcssize = WideCharToMultiByte(CP_ACP, 0, p, size, NULL, 0, NULL, NULL);
4503 if (mbcssize == 0) {
4504 PyErr_SetFromWindowsErrWithFilename(0, NULL);
4505 return -1;
4506 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004507 }
4508
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004509 if (*repr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004510 /* Create string object */
4511 *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
4512 if (*repr == NULL)
4513 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004514 }
4515 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004516 /* Extend string object */
4517 n = PyBytes_Size(*repr);
4518 if (_PyBytes_Resize(repr, n + mbcssize) < 0)
4519 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004520 }
4521
4522 /* Do the conversion */
4523 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004524 char *s = PyBytes_AS_STRING(*repr) + n;
4525 if (0 == WideCharToMultiByte(CP_ACP, 0, p, size, s, mbcssize, NULL, NULL)) {
4526 PyErr_SetFromWindowsErrWithFilename(0, NULL);
4527 return -1;
4528 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004529 }
4530
4531 return 0;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004532}
4533
4534PyObject *PyUnicode_EncodeMBCS(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004535 Py_ssize_t size,
4536 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004537{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004538 PyObject *repr = NULL;
4539 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00004540
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004541#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00004542 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004543 if (size > INT_MAX)
Benjamin Peterson29060642009-01-31 22:14:21 +00004544 ret = encode_mbcs(&repr, p, INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004545 else
4546#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004547 ret = encode_mbcs(&repr, p, (int)size);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004548
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004549 if (ret < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004550 Py_XDECREF(repr);
4551 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004552 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004553
4554#ifdef NEED_RETRY
4555 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004556 p += INT_MAX;
4557 size -= INT_MAX;
4558 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004559 }
4560#endif
4561
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004562 return repr;
4563}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004564
Mark Hammond0ccda1e2003-07-01 00:13:27 +00004565PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
4566{
4567 if (!PyUnicode_Check(unicode)) {
4568 PyErr_BadArgument();
4569 return NULL;
4570 }
4571 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004572 PyUnicode_GET_SIZE(unicode),
4573 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00004574}
4575
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004576#undef NEED_RETRY
4577
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004578#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004579
Guido van Rossumd57fd912000-03-10 22:53:23 +00004580/* --- Character Mapping Codec -------------------------------------------- */
4581
Guido van Rossumd57fd912000-03-10 22:53:23 +00004582PyObject *PyUnicode_DecodeCharmap(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004583 Py_ssize_t size,
4584 PyObject *mapping,
4585 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004586{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004587 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004588 Py_ssize_t startinpos;
4589 Py_ssize_t endinpos;
4590 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004591 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004592 PyUnicodeObject *v;
4593 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004594 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004595 PyObject *errorHandler = NULL;
4596 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00004597 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004598 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00004599
Guido van Rossumd57fd912000-03-10 22:53:23 +00004600 /* Default to Latin-1 */
4601 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004602 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004603
4604 v = _PyUnicode_New(size);
4605 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004606 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004607 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004608 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004609 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004610 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00004611 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004612 mapstring = PyUnicode_AS_UNICODE(mapping);
4613 maplen = PyUnicode_GET_SIZE(mapping);
4614 while (s < e) {
4615 unsigned char ch = *s;
4616 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004617
Benjamin Peterson29060642009-01-31 22:14:21 +00004618 if (ch < maplen)
4619 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00004620
Benjamin Peterson29060642009-01-31 22:14:21 +00004621 if (x == 0xfffe) {
4622 /* undefined mapping */
4623 outpos = p-PyUnicode_AS_UNICODE(v);
4624 startinpos = s-starts;
4625 endinpos = startinpos+1;
4626 if (unicode_decode_call_errorhandler(
4627 errors, &errorHandler,
4628 "charmap", "character maps to <undefined>",
4629 &starts, &e, &startinpos, &endinpos, &exc, &s,
4630 &v, &outpos, &p)) {
4631 goto onError;
4632 }
4633 continue;
4634 }
4635 *p++ = x;
4636 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004637 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00004638 }
4639 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004640 while (s < e) {
4641 unsigned char ch = *s;
4642 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00004643
Benjamin Peterson29060642009-01-31 22:14:21 +00004644 /* Get mapping (char ordinal -> integer, Unicode char or None) */
4645 w = PyLong_FromLong((long)ch);
4646 if (w == NULL)
4647 goto onError;
4648 x = PyObject_GetItem(mapping, w);
4649 Py_DECREF(w);
4650 if (x == NULL) {
4651 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
4652 /* No mapping found means: mapping is undefined. */
4653 PyErr_Clear();
4654 x = Py_None;
4655 Py_INCREF(x);
4656 } else
4657 goto onError;
4658 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004659
Benjamin Peterson29060642009-01-31 22:14:21 +00004660 /* Apply mapping */
4661 if (PyLong_Check(x)) {
4662 long value = PyLong_AS_LONG(x);
4663 if (value < 0 || value > 65535) {
4664 PyErr_SetString(PyExc_TypeError,
4665 "character mapping must be in range(65536)");
4666 Py_DECREF(x);
4667 goto onError;
4668 }
4669 *p++ = (Py_UNICODE)value;
4670 }
4671 else if (x == Py_None) {
4672 /* undefined mapping */
4673 outpos = p-PyUnicode_AS_UNICODE(v);
4674 startinpos = s-starts;
4675 endinpos = startinpos+1;
4676 if (unicode_decode_call_errorhandler(
4677 errors, &errorHandler,
4678 "charmap", "character maps to <undefined>",
4679 &starts, &e, &startinpos, &endinpos, &exc, &s,
4680 &v, &outpos, &p)) {
4681 Py_DECREF(x);
4682 goto onError;
4683 }
4684 Py_DECREF(x);
4685 continue;
4686 }
4687 else if (PyUnicode_Check(x)) {
4688 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00004689
Benjamin Peterson29060642009-01-31 22:14:21 +00004690 if (targetsize == 1)
4691 /* 1-1 mapping */
4692 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00004693
Benjamin Peterson29060642009-01-31 22:14:21 +00004694 else if (targetsize > 1) {
4695 /* 1-n mapping */
4696 if (targetsize > extrachars) {
4697 /* resize first */
4698 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
4699 Py_ssize_t needed = (targetsize - extrachars) + \
4700 (targetsize << 2);
4701 extrachars += needed;
4702 /* XXX overflow detection missing */
4703 if (_PyUnicode_Resize(&v,
4704 PyUnicode_GET_SIZE(v) + needed) < 0) {
4705 Py_DECREF(x);
4706 goto onError;
4707 }
4708 p = PyUnicode_AS_UNICODE(v) + oldpos;
4709 }
4710 Py_UNICODE_COPY(p,
4711 PyUnicode_AS_UNICODE(x),
4712 targetsize);
4713 p += targetsize;
4714 extrachars -= targetsize;
4715 }
4716 /* 1-0 mapping: skip the character */
4717 }
4718 else {
4719 /* wrong return value */
4720 PyErr_SetString(PyExc_TypeError,
4721 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00004722 Py_DECREF(x);
4723 goto onError;
4724 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004725 Py_DECREF(x);
4726 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004727 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004728 }
4729 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00004730 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
4731 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004732 Py_XDECREF(errorHandler);
4733 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004734 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004735
Benjamin Peterson29060642009-01-31 22:14:21 +00004736 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004737 Py_XDECREF(errorHandler);
4738 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004739 Py_XDECREF(v);
4740 return NULL;
4741}
4742
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004743/* Charmap encoding: the lookup table */
4744
4745struct encoding_map{
Benjamin Peterson29060642009-01-31 22:14:21 +00004746 PyObject_HEAD
4747 unsigned char level1[32];
4748 int count2, count3;
4749 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004750};
4751
4752static PyObject*
4753encoding_map_size(PyObject *obj, PyObject* args)
4754{
4755 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004756 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00004757 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004758}
4759
4760static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00004761 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00004762 PyDoc_STR("Return the size (in bytes) of this object") },
4763 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004764};
4765
4766static void
4767encoding_map_dealloc(PyObject* o)
4768{
Benjamin Peterson14339b62009-01-31 16:36:08 +00004769 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004770}
4771
4772static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00004773 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004774 "EncodingMap", /*tp_name*/
4775 sizeof(struct encoding_map), /*tp_basicsize*/
4776 0, /*tp_itemsize*/
4777 /* methods */
4778 encoding_map_dealloc, /*tp_dealloc*/
4779 0, /*tp_print*/
4780 0, /*tp_getattr*/
4781 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00004782 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00004783 0, /*tp_repr*/
4784 0, /*tp_as_number*/
4785 0, /*tp_as_sequence*/
4786 0, /*tp_as_mapping*/
4787 0, /*tp_hash*/
4788 0, /*tp_call*/
4789 0, /*tp_str*/
4790 0, /*tp_getattro*/
4791 0, /*tp_setattro*/
4792 0, /*tp_as_buffer*/
4793 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4794 0, /*tp_doc*/
4795 0, /*tp_traverse*/
4796 0, /*tp_clear*/
4797 0, /*tp_richcompare*/
4798 0, /*tp_weaklistoffset*/
4799 0, /*tp_iter*/
4800 0, /*tp_iternext*/
4801 encoding_map_methods, /*tp_methods*/
4802 0, /*tp_members*/
4803 0, /*tp_getset*/
4804 0, /*tp_base*/
4805 0, /*tp_dict*/
4806 0, /*tp_descr_get*/
4807 0, /*tp_descr_set*/
4808 0, /*tp_dictoffset*/
4809 0, /*tp_init*/
4810 0, /*tp_alloc*/
4811 0, /*tp_new*/
4812 0, /*tp_free*/
4813 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004814};
4815
4816PyObject*
4817PyUnicode_BuildEncodingMap(PyObject* string)
4818{
4819 Py_UNICODE *decode;
4820 PyObject *result;
4821 struct encoding_map *mresult;
4822 int i;
4823 int need_dict = 0;
4824 unsigned char level1[32];
4825 unsigned char level2[512];
4826 unsigned char *mlevel1, *mlevel2, *mlevel3;
4827 int count2 = 0, count3 = 0;
4828
4829 if (!PyUnicode_Check(string) || PyUnicode_GetSize(string) != 256) {
4830 PyErr_BadArgument();
4831 return NULL;
4832 }
4833 decode = PyUnicode_AS_UNICODE(string);
4834 memset(level1, 0xFF, sizeof level1);
4835 memset(level2, 0xFF, sizeof level2);
4836
4837 /* If there isn't a one-to-one mapping of NULL to \0,
4838 or if there are non-BMP characters, we need to use
4839 a mapping dictionary. */
4840 if (decode[0] != 0)
4841 need_dict = 1;
4842 for (i = 1; i < 256; i++) {
4843 int l1, l2;
4844 if (decode[i] == 0
Benjamin Peterson29060642009-01-31 22:14:21 +00004845#ifdef Py_UNICODE_WIDE
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004846 || decode[i] > 0xFFFF
Benjamin Peterson29060642009-01-31 22:14:21 +00004847#endif
4848 ) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004849 need_dict = 1;
4850 break;
4851 }
4852 if (decode[i] == 0xFFFE)
4853 /* unmapped character */
4854 continue;
4855 l1 = decode[i] >> 11;
4856 l2 = decode[i] >> 7;
4857 if (level1[l1] == 0xFF)
4858 level1[l1] = count2++;
4859 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00004860 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004861 }
4862
4863 if (count2 >= 0xFF || count3 >= 0xFF)
4864 need_dict = 1;
4865
4866 if (need_dict) {
4867 PyObject *result = PyDict_New();
4868 PyObject *key, *value;
4869 if (!result)
4870 return NULL;
4871 for (i = 0; i < 256; i++) {
4872 key = value = NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00004873 key = PyLong_FromLong(decode[i]);
4874 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004875 if (!key || !value)
4876 goto failed1;
4877 if (PyDict_SetItem(result, key, value) == -1)
4878 goto failed1;
4879 Py_DECREF(key);
4880 Py_DECREF(value);
4881 }
4882 return result;
4883 failed1:
4884 Py_XDECREF(key);
4885 Py_XDECREF(value);
4886 Py_DECREF(result);
4887 return NULL;
4888 }
4889
4890 /* Create a three-level trie */
4891 result = PyObject_MALLOC(sizeof(struct encoding_map) +
4892 16*count2 + 128*count3 - 1);
4893 if (!result)
4894 return PyErr_NoMemory();
4895 PyObject_Init(result, &EncodingMapType);
4896 mresult = (struct encoding_map*)result;
4897 mresult->count2 = count2;
4898 mresult->count3 = count3;
4899 mlevel1 = mresult->level1;
4900 mlevel2 = mresult->level23;
4901 mlevel3 = mresult->level23 + 16*count2;
4902 memcpy(mlevel1, level1, 32);
4903 memset(mlevel2, 0xFF, 16*count2);
4904 memset(mlevel3, 0, 128*count3);
4905 count3 = 0;
4906 for (i = 1; i < 256; i++) {
4907 int o1, o2, o3, i2, i3;
4908 if (decode[i] == 0xFFFE)
4909 /* unmapped character */
4910 continue;
4911 o1 = decode[i]>>11;
4912 o2 = (decode[i]>>7) & 0xF;
4913 i2 = 16*mlevel1[o1] + o2;
4914 if (mlevel2[i2] == 0xFF)
4915 mlevel2[i2] = count3++;
4916 o3 = decode[i] & 0x7F;
4917 i3 = 128*mlevel2[i2] + o3;
4918 mlevel3[i3] = i;
4919 }
4920 return result;
4921}
4922
4923static int
4924encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
4925{
4926 struct encoding_map *map = (struct encoding_map*)mapping;
4927 int l1 = c>>11;
4928 int l2 = (c>>7) & 0xF;
4929 int l3 = c & 0x7F;
4930 int i;
4931
4932#ifdef Py_UNICODE_WIDE
4933 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004934 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004935 }
4936#endif
4937 if (c == 0)
4938 return 0;
4939 /* level 1*/
4940 i = map->level1[l1];
4941 if (i == 0xFF) {
4942 return -1;
4943 }
4944 /* level 2*/
4945 i = map->level23[16*i+l2];
4946 if (i == 0xFF) {
4947 return -1;
4948 }
4949 /* level 3 */
4950 i = map->level23[16*map->count2 + 128*i + l3];
4951 if (i == 0) {
4952 return -1;
4953 }
4954 return i;
4955}
4956
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004957/* Lookup the character ch in the mapping. If the character
4958 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00004959 error occurred). */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004960static PyObject *charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004961{
Christian Heimes217cfd12007-12-02 14:31:20 +00004962 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004963 PyObject *x;
4964
4965 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004966 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004967 x = PyObject_GetItem(mapping, w);
4968 Py_DECREF(w);
4969 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004970 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
4971 /* No mapping found means: mapping is undefined. */
4972 PyErr_Clear();
4973 x = Py_None;
4974 Py_INCREF(x);
4975 return x;
4976 } else
4977 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004978 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00004979 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00004980 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00004981 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004982 long value = PyLong_AS_LONG(x);
4983 if (value < 0 || value > 255) {
4984 PyErr_SetString(PyExc_TypeError,
4985 "character mapping must be in range(256)");
4986 Py_DECREF(x);
4987 return NULL;
4988 }
4989 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004990 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004991 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00004992 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004993 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004994 /* wrong return value */
4995 PyErr_Format(PyExc_TypeError,
4996 "character mapping must return integer, bytes or None, not %.400s",
4997 x->ob_type->tp_name);
4998 Py_DECREF(x);
4999 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005000 }
5001}
5002
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005003static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00005004charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005005{
Benjamin Peterson14339b62009-01-31 16:36:08 +00005006 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
5007 /* exponentially overallocate to minimize reallocations */
5008 if (requiredsize < 2*outsize)
5009 requiredsize = 2*outsize;
5010 if (_PyBytes_Resize(outobj, requiredsize))
5011 return -1;
5012 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005013}
5014
Benjamin Peterson14339b62009-01-31 16:36:08 +00005015typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00005016 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005017}charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005018/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00005019 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005020 space is available. Return a new reference to the object that
5021 was put in the output buffer, or Py_None, if the mapping was undefined
5022 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00005023 reallocation error occurred. The caller must decref the result */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005024static
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005025charmapencode_result charmapencode_output(Py_UNICODE c, PyObject *mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00005026 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005027{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005028 PyObject *rep;
5029 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00005030 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005031
Christian Heimes90aa7642007-12-19 02:45:37 +00005032 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005033 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00005034 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005035 if (res == -1)
5036 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00005037 if (outsize<requiredsize)
5038 if (charmapencode_resize(outobj, outpos, requiredsize))
5039 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00005040 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005041 outstart[(*outpos)++] = (char)res;
5042 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005043 }
5044
5045 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005046 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005047 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005048 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005049 Py_DECREF(rep);
5050 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005051 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005052 if (PyLong_Check(rep)) {
5053 Py_ssize_t requiredsize = *outpos+1;
5054 if (outsize<requiredsize)
5055 if (charmapencode_resize(outobj, outpos, requiredsize)) {
5056 Py_DECREF(rep);
5057 return enc_EXCEPTION;
5058 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005059 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005060 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005061 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005062 else {
5063 const char *repchars = PyBytes_AS_STRING(rep);
5064 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
5065 Py_ssize_t requiredsize = *outpos+repsize;
5066 if (outsize<requiredsize)
5067 if (charmapencode_resize(outobj, outpos, requiredsize)) {
5068 Py_DECREF(rep);
5069 return enc_EXCEPTION;
5070 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005071 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005072 memcpy(outstart + *outpos, repchars, repsize);
5073 *outpos += repsize;
5074 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005075 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005076 Py_DECREF(rep);
5077 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005078}
5079
5080/* handle an error in PyUnicode_EncodeCharmap
5081 Return 0 on success, -1 on error */
5082static
5083int charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00005084 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005085 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00005086 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00005087 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005088{
5089 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005090 Py_ssize_t repsize;
5091 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005092 Py_UNICODE *uni2;
5093 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005094 Py_ssize_t collstartpos = *inpos;
5095 Py_ssize_t collendpos = *inpos+1;
5096 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005097 char *encoding = "charmap";
5098 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005099 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005100
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005101 /* find all unencodable characters */
5102 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005103 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00005104 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005105 int res = encoding_map_lookup(p[collendpos], mapping);
5106 if (res != -1)
5107 break;
5108 ++collendpos;
5109 continue;
5110 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005111
Benjamin Peterson29060642009-01-31 22:14:21 +00005112 rep = charmapencode_lookup(p[collendpos], mapping);
5113 if (rep==NULL)
5114 return -1;
5115 else if (rep!=Py_None) {
5116 Py_DECREF(rep);
5117 break;
5118 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005119 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00005120 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005121 }
5122 /* cache callback name lookup
5123 * (if not done yet, i.e. it's the first error) */
5124 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005125 if ((errors==NULL) || (!strcmp(errors, "strict")))
5126 *known_errorHandler = 1;
5127 else if (!strcmp(errors, "replace"))
5128 *known_errorHandler = 2;
5129 else if (!strcmp(errors, "ignore"))
5130 *known_errorHandler = 3;
5131 else if (!strcmp(errors, "xmlcharrefreplace"))
5132 *known_errorHandler = 4;
5133 else
5134 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005135 }
5136 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005137 case 1: /* strict */
5138 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5139 return -1;
5140 case 2: /* replace */
5141 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005142 x = charmapencode_output('?', mapping, res, respos);
5143 if (x==enc_EXCEPTION) {
5144 return -1;
5145 }
5146 else if (x==enc_FAILED) {
5147 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5148 return -1;
5149 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005150 }
5151 /* fall through */
5152 case 3: /* ignore */
5153 *inpos = collendpos;
5154 break;
5155 case 4: /* xmlcharrefreplace */
5156 /* generate replacement (temporarily (mis)uses p) */
5157 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005158 char buffer[2+29+1+1];
5159 char *cp;
5160 sprintf(buffer, "&#%d;", (int)p[collpos]);
5161 for (cp = buffer; *cp; ++cp) {
5162 x = charmapencode_output(*cp, mapping, res, respos);
5163 if (x==enc_EXCEPTION)
5164 return -1;
5165 else if (x==enc_FAILED) {
5166 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5167 return -1;
5168 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005169 }
5170 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005171 *inpos = collendpos;
5172 break;
5173 default:
5174 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00005175 encoding, reason, p, size, exceptionObject,
5176 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005177 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005178 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005179 if (PyBytes_Check(repunicode)) {
5180 /* Directly copy bytes result to output. */
5181 Py_ssize_t outsize = PyBytes_Size(*res);
5182 Py_ssize_t requiredsize;
5183 repsize = PyBytes_Size(repunicode);
5184 requiredsize = *respos + repsize;
5185 if (requiredsize > outsize)
5186 /* Make room for all additional bytes. */
5187 if (charmapencode_resize(res, respos, requiredsize)) {
5188 Py_DECREF(repunicode);
5189 return -1;
5190 }
5191 memcpy(PyBytes_AsString(*res) + *respos,
5192 PyBytes_AsString(repunicode), repsize);
5193 *respos += repsize;
5194 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005195 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00005196 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005197 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005198 /* generate replacement */
5199 repsize = PyUnicode_GET_SIZE(repunicode);
5200 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005201 x = charmapencode_output(*uni2, mapping, res, respos);
5202 if (x==enc_EXCEPTION) {
5203 return -1;
5204 }
5205 else if (x==enc_FAILED) {
5206 Py_DECREF(repunicode);
5207 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5208 return -1;
5209 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005210 }
5211 *inpos = newpos;
5212 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005213 }
5214 return 0;
5215}
5216
Guido van Rossumd57fd912000-03-10 22:53:23 +00005217PyObject *PyUnicode_EncodeCharmap(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00005218 Py_ssize_t size,
5219 PyObject *mapping,
5220 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005221{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005222 /* output object */
5223 PyObject *res = NULL;
5224 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005225 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005226 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005227 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005228 PyObject *errorHandler = NULL;
5229 PyObject *exc = NULL;
5230 /* the following variable is used for caching string comparisons
5231 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
5232 * 3=ignore, 4=xmlcharrefreplace */
5233 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005234
5235 /* Default to Latin-1 */
5236 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005237 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005238
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005239 /* allocate enough for a simple encoding without
5240 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00005241 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005242 if (res == NULL)
5243 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00005244 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005245 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005246
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005247 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005248 /* try to encode it */
5249 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
5250 if (x==enc_EXCEPTION) /* error */
5251 goto onError;
5252 if (x==enc_FAILED) { /* unencodable character */
5253 if (charmap_encoding_error(p, size, &inpos, mapping,
5254 &exc,
5255 &known_errorHandler, &errorHandler, errors,
5256 &res, &respos)) {
5257 goto onError;
5258 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005259 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005260 else
5261 /* done with this character => adjust input position */
5262 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005263 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005264
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005265 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00005266 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005267 if (_PyBytes_Resize(&res, respos) < 0)
5268 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005269
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005270 Py_XDECREF(exc);
5271 Py_XDECREF(errorHandler);
5272 return res;
5273
Benjamin Peterson29060642009-01-31 22:14:21 +00005274 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005275 Py_XDECREF(res);
5276 Py_XDECREF(exc);
5277 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005278 return NULL;
5279}
5280
5281PyObject *PyUnicode_AsCharmapString(PyObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00005282 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005283{
5284 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005285 PyErr_BadArgument();
5286 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005287 }
5288 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005289 PyUnicode_GET_SIZE(unicode),
5290 mapping,
5291 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005292}
5293
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005294/* create or adjust a UnicodeTranslateError */
5295static void make_translate_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005296 const Py_UNICODE *unicode, Py_ssize_t size,
5297 Py_ssize_t startpos, Py_ssize_t endpos,
5298 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005299{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005300 if (*exceptionObject == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005301 *exceptionObject = PyUnicodeTranslateError_Create(
Benjamin Peterson29060642009-01-31 22:14:21 +00005302 unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005303 }
5304 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005305 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
5306 goto onError;
5307 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
5308 goto onError;
5309 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
5310 goto onError;
5311 return;
5312 onError:
5313 Py_DECREF(*exceptionObject);
5314 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005315 }
5316}
5317
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005318/* raises a UnicodeTranslateError */
5319static void raise_translate_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005320 const Py_UNICODE *unicode, Py_ssize_t size,
5321 Py_ssize_t startpos, Py_ssize_t endpos,
5322 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005323{
5324 make_translate_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005325 unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005326 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005327 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005328}
5329
5330/* error handling callback helper:
5331 build arguments, call the callback and check the arguments,
5332 put the result into newpos and return the replacement string, which
5333 has to be freed by the caller */
5334static PyObject *unicode_translate_call_errorhandler(const char *errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00005335 PyObject **errorHandler,
5336 const char *reason,
5337 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
5338 Py_ssize_t startpos, Py_ssize_t endpos,
5339 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005340{
Benjamin Peterson142957c2008-07-04 19:55:29 +00005341 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005342
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005343 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005344 PyObject *restuple;
5345 PyObject *resunicode;
5346
5347 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005348 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005349 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005350 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005351 }
5352
5353 make_translate_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005354 unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005355 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005356 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005357
5358 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00005359 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005360 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005361 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005362 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00005363 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00005364 Py_DECREF(restuple);
5365 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005366 }
5367 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00005368 &resunicode, &i_newpos)) {
5369 Py_DECREF(restuple);
5370 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005371 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00005372 if (i_newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005373 *newpos = size+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005374 else
5375 *newpos = i_newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005376 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005377 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
5378 Py_DECREF(restuple);
5379 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005380 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005381 Py_INCREF(resunicode);
5382 Py_DECREF(restuple);
5383 return resunicode;
5384}
5385
5386/* Lookup the character ch in the mapping and put the result in result,
5387 which must be decrefed by the caller.
5388 Return 0 on success, -1 on error */
5389static
5390int charmaptranslate_lookup(Py_UNICODE c, PyObject *mapping, PyObject **result)
5391{
Christian Heimes217cfd12007-12-02 14:31:20 +00005392 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005393 PyObject *x;
5394
5395 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005396 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005397 x = PyObject_GetItem(mapping, w);
5398 Py_DECREF(w);
5399 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005400 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5401 /* No mapping found means: use 1:1 mapping. */
5402 PyErr_Clear();
5403 *result = NULL;
5404 return 0;
5405 } else
5406 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005407 }
5408 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005409 *result = x;
5410 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005411 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005412 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005413 long value = PyLong_AS_LONG(x);
5414 long max = PyUnicode_GetMax();
5415 if (value < 0 || value > max) {
5416 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00005417 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00005418 Py_DECREF(x);
5419 return -1;
5420 }
5421 *result = x;
5422 return 0;
5423 }
5424 else if (PyUnicode_Check(x)) {
5425 *result = x;
5426 return 0;
5427 }
5428 else {
5429 /* wrong return value */
5430 PyErr_SetString(PyExc_TypeError,
5431 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00005432 Py_DECREF(x);
5433 return -1;
5434 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005435}
5436/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00005437 if not reallocate and adjust various state variables.
5438 Return 0 on success, -1 on error */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005439static
Walter Dörwald4894c302003-10-24 14:25:28 +00005440int charmaptranslate_makespace(PyObject **outobj, Py_UNICODE **outp,
Benjamin Peterson29060642009-01-31 22:14:21 +00005441 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005442{
Martin v. Löwis18e16552006-02-15 17:27:45 +00005443 Py_ssize_t oldsize = PyUnicode_GET_SIZE(*outobj);
Walter Dörwald4894c302003-10-24 14:25:28 +00005444 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005445 /* remember old output position */
5446 Py_ssize_t outpos = *outp-PyUnicode_AS_UNICODE(*outobj);
5447 /* exponentially overallocate to minimize reallocations */
5448 if (requiredsize < 2 * oldsize)
5449 requiredsize = 2 * oldsize;
5450 if (PyUnicode_Resize(outobj, requiredsize) < 0)
5451 return -1;
5452 *outp = PyUnicode_AS_UNICODE(*outobj) + outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005453 }
5454 return 0;
5455}
5456/* lookup the character, put the result in the output string and adjust
5457 various state variables. Return a new reference to the object that
5458 was put in the output buffer in *result, or Py_None, if the mapping was
5459 undefined (in which case no character was written).
5460 The called must decref result.
5461 Return 0 on success, -1 on error. */
5462static
Walter Dörwald4894c302003-10-24 14:25:28 +00005463int charmaptranslate_output(const Py_UNICODE *startinp, const Py_UNICODE *curinp,
Benjamin Peterson29060642009-01-31 22:14:21 +00005464 Py_ssize_t insize, PyObject *mapping, PyObject **outobj, Py_UNICODE **outp,
5465 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005466{
Walter Dörwald4894c302003-10-24 14:25:28 +00005467 if (charmaptranslate_lookup(*curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00005468 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005469 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005470 /* not found => default to 1:1 mapping */
5471 *(*outp)++ = *curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005472 }
5473 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00005474 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00005475 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005476 /* no overflow check, because we know that the space is enough */
5477 *(*outp)++ = (Py_UNICODE)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005478 }
5479 else if (PyUnicode_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005480 Py_ssize_t repsize = PyUnicode_GET_SIZE(*res);
5481 if (repsize==1) {
5482 /* no overflow check, because we know that the space is enough */
5483 *(*outp)++ = *PyUnicode_AS_UNICODE(*res);
5484 }
5485 else if (repsize!=0) {
5486 /* more than one character */
5487 Py_ssize_t requiredsize = (*outp-PyUnicode_AS_UNICODE(*outobj)) +
5488 (insize - (curinp-startinp)) +
5489 repsize - 1;
5490 if (charmaptranslate_makespace(outobj, outp, requiredsize))
5491 return -1;
5492 memcpy(*outp, PyUnicode_AS_UNICODE(*res), sizeof(Py_UNICODE)*repsize);
5493 *outp += repsize;
5494 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005495 }
5496 else
Benjamin Peterson29060642009-01-31 22:14:21 +00005497 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005498 return 0;
5499}
5500
5501PyObject *PyUnicode_TranslateCharmap(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00005502 Py_ssize_t size,
5503 PyObject *mapping,
5504 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005505{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005506 /* output object */
5507 PyObject *res = NULL;
5508 /* pointers to the beginning and end+1 of input */
5509 const Py_UNICODE *startp = p;
5510 const Py_UNICODE *endp = p + size;
5511 /* pointer into the output */
5512 Py_UNICODE *str;
5513 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005514 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005515 char *reason = "character maps to <undefined>";
5516 PyObject *errorHandler = NULL;
5517 PyObject *exc = NULL;
5518 /* the following variable is used for caching string comparisons
5519 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
5520 * 3=ignore, 4=xmlcharrefreplace */
5521 int known_errorHandler = -1;
5522
Guido van Rossumd57fd912000-03-10 22:53:23 +00005523 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005524 PyErr_BadArgument();
5525 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005526 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005527
5528 /* allocate enough for a simple 1:1 translation without
5529 replacements, if we need more, we'll resize */
5530 res = PyUnicode_FromUnicode(NULL, size);
5531 if (res == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005532 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005533 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005534 return res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005535 str = PyUnicode_AS_UNICODE(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005536
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005537 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005538 /* try to encode it */
5539 PyObject *x = NULL;
5540 if (charmaptranslate_output(startp, p, size, mapping, &res, &str, &x)) {
5541 Py_XDECREF(x);
5542 goto onError;
5543 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005544 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00005545 if (x!=Py_None) /* it worked => adjust input pointer */
5546 ++p;
5547 else { /* untranslatable character */
5548 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
5549 Py_ssize_t repsize;
5550 Py_ssize_t newpos;
5551 Py_UNICODE *uni2;
5552 /* startpos for collecting untranslatable chars */
5553 const Py_UNICODE *collstart = p;
5554 const Py_UNICODE *collend = p+1;
5555 const Py_UNICODE *coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005556
Benjamin Peterson29060642009-01-31 22:14:21 +00005557 /* find all untranslatable characters */
5558 while (collend < endp) {
5559 if (charmaptranslate_lookup(*collend, mapping, &x))
5560 goto onError;
5561 Py_XDECREF(x);
5562 if (x!=Py_None)
5563 break;
5564 ++collend;
5565 }
5566 /* cache callback name lookup
5567 * (if not done yet, i.e. it's the first error) */
5568 if (known_errorHandler==-1) {
5569 if ((errors==NULL) || (!strcmp(errors, "strict")))
5570 known_errorHandler = 1;
5571 else if (!strcmp(errors, "replace"))
5572 known_errorHandler = 2;
5573 else if (!strcmp(errors, "ignore"))
5574 known_errorHandler = 3;
5575 else if (!strcmp(errors, "xmlcharrefreplace"))
5576 known_errorHandler = 4;
5577 else
5578 known_errorHandler = 0;
5579 }
5580 switch (known_errorHandler) {
5581 case 1: /* strict */
5582 raise_translate_exception(&exc, startp, size, collstart-startp, collend-startp, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005583 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005584 case 2: /* replace */
5585 /* No need to check for space, this is a 1:1 replacement */
5586 for (coll = collstart; coll<collend; ++coll)
5587 *str++ = '?';
5588 /* fall through */
5589 case 3: /* ignore */
5590 p = collend;
5591 break;
5592 case 4: /* xmlcharrefreplace */
5593 /* generate replacement (temporarily (mis)uses p) */
5594 for (p = collstart; p < collend; ++p) {
5595 char buffer[2+29+1+1];
5596 char *cp;
5597 sprintf(buffer, "&#%d;", (int)*p);
5598 if (charmaptranslate_makespace(&res, &str,
5599 (str-PyUnicode_AS_UNICODE(res))+strlen(buffer)+(endp-collend)))
5600 goto onError;
5601 for (cp = buffer; *cp; ++cp)
5602 *str++ = *cp;
5603 }
5604 p = collend;
5605 break;
5606 default:
5607 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
5608 reason, startp, size, &exc,
5609 collstart-startp, collend-startp, &newpos);
5610 if (repunicode == NULL)
5611 goto onError;
5612 /* generate replacement */
5613 repsize = PyUnicode_GET_SIZE(repunicode);
5614 if (charmaptranslate_makespace(&res, &str,
5615 (str-PyUnicode_AS_UNICODE(res))+repsize+(endp-collend))) {
5616 Py_DECREF(repunicode);
5617 goto onError;
5618 }
5619 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2)
5620 *str++ = *uni2;
5621 p = startp + newpos;
5622 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005623 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005624 }
5625 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005626 /* Resize if we allocated to much */
5627 respos = str-PyUnicode_AS_UNICODE(res);
Walter Dörwald4894c302003-10-24 14:25:28 +00005628 if (respos<PyUnicode_GET_SIZE(res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005629 if (PyUnicode_Resize(&res, respos) < 0)
5630 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005631 }
5632 Py_XDECREF(exc);
5633 Py_XDECREF(errorHandler);
5634 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005635
Benjamin Peterson29060642009-01-31 22:14:21 +00005636 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005637 Py_XDECREF(res);
5638 Py_XDECREF(exc);
5639 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005640 return NULL;
5641}
5642
5643PyObject *PyUnicode_Translate(PyObject *str,
Benjamin Peterson29060642009-01-31 22:14:21 +00005644 PyObject *mapping,
5645 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005646{
5647 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00005648
Guido van Rossumd57fd912000-03-10 22:53:23 +00005649 str = PyUnicode_FromObject(str);
5650 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005651 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005652 result = PyUnicode_TranslateCharmap(PyUnicode_AS_UNICODE(str),
Benjamin Peterson29060642009-01-31 22:14:21 +00005653 PyUnicode_GET_SIZE(str),
5654 mapping,
5655 errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005656 Py_DECREF(str);
5657 return result;
Tim Petersced69f82003-09-16 20:30:58 +00005658
Benjamin Peterson29060642009-01-31 22:14:21 +00005659 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005660 Py_XDECREF(str);
5661 return NULL;
5662}
Tim Petersced69f82003-09-16 20:30:58 +00005663
Guido van Rossum9e896b32000-04-05 20:11:21 +00005664/* --- Decimal Encoder ---------------------------------------------------- */
5665
5666int PyUnicode_EncodeDecimal(Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005667 Py_ssize_t length,
5668 char *output,
5669 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00005670{
5671 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005672 PyObject *errorHandler = NULL;
5673 PyObject *exc = NULL;
5674 const char *encoding = "decimal";
5675 const char *reason = "invalid decimal Unicode string";
5676 /* the following variable is used for caching string comparisons
5677 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
5678 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00005679
5680 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005681 PyErr_BadArgument();
5682 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00005683 }
5684
5685 p = s;
5686 end = s + length;
5687 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005688 register Py_UNICODE ch = *p;
5689 int decimal;
5690 PyObject *repunicode;
5691 Py_ssize_t repsize;
5692 Py_ssize_t newpos;
5693 Py_UNICODE *uni2;
5694 Py_UNICODE *collstart;
5695 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00005696
Benjamin Peterson29060642009-01-31 22:14:21 +00005697 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005698 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00005699 ++p;
5700 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005701 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005702 decimal = Py_UNICODE_TODECIMAL(ch);
5703 if (decimal >= 0) {
5704 *output++ = '0' + decimal;
5705 ++p;
5706 continue;
5707 }
5708 if (0 < ch && ch < 256) {
5709 *output++ = (char)ch;
5710 ++p;
5711 continue;
5712 }
5713 /* All other characters are considered unencodable */
5714 collstart = p;
5715 collend = p+1;
5716 while (collend < end) {
5717 if ((0 < *collend && *collend < 256) ||
5718 !Py_UNICODE_ISSPACE(*collend) ||
5719 Py_UNICODE_TODECIMAL(*collend))
5720 break;
5721 }
5722 /* cache callback name lookup
5723 * (if not done yet, i.e. it's the first error) */
5724 if (known_errorHandler==-1) {
5725 if ((errors==NULL) || (!strcmp(errors, "strict")))
5726 known_errorHandler = 1;
5727 else if (!strcmp(errors, "replace"))
5728 known_errorHandler = 2;
5729 else if (!strcmp(errors, "ignore"))
5730 known_errorHandler = 3;
5731 else if (!strcmp(errors, "xmlcharrefreplace"))
5732 known_errorHandler = 4;
5733 else
5734 known_errorHandler = 0;
5735 }
5736 switch (known_errorHandler) {
5737 case 1: /* strict */
5738 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
5739 goto onError;
5740 case 2: /* replace */
5741 for (p = collstart; p < collend; ++p)
5742 *output++ = '?';
5743 /* fall through */
5744 case 3: /* ignore */
5745 p = collend;
5746 break;
5747 case 4: /* xmlcharrefreplace */
5748 /* generate replacement (temporarily (mis)uses p) */
5749 for (p = collstart; p < collend; ++p)
5750 output += sprintf(output, "&#%d;", (int)*p);
5751 p = collend;
5752 break;
5753 default:
5754 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
5755 encoding, reason, s, length, &exc,
5756 collstart-s, collend-s, &newpos);
5757 if (repunicode == NULL)
5758 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005759 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00005760 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005761 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
5762 Py_DECREF(repunicode);
5763 goto onError;
5764 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005765 /* generate replacement */
5766 repsize = PyUnicode_GET_SIZE(repunicode);
5767 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
5768 Py_UNICODE ch = *uni2;
5769 if (Py_UNICODE_ISSPACE(ch))
5770 *output++ = ' ';
5771 else {
5772 decimal = Py_UNICODE_TODECIMAL(ch);
5773 if (decimal >= 0)
5774 *output++ = '0' + decimal;
5775 else if (0 < ch && ch < 256)
5776 *output++ = (char)ch;
5777 else {
5778 Py_DECREF(repunicode);
5779 raise_encode_exception(&exc, encoding,
5780 s, length, collstart-s, collend-s, reason);
5781 goto onError;
5782 }
5783 }
5784 }
5785 p = s + newpos;
5786 Py_DECREF(repunicode);
5787 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00005788 }
5789 /* 0-terminate the output string */
5790 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005791 Py_XDECREF(exc);
5792 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00005793 return 0;
5794
Benjamin Peterson29060642009-01-31 22:14:21 +00005795 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005796 Py_XDECREF(exc);
5797 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00005798 return -1;
5799}
5800
Guido van Rossumd57fd912000-03-10 22:53:23 +00005801/* --- Helpers ------------------------------------------------------------ */
5802
Eric Smith8c663262007-08-25 02:26:07 +00005803#include "stringlib/unicodedefs.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00005804#include "stringlib/fastsearch.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00005805#include "stringlib/count.h"
Christian Heimes9cd17752007-11-18 19:35:23 +00005806/* Include _ParseTupleFinds from find.h */
5807#define FROM_UNICODE
Thomas Wouters477c8d52006-05-27 19:21:47 +00005808#include "stringlib/find.h"
5809#include "stringlib/partition.h"
5810
Eric Smith5807c412008-05-11 21:00:57 +00005811#define _Py_InsertThousandsGrouping _PyUnicode_InsertThousandsGrouping
Eric Smitha3b1ac82009-04-03 14:45:06 +00005812#define _Py_InsertThousandsGroupingLocale _PyUnicode_InsertThousandsGroupingLocale
Eric Smith5807c412008-05-11 21:00:57 +00005813#include "stringlib/localeutil.h"
5814
Thomas Wouters477c8d52006-05-27 19:21:47 +00005815/* helper macro to fixup start/end slice values */
5816#define FIX_START_END(obj) \
5817 if (start < 0) \
5818 start += (obj)->length; \
5819 if (start < 0) \
5820 start = 0; \
5821 if (end > (obj)->length) \
5822 end = (obj)->length; \
5823 if (end < 0) \
5824 end += (obj)->length; \
5825 if (end < 0) \
5826 end = 0;
5827
Martin v. Löwis18e16552006-02-15 17:27:45 +00005828Py_ssize_t PyUnicode_Count(PyObject *str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00005829 PyObject *substr,
5830 Py_ssize_t start,
5831 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005832{
Martin v. Löwis18e16552006-02-15 17:27:45 +00005833 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00005834 PyUnicodeObject* str_obj;
5835 PyUnicodeObject* sub_obj;
Tim Petersced69f82003-09-16 20:30:58 +00005836
Thomas Wouters477c8d52006-05-27 19:21:47 +00005837 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
5838 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00005839 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00005840 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
5841 if (!sub_obj) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005842 Py_DECREF(str_obj);
5843 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005844 }
Tim Petersced69f82003-09-16 20:30:58 +00005845
Thomas Wouters477c8d52006-05-27 19:21:47 +00005846 FIX_START_END(str_obj);
Tim Petersced69f82003-09-16 20:30:58 +00005847
Thomas Wouters477c8d52006-05-27 19:21:47 +00005848 result = stringlib_count(
5849 str_obj->str + start, end - start, sub_obj->str, sub_obj->length
5850 );
5851
5852 Py_DECREF(sub_obj);
5853 Py_DECREF(str_obj);
5854
Guido van Rossumd57fd912000-03-10 22:53:23 +00005855 return result;
5856}
5857
Martin v. Löwis18e16552006-02-15 17:27:45 +00005858Py_ssize_t PyUnicode_Find(PyObject *str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00005859 PyObject *sub,
5860 Py_ssize_t start,
5861 Py_ssize_t end,
5862 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005863{
Martin v. Löwis18e16552006-02-15 17:27:45 +00005864 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00005865
Guido van Rossumd57fd912000-03-10 22:53:23 +00005866 str = PyUnicode_FromObject(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00005867 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00005868 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00005869 sub = PyUnicode_FromObject(sub);
5870 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005871 Py_DECREF(str);
5872 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005873 }
Tim Petersced69f82003-09-16 20:30:58 +00005874
Thomas Wouters477c8d52006-05-27 19:21:47 +00005875 if (direction > 0)
5876 result = stringlib_find_slice(
5877 PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
5878 PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
5879 start, end
5880 );
5881 else
5882 result = stringlib_rfind_slice(
5883 PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
5884 PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
5885 start, end
5886 );
5887
Guido van Rossumd57fd912000-03-10 22:53:23 +00005888 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00005889 Py_DECREF(sub);
5890
Guido van Rossumd57fd912000-03-10 22:53:23 +00005891 return result;
5892}
5893
Tim Petersced69f82003-09-16 20:30:58 +00005894static
Guido van Rossumd57fd912000-03-10 22:53:23 +00005895int tailmatch(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00005896 PyUnicodeObject *substring,
5897 Py_ssize_t start,
5898 Py_ssize_t end,
5899 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005900{
Guido van Rossumd57fd912000-03-10 22:53:23 +00005901 if (substring->length == 0)
5902 return 1;
5903
Thomas Wouters477c8d52006-05-27 19:21:47 +00005904 FIX_START_END(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005905
5906 end -= substring->length;
5907 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00005908 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005909
5910 if (direction > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005911 if (Py_UNICODE_MATCH(self, end, substring))
5912 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005913 } else {
5914 if (Py_UNICODE_MATCH(self, start, substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00005915 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005916 }
5917
5918 return 0;
5919}
5920
Martin v. Löwis18e16552006-02-15 17:27:45 +00005921Py_ssize_t PyUnicode_Tailmatch(PyObject *str,
Benjamin Peterson29060642009-01-31 22:14:21 +00005922 PyObject *substr,
5923 Py_ssize_t start,
5924 Py_ssize_t end,
5925 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005926{
Martin v. Löwis18e16552006-02-15 17:27:45 +00005927 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00005928
Guido van Rossumd57fd912000-03-10 22:53:23 +00005929 str = PyUnicode_FromObject(str);
5930 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005931 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005932 substr = PyUnicode_FromObject(substr);
5933 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005934 Py_DECREF(str);
5935 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005936 }
Tim Petersced69f82003-09-16 20:30:58 +00005937
Guido van Rossumd57fd912000-03-10 22:53:23 +00005938 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00005939 (PyUnicodeObject *)substr,
5940 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005941 Py_DECREF(str);
5942 Py_DECREF(substr);
5943 return result;
5944}
5945
Guido van Rossumd57fd912000-03-10 22:53:23 +00005946/* Apply fixfct filter to the Unicode object self and return a
5947 reference to the modified object */
5948
Tim Petersced69f82003-09-16 20:30:58 +00005949static
Guido van Rossumd57fd912000-03-10 22:53:23 +00005950PyObject *fixup(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00005951 int (*fixfct)(PyUnicodeObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00005952{
5953
5954 PyUnicodeObject *u;
5955
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00005956 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005957 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005958 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00005959
5960 Py_UNICODE_COPY(u->str, self->str, self->length);
5961
Tim Peters7a29bd52001-09-12 03:03:31 +00005962 if (!fixfct(u) && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005963 /* fixfct should return TRUE if it modified the buffer. If
5964 FALSE, return a reference to the original buffer instead
5965 (to save space, not time) */
5966 Py_INCREF(self);
5967 Py_DECREF(u);
5968 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005969 }
5970 return (PyObject*) u;
5971}
5972
Tim Petersced69f82003-09-16 20:30:58 +00005973static
Guido van Rossumd57fd912000-03-10 22:53:23 +00005974int fixupper(PyUnicodeObject *self)
5975{
Martin v. Löwis18e16552006-02-15 17:27:45 +00005976 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005977 Py_UNICODE *s = self->str;
5978 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00005979
Guido van Rossumd57fd912000-03-10 22:53:23 +00005980 while (len-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005981 register Py_UNICODE ch;
Tim Petersced69f82003-09-16 20:30:58 +00005982
Benjamin Peterson29060642009-01-31 22:14:21 +00005983 ch = Py_UNICODE_TOUPPER(*s);
5984 if (ch != *s) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005985 status = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005986 *s = ch;
5987 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005988 s++;
5989 }
5990
5991 return status;
5992}
5993
Tim Petersced69f82003-09-16 20:30:58 +00005994static
Guido van Rossumd57fd912000-03-10 22:53:23 +00005995int fixlower(PyUnicodeObject *self)
5996{
Martin v. Löwis18e16552006-02-15 17:27:45 +00005997 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005998 Py_UNICODE *s = self->str;
5999 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006000
Guido van Rossumd57fd912000-03-10 22:53:23 +00006001 while (len-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006002 register Py_UNICODE ch;
Tim Petersced69f82003-09-16 20:30:58 +00006003
Benjamin Peterson29060642009-01-31 22:14:21 +00006004 ch = Py_UNICODE_TOLOWER(*s);
6005 if (ch != *s) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006006 status = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006007 *s = ch;
6008 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006009 s++;
6010 }
6011
6012 return status;
6013}
6014
Tim Petersced69f82003-09-16 20:30:58 +00006015static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006016int fixswapcase(PyUnicodeObject *self)
6017{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006018 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006019 Py_UNICODE *s = self->str;
6020 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006021
Guido van Rossumd57fd912000-03-10 22:53:23 +00006022 while (len-- > 0) {
6023 if (Py_UNICODE_ISUPPER(*s)) {
6024 *s = Py_UNICODE_TOLOWER(*s);
6025 status = 1;
6026 } else if (Py_UNICODE_ISLOWER(*s)) {
6027 *s = Py_UNICODE_TOUPPER(*s);
6028 status = 1;
6029 }
6030 s++;
6031 }
6032
6033 return status;
6034}
6035
Tim Petersced69f82003-09-16 20:30:58 +00006036static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006037int fixcapitalize(PyUnicodeObject *self)
6038{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006039 Py_ssize_t len = self->length;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006040 Py_UNICODE *s = self->str;
6041 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006042
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006043 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006044 return 0;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006045 if (Py_UNICODE_ISLOWER(*s)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006046 *s = Py_UNICODE_TOUPPER(*s);
6047 status = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006048 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006049 s++;
6050 while (--len > 0) {
6051 if (Py_UNICODE_ISUPPER(*s)) {
6052 *s = Py_UNICODE_TOLOWER(*s);
6053 status = 1;
6054 }
6055 s++;
6056 }
6057 return status;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006058}
6059
6060static
6061int fixtitle(PyUnicodeObject *self)
6062{
6063 register Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
6064 register Py_UNICODE *e;
6065 int previous_is_cased;
6066
6067 /* Shortcut for single character strings */
6068 if (PyUnicode_GET_SIZE(self) == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006069 Py_UNICODE ch = Py_UNICODE_TOTITLE(*p);
6070 if (*p != ch) {
6071 *p = ch;
6072 return 1;
6073 }
6074 else
6075 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006076 }
Tim Petersced69f82003-09-16 20:30:58 +00006077
Guido van Rossumd57fd912000-03-10 22:53:23 +00006078 e = p + PyUnicode_GET_SIZE(self);
6079 previous_is_cased = 0;
6080 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006081 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00006082
Benjamin Peterson29060642009-01-31 22:14:21 +00006083 if (previous_is_cased)
6084 *p = Py_UNICODE_TOLOWER(ch);
6085 else
6086 *p = Py_UNICODE_TOTITLE(ch);
Tim Petersced69f82003-09-16 20:30:58 +00006087
Benjamin Peterson29060642009-01-31 22:14:21 +00006088 if (Py_UNICODE_ISLOWER(ch) ||
6089 Py_UNICODE_ISUPPER(ch) ||
6090 Py_UNICODE_ISTITLE(ch))
6091 previous_is_cased = 1;
6092 else
6093 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006094 }
6095 return 1;
6096}
6097
Tim Peters8ce9f162004-08-27 01:49:32 +00006098PyObject *
6099PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006100{
Skip Montanaro6543b452004-09-16 03:28:13 +00006101 const Py_UNICODE blank = ' ';
6102 const Py_UNICODE *sep = &blank;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006103 Py_ssize_t seplen = 1;
Tim Peters05eba1f2004-08-27 21:32:02 +00006104 PyUnicodeObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00006105 Py_UNICODE *res_p; /* pointer to free byte in res's string area */
6106 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006107 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
6108 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00006109 PyObject *item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006110 Py_ssize_t sz, i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006111
Tim Peters05eba1f2004-08-27 21:32:02 +00006112 fseq = PySequence_Fast(seq, "");
6113 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006114 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00006115 }
6116
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006117 /* NOTE: the following code can't call back into Python code,
6118 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00006119 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006120
Tim Peters05eba1f2004-08-27 21:32:02 +00006121 seqlen = PySequence_Fast_GET_SIZE(fseq);
6122 /* If empty sequence, return u"". */
6123 if (seqlen == 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006124 res = _PyUnicode_New(0); /* empty sequence; return u"" */
6125 goto Done;
Tim Peters05eba1f2004-08-27 21:32:02 +00006126 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006127 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00006128 /* If singleton sequence with an exact Unicode, return that. */
6129 if (seqlen == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006130 item = items[0];
6131 if (PyUnicode_CheckExact(item)) {
6132 Py_INCREF(item);
6133 res = (PyUnicodeObject *)item;
6134 goto Done;
6135 }
Tim Peters8ce9f162004-08-27 01:49:32 +00006136 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006137 else {
6138 /* Set up sep and seplen */
6139 if (separator == NULL) {
6140 sep = &blank;
6141 seplen = 1;
Tim Peters05eba1f2004-08-27 21:32:02 +00006142 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006143 else {
6144 if (!PyUnicode_Check(separator)) {
6145 PyErr_Format(PyExc_TypeError,
6146 "separator: expected str instance,"
6147 " %.80s found",
6148 Py_TYPE(separator)->tp_name);
6149 goto onError;
6150 }
6151 sep = PyUnicode_AS_UNICODE(separator);
6152 seplen = PyUnicode_GET_SIZE(separator);
Tim Peters05eba1f2004-08-27 21:32:02 +00006153 }
6154 }
6155
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006156 /* There are at least two things to join, or else we have a subclass
6157 * of str in the sequence.
6158 * Do a pre-pass to figure out the total amount of space we'll
6159 * need (sz), and see whether all argument are strings.
6160 */
6161 sz = 0;
6162 for (i = 0; i < seqlen; i++) {
6163 const Py_ssize_t old_sz = sz;
6164 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00006165 if (!PyUnicode_Check(item)) {
6166 PyErr_Format(PyExc_TypeError,
6167 "sequence item %zd: expected str instance,"
6168 " %.80s found",
6169 i, Py_TYPE(item)->tp_name);
6170 goto onError;
6171 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006172 sz += PyUnicode_GET_SIZE(item);
6173 if (i != 0)
6174 sz += seplen;
6175 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
6176 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00006177 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006178 goto onError;
6179 }
6180 }
Tim Petersced69f82003-09-16 20:30:58 +00006181
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006182 res = _PyUnicode_New(sz);
6183 if (res == NULL)
6184 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00006185
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006186 /* Catenate everything. */
6187 res_p = PyUnicode_AS_UNICODE(res);
6188 for (i = 0; i < seqlen; ++i) {
6189 Py_ssize_t itemlen;
6190 item = items[i];
6191 itemlen = PyUnicode_GET_SIZE(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00006192 /* Copy item, and maybe the separator. */
6193 if (i) {
6194 Py_UNICODE_COPY(res_p, sep, seplen);
6195 res_p += seplen;
6196 }
6197 Py_UNICODE_COPY(res_p, PyUnicode_AS_UNICODE(item), itemlen);
6198 res_p += itemlen;
Tim Peters05eba1f2004-08-27 21:32:02 +00006199 }
Tim Peters8ce9f162004-08-27 01:49:32 +00006200
Benjamin Peterson29060642009-01-31 22:14:21 +00006201 Done:
Tim Peters05eba1f2004-08-27 21:32:02 +00006202 Py_DECREF(fseq);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006203 return (PyObject *)res;
6204
Benjamin Peterson29060642009-01-31 22:14:21 +00006205 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00006206 Py_DECREF(fseq);
Tim Peters8ce9f162004-08-27 01:49:32 +00006207 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006208 return NULL;
6209}
6210
Tim Petersced69f82003-09-16 20:30:58 +00006211static
6212PyUnicodeObject *pad(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006213 Py_ssize_t left,
6214 Py_ssize_t right,
6215 Py_UNICODE fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006216{
6217 PyUnicodeObject *u;
6218
6219 if (left < 0)
6220 left = 0;
6221 if (right < 0)
6222 right = 0;
6223
Tim Peters7a29bd52001-09-12 03:03:31 +00006224 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006225 Py_INCREF(self);
6226 return self;
6227 }
6228
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006229 if (left > PY_SSIZE_T_MAX - self->length ||
6230 right > PY_SSIZE_T_MAX - (left + self->length)) {
6231 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
6232 return NULL;
6233 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006234 u = _PyUnicode_New(left + self->length + right);
6235 if (u) {
6236 if (left)
6237 Py_UNICODE_FILL(u->str, fill, left);
6238 Py_UNICODE_COPY(u->str + left, self->str, self->length);
6239 if (right)
6240 Py_UNICODE_FILL(u->str + left + self->length, fill, right);
6241 }
6242
6243 return u;
6244}
6245
Benjamin Peterson29060642009-01-31 22:14:21 +00006246#define SPLIT_APPEND(data, left, right) \
6247 str = PyUnicode_FromUnicode((data) + (left), (right) - (left)); \
6248 if (!str) \
6249 goto onError; \
6250 if (PyList_Append(list, str)) { \
6251 Py_DECREF(str); \
6252 goto onError; \
6253 } \
6254 else \
6255 Py_DECREF(str);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006256
6257static
6258PyObject *split_whitespace(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006259 PyObject *list,
6260 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006261{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006262 register Py_ssize_t i;
6263 register Py_ssize_t j;
6264 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006265 PyObject *str;
Christian Heimes190d79e2008-01-30 11:58:22 +00006266 register const Py_UNICODE *buf = self->str;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006267
6268 for (i = j = 0; i < len; ) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006269 /* find a token */
Benjamin Peterson14339b62009-01-31 16:36:08 +00006270 while (i < len && Py_UNICODE_ISSPACE(buf[i]))
Benjamin Peterson29060642009-01-31 22:14:21 +00006271 i++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006272 j = i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006273 while (i < len && !Py_UNICODE_ISSPACE(buf[i]))
6274 i++;
6275 if (j < i) {
6276 if (maxcount-- <= 0)
6277 break;
6278 SPLIT_APPEND(buf, j, i);
6279 while (i < len && Py_UNICODE_ISSPACE(buf[i]))
6280 i++;
6281 j = i;
6282 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006283 }
6284 if (j < len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006285 SPLIT_APPEND(buf, j, len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006286 }
6287 return list;
6288
Benjamin Peterson29060642009-01-31 22:14:21 +00006289 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006290 Py_DECREF(list);
6291 return NULL;
6292}
6293
6294PyObject *PyUnicode_Splitlines(PyObject *string,
Benjamin Peterson29060642009-01-31 22:14:21 +00006295 int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006296{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006297 register Py_ssize_t i;
6298 register Py_ssize_t j;
6299 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006300 PyObject *list;
6301 PyObject *str;
6302 Py_UNICODE *data;
6303
6304 string = PyUnicode_FromObject(string);
6305 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006306 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006307 data = PyUnicode_AS_UNICODE(string);
6308 len = PyUnicode_GET_SIZE(string);
6309
Guido van Rossumd57fd912000-03-10 22:53:23 +00006310 list = PyList_New(0);
6311 if (!list)
6312 goto onError;
6313
6314 for (i = j = 0; i < len; ) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006315 Py_ssize_t eol;
Tim Petersced69f82003-09-16 20:30:58 +00006316
Benjamin Peterson29060642009-01-31 22:14:21 +00006317 /* Find a line and append it */
6318 while (i < len && !BLOOM_LINEBREAK(data[i]))
6319 i++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006320
Benjamin Peterson29060642009-01-31 22:14:21 +00006321 /* Skip the line break reading CRLF as one line break */
Benjamin Peterson14339b62009-01-31 16:36:08 +00006322 eol = i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006323 if (i < len) {
6324 if (data[i] == '\r' && i + 1 < len &&
6325 data[i+1] == '\n')
6326 i += 2;
6327 else
6328 i++;
6329 if (keepends)
6330 eol = i;
6331 }
6332 SPLIT_APPEND(data, j, eol);
6333 j = i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006334 }
6335 if (j < len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006336 SPLIT_APPEND(data, j, len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006337 }
6338
6339 Py_DECREF(string);
6340 return list;
6341
Benjamin Peterson29060642009-01-31 22:14:21 +00006342 onError:
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00006343 Py_XDECREF(list);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006344 Py_DECREF(string);
6345 return NULL;
6346}
6347
Tim Petersced69f82003-09-16 20:30:58 +00006348static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006349PyObject *split_char(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006350 PyObject *list,
6351 Py_UNICODE ch,
6352 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006353{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006354 register Py_ssize_t i;
6355 register Py_ssize_t j;
6356 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006357 PyObject *str;
Christian Heimes190d79e2008-01-30 11:58:22 +00006358 register const Py_UNICODE *buf = self->str;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006359
6360 for (i = j = 0; i < len; ) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006361 if (buf[i] == ch) {
6362 if (maxcount-- <= 0)
6363 break;
6364 SPLIT_APPEND(buf, j, i);
6365 i = j = i + 1;
6366 } else
6367 i++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006368 }
6369 if (j <= len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006370 SPLIT_APPEND(buf, j, len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006371 }
6372 return list;
6373
Benjamin Peterson29060642009-01-31 22:14:21 +00006374 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006375 Py_DECREF(list);
6376 return NULL;
6377}
6378
Tim Petersced69f82003-09-16 20:30:58 +00006379static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006380PyObject *split_substring(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006381 PyObject *list,
6382 PyUnicodeObject *substring,
6383 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006384{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006385 register Py_ssize_t i;
6386 register Py_ssize_t j;
6387 Py_ssize_t len = self->length;
6388 Py_ssize_t sublen = substring->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006389 PyObject *str;
6390
Guido van Rossumcda4f9a2000-12-19 02:23:19 +00006391 for (i = j = 0; i <= len - sublen; ) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006392 if (Py_UNICODE_MATCH(self, i, substring)) {
6393 if (maxcount-- <= 0)
6394 break;
6395 SPLIT_APPEND(self->str, j, i);
6396 i = j = i + sublen;
6397 } else
6398 i++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006399 }
6400 if (j <= len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006401 SPLIT_APPEND(self->str, j, len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006402 }
6403 return list;
6404
Benjamin Peterson29060642009-01-31 22:14:21 +00006405 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006406 Py_DECREF(list);
6407 return NULL;
6408}
6409
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006410static
6411PyObject *rsplit_whitespace(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006412 PyObject *list,
6413 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006414{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006415 register Py_ssize_t i;
6416 register Py_ssize_t j;
6417 Py_ssize_t len = self->length;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006418 PyObject *str;
Christian Heimes190d79e2008-01-30 11:58:22 +00006419 register const Py_UNICODE *buf = self->str;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006420
6421 for (i = j = len - 1; i >= 0; ) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006422 /* find a token */
Benjamin Peterson14339b62009-01-31 16:36:08 +00006423 while (i >= 0 && Py_UNICODE_ISSPACE(buf[i]))
Benjamin Peterson29060642009-01-31 22:14:21 +00006424 i--;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006425 j = i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006426 while (i >= 0 && !Py_UNICODE_ISSPACE(buf[i]))
6427 i--;
6428 if (j > i) {
6429 if (maxcount-- <= 0)
6430 break;
6431 SPLIT_APPEND(buf, i + 1, j + 1);
6432 while (i >= 0 && Py_UNICODE_ISSPACE(buf[i]))
6433 i--;
6434 j = i;
6435 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006436 }
6437 if (j >= 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006438 SPLIT_APPEND(buf, 0, j + 1);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006439 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00006440 if (PyList_Reverse(list) < 0)
6441 goto onError;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006442 return list;
6443
Benjamin Peterson29060642009-01-31 22:14:21 +00006444 onError:
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006445 Py_DECREF(list);
6446 return NULL;
6447}
6448
Benjamin Peterson14339b62009-01-31 16:36:08 +00006449static
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006450PyObject *rsplit_char(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006451 PyObject *list,
6452 Py_UNICODE ch,
6453 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006454{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006455 register Py_ssize_t i;
6456 register Py_ssize_t j;
6457 Py_ssize_t len = self->length;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006458 PyObject *str;
Christian Heimes190d79e2008-01-30 11:58:22 +00006459 register const Py_UNICODE *buf = self->str;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006460
6461 for (i = j = len - 1; i >= 0; ) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006462 if (buf[i] == ch) {
6463 if (maxcount-- <= 0)
6464 break;
6465 SPLIT_APPEND(buf, i + 1, j + 1);
6466 j = i = i - 1;
6467 } else
6468 i--;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006469 }
Hye-Shik Chang7fc4cf52003-12-23 09:10:16 +00006470 if (j >= -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006471 SPLIT_APPEND(buf, 0, j + 1);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006472 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00006473 if (PyList_Reverse(list) < 0)
6474 goto onError;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006475 return list;
6476
Benjamin Peterson29060642009-01-31 22:14:21 +00006477 onError:
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006478 Py_DECREF(list);
6479 return NULL;
6480}
6481
Benjamin Peterson14339b62009-01-31 16:36:08 +00006482static
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006483PyObject *rsplit_substring(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006484 PyObject *list,
6485 PyUnicodeObject *substring,
6486 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006487{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006488 register Py_ssize_t i;
6489 register Py_ssize_t j;
6490 Py_ssize_t len = self->length;
6491 Py_ssize_t sublen = substring->length;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006492 PyObject *str;
6493
6494 for (i = len - sublen, j = len; i >= 0; ) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006495 if (Py_UNICODE_MATCH(self, i, substring)) {
6496 if (maxcount-- <= 0)
6497 break;
6498 SPLIT_APPEND(self->str, i + sublen, j);
6499 j = i;
6500 i -= sublen;
6501 } else
6502 i--;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006503 }
6504 if (j >= 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006505 SPLIT_APPEND(self->str, 0, j);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006506 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00006507 if (PyList_Reverse(list) < 0)
6508 goto onError;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006509 return list;
6510
Benjamin Peterson29060642009-01-31 22:14:21 +00006511 onError:
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006512 Py_DECREF(list);
6513 return NULL;
6514}
6515
Guido van Rossumd57fd912000-03-10 22:53:23 +00006516#undef SPLIT_APPEND
6517
6518static
6519PyObject *split(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006520 PyUnicodeObject *substring,
6521 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006522{
6523 PyObject *list;
6524
6525 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006526 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006527
6528 list = PyList_New(0);
6529 if (!list)
6530 return NULL;
6531
6532 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006533 return split_whitespace(self,list,maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006534
6535 else if (substring->length == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00006536 return split_char(self,list,substring->str[0],maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006537
6538 else if (substring->length == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006539 Py_DECREF(list);
6540 PyErr_SetString(PyExc_ValueError, "empty separator");
6541 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006542 }
6543 else
Benjamin Peterson29060642009-01-31 22:14:21 +00006544 return split_substring(self,list,substring,maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006545}
6546
Tim Petersced69f82003-09-16 20:30:58 +00006547static
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006548PyObject *rsplit(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006549 PyUnicodeObject *substring,
6550 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006551{
6552 PyObject *list;
6553
6554 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006555 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006556
6557 list = PyList_New(0);
6558 if (!list)
6559 return NULL;
6560
6561 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006562 return rsplit_whitespace(self,list,maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006563
6564 else if (substring->length == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00006565 return rsplit_char(self,list,substring->str[0],maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006566
6567 else if (substring->length == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006568 Py_DECREF(list);
6569 PyErr_SetString(PyExc_ValueError, "empty separator");
6570 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006571 }
6572 else
Benjamin Peterson29060642009-01-31 22:14:21 +00006573 return rsplit_substring(self,list,substring,maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006574}
6575
6576static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006577PyObject *replace(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006578 PyUnicodeObject *str1,
6579 PyUnicodeObject *str2,
6580 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006581{
6582 PyUnicodeObject *u;
6583
6584 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006585 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006586
Thomas Wouters477c8d52006-05-27 19:21:47 +00006587 if (str1->length == str2->length) {
6588 /* same length */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006589 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006590 if (str1->length == 1) {
6591 /* replace characters */
6592 Py_UNICODE u1, u2;
6593 if (!findchar(self->str, self->length, str1->str[0]))
6594 goto nothing;
6595 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
6596 if (!u)
6597 return NULL;
6598 Py_UNICODE_COPY(u->str, self->str, self->length);
6599 u1 = str1->str[0];
6600 u2 = str2->str[0];
6601 for (i = 0; i < u->length; i++)
6602 if (u->str[i] == u1) {
6603 if (--maxcount < 0)
6604 break;
6605 u->str[i] = u2;
6606 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006607 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006608 i = fastsearch(
6609 self->str, self->length, str1->str, str1->length, FAST_SEARCH
Guido van Rossumd57fd912000-03-10 22:53:23 +00006610 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00006611 if (i < 0)
6612 goto nothing;
6613 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
6614 if (!u)
6615 return NULL;
6616 Py_UNICODE_COPY(u->str, self->str, self->length);
6617 while (i <= self->length - str1->length)
6618 if (Py_UNICODE_MATCH(self, i, str1)) {
6619 if (--maxcount < 0)
6620 break;
6621 Py_UNICODE_COPY(u->str+i, str2->str, str2->length);
6622 i += str1->length;
6623 } else
6624 i++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006625 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006626 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006627
6628 Py_ssize_t n, i, j, e;
6629 Py_ssize_t product, new_size, delta;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006630 Py_UNICODE *p;
6631
6632 /* replace strings */
Thomas Wouters477c8d52006-05-27 19:21:47 +00006633 n = stringlib_count(self->str, self->length, str1->str, str1->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006634 if (n > maxcount)
6635 n = maxcount;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006636 if (n == 0)
6637 goto nothing;
6638 /* new_size = self->length + n * (str2->length - str1->length)); */
6639 delta = (str2->length - str1->length);
6640 if (delta == 0) {
6641 new_size = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006642 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006643 product = n * (str2->length - str1->length);
6644 if ((product / (str2->length - str1->length)) != n) {
6645 PyErr_SetString(PyExc_OverflowError,
6646 "replace string is too long");
6647 return NULL;
6648 }
6649 new_size = self->length + product;
6650 if (new_size < 0) {
6651 PyErr_SetString(PyExc_OverflowError,
6652 "replace string is too long");
6653 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006654 }
6655 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00006656 u = _PyUnicode_New(new_size);
6657 if (!u)
6658 return NULL;
6659 i = 0;
6660 p = u->str;
6661 e = self->length - str1->length;
6662 if (str1->length > 0) {
6663 while (n-- > 0) {
6664 /* look for next match */
6665 j = i;
6666 while (j <= e) {
6667 if (Py_UNICODE_MATCH(self, j, str1))
6668 break;
6669 j++;
6670 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006671 if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006672 if (j > e)
6673 break;
6674 /* copy unchanged part [i:j] */
6675 Py_UNICODE_COPY(p, self->str+i, j-i);
6676 p += j - i;
6677 }
6678 /* copy substitution string */
6679 if (str2->length > 0) {
6680 Py_UNICODE_COPY(p, str2->str, str2->length);
6681 p += str2->length;
6682 }
6683 i = j + str1->length;
6684 }
6685 if (i < self->length)
6686 /* copy tail [i:] */
6687 Py_UNICODE_COPY(p, self->str+i, self->length-i);
6688 } else {
6689 /* interleave */
6690 while (n > 0) {
6691 Py_UNICODE_COPY(p, str2->str, str2->length);
6692 p += str2->length;
6693 if (--n <= 0)
6694 break;
6695 *p++ = self->str[i++];
6696 }
6697 Py_UNICODE_COPY(p, self->str+i, self->length-i);
6698 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006699 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006700 return (PyObject *) u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006701
Benjamin Peterson29060642009-01-31 22:14:21 +00006702 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00006703 /* nothing to replace; return original string (when possible) */
6704 if (PyUnicode_CheckExact(self)) {
6705 Py_INCREF(self);
6706 return (PyObject *) self;
6707 }
6708 return PyUnicode_FromUnicode(self->str, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006709}
6710
6711/* --- Unicode Object Methods --------------------------------------------- */
6712
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006713PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00006714 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00006715\n\
6716Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006717characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00006718
6719static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00006720unicode_title(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006721{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006722 return fixup(self, fixtitle);
6723}
6724
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006725PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00006726 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00006727\n\
6728Return a capitalized version of S, i.e. make the first character\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006729have upper case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00006730
6731static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00006732unicode_capitalize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006733{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006734 return fixup(self, fixcapitalize);
6735}
6736
6737#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006738PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00006739 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00006740\n\
6741Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006742normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00006743
6744static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00006745unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006746{
6747 PyObject *list;
6748 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006749 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006750
Guido van Rossumd57fd912000-03-10 22:53:23 +00006751 /* Split into words */
6752 list = split(self, NULL, -1);
6753 if (!list)
6754 return NULL;
6755
6756 /* Capitalize each word */
6757 for (i = 0; i < PyList_GET_SIZE(list); i++) {
6758 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00006759 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006760 if (item == NULL)
6761 goto onError;
6762 Py_DECREF(PyList_GET_ITEM(list, i));
6763 PyList_SET_ITEM(list, i, item);
6764 }
6765
6766 /* Join the words to form a new string */
6767 item = PyUnicode_Join(NULL, list);
6768
Benjamin Peterson29060642009-01-31 22:14:21 +00006769 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006770 Py_DECREF(list);
6771 return (PyObject *)item;
6772}
6773#endif
6774
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006775/* Argument converter. Coerces to a single unicode character */
6776
6777static int
6778convert_uc(PyObject *obj, void *addr)
6779{
Benjamin Peterson14339b62009-01-31 16:36:08 +00006780 Py_UNICODE *fillcharloc = (Py_UNICODE *)addr;
6781 PyObject *uniobj;
6782 Py_UNICODE *unistr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006783
Benjamin Peterson14339b62009-01-31 16:36:08 +00006784 uniobj = PyUnicode_FromObject(obj);
6785 if (uniobj == NULL) {
6786 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00006787 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +00006788 return 0;
6789 }
6790 if (PyUnicode_GET_SIZE(uniobj) != 1) {
6791 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00006792 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +00006793 Py_DECREF(uniobj);
6794 return 0;
6795 }
6796 unistr = PyUnicode_AS_UNICODE(uniobj);
6797 *fillcharloc = unistr[0];
6798 Py_DECREF(uniobj);
6799 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006800}
6801
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006802PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00006803 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00006804\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00006805Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006806done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +00006807
6808static PyObject *
6809unicode_center(PyUnicodeObject *self, PyObject *args)
6810{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006811 Py_ssize_t marg, left;
6812 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006813 Py_UNICODE fillchar = ' ';
Guido van Rossumd57fd912000-03-10 22:53:23 +00006814
Thomas Woutersde017742006-02-16 19:34:37 +00006815 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00006816 return NULL;
6817
Tim Peters7a29bd52001-09-12 03:03:31 +00006818 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006819 Py_INCREF(self);
6820 return (PyObject*) self;
6821 }
6822
6823 marg = width - self->length;
6824 left = marg / 2 + (marg & width & 1);
6825
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006826 return (PyObject*) pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006827}
6828
Marc-André Lemburge5034372000-08-08 08:04:29 +00006829#if 0
6830
6831/* This code should go into some future Unicode collation support
6832 module. The basic comparison should compare ordinals on a naive
Trent Mick20abf572000-08-12 22:14:34 +00006833 basis (this is what Java does and thus JPython too). */
Marc-André Lemburge5034372000-08-08 08:04:29 +00006834
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006835/* speedy UTF-16 code point order comparison */
6836/* gleaned from: */
6837/* http://www-4.ibm.com/software/developer/library/utf16.html?dwzone=unicode */
6838
Marc-André Lemburge12896e2000-07-07 17:51:08 +00006839static short utf16Fixup[32] =
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006840{
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006841 0, 0, 0, 0, 0, 0, 0, 0,
Tim Petersced69f82003-09-16 20:30:58 +00006842 0, 0, 0, 0, 0, 0, 0, 0,
6843 0, 0, 0, 0, 0, 0, 0, 0,
Marc-André Lemburge12896e2000-07-07 17:51:08 +00006844 0, 0, 0, 0x2000, -0x800, -0x800, -0x800, -0x800
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006845};
6846
Guido van Rossumd57fd912000-03-10 22:53:23 +00006847static int
6848unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
6849{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006850 Py_ssize_t len1, len2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006851
Guido van Rossumd57fd912000-03-10 22:53:23 +00006852 Py_UNICODE *s1 = str1->str;
6853 Py_UNICODE *s2 = str2->str;
6854
6855 len1 = str1->length;
6856 len2 = str2->length;
Tim Petersced69f82003-09-16 20:30:58 +00006857
Guido van Rossumd57fd912000-03-10 22:53:23 +00006858 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00006859 Py_UNICODE c1, c2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006860
6861 c1 = *s1++;
6862 c2 = *s2++;
Fredrik Lundh45714e92001-06-26 16:39:36 +00006863
Benjamin Peterson29060642009-01-31 22:14:21 +00006864 if (c1 > (1<<11) * 26)
6865 c1 += utf16Fixup[c1>>11];
6866 if (c2 > (1<<11) * 26)
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006867 c2 += utf16Fixup[c2>>11];
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006868 /* now c1 and c2 are in UTF-32-compatible order */
Fredrik Lundh45714e92001-06-26 16:39:36 +00006869
6870 if (c1 != c2)
6871 return (c1 < c2) ? -1 : 1;
Tim Petersced69f82003-09-16 20:30:58 +00006872
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006873 len1--; len2--;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006874 }
6875
6876 return (len1 < len2) ? -1 : (len1 != len2);
6877}
6878
Marc-André Lemburge5034372000-08-08 08:04:29 +00006879#else
6880
6881static int
6882unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
6883{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006884 register Py_ssize_t len1, len2;
Marc-André Lemburge5034372000-08-08 08:04:29 +00006885
6886 Py_UNICODE *s1 = str1->str;
6887 Py_UNICODE *s2 = str2->str;
6888
6889 len1 = str1->length;
6890 len2 = str2->length;
Tim Petersced69f82003-09-16 20:30:58 +00006891
Marc-André Lemburge5034372000-08-08 08:04:29 +00006892 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00006893 Py_UNICODE c1, c2;
Marc-André Lemburge5034372000-08-08 08:04:29 +00006894
Fredrik Lundh45714e92001-06-26 16:39:36 +00006895 c1 = *s1++;
6896 c2 = *s2++;
6897
6898 if (c1 != c2)
6899 return (c1 < c2) ? -1 : 1;
6900
Marc-André Lemburge5034372000-08-08 08:04:29 +00006901 len1--; len2--;
6902 }
6903
6904 return (len1 < len2) ? -1 : (len1 != len2);
6905}
6906
6907#endif
6908
Guido van Rossumd57fd912000-03-10 22:53:23 +00006909int PyUnicode_Compare(PyObject *left,
Benjamin Peterson29060642009-01-31 22:14:21 +00006910 PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006911{
Guido van Rossum09dc34f2007-05-04 04:17:33 +00006912 if (PyUnicode_Check(left) && PyUnicode_Check(right))
6913 return unicode_compare((PyUnicodeObject *)left,
6914 (PyUnicodeObject *)right);
Guido van Rossum09dc34f2007-05-04 04:17:33 +00006915 PyErr_Format(PyExc_TypeError,
6916 "Can't compare %.100s and %.100s",
6917 left->ob_type->tp_name,
6918 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006919 return -1;
6920}
6921
Martin v. Löwis5b222132007-06-10 09:51:05 +00006922int
6923PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
6924{
6925 int i;
6926 Py_UNICODE *id;
6927 assert(PyUnicode_Check(uni));
6928 id = PyUnicode_AS_UNICODE(uni);
6929 /* Compare Unicode string and source character set string */
6930 for (i = 0; id[i] && str[i]; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00006931 if (id[i] != str[i])
6932 return ((int)id[i] < (int)str[i]) ? -1 : 1;
Martin v. Löwis5b222132007-06-10 09:51:05 +00006933 if (id[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00006934 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00006935 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00006936 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00006937 return 0;
6938}
6939
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00006940
Benjamin Peterson29060642009-01-31 22:14:21 +00006941#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +00006942 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00006943
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00006944PyObject *PyUnicode_RichCompare(PyObject *left,
6945 PyObject *right,
6946 int op)
6947{
6948 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006949
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00006950 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
6951 PyObject *v;
6952 if (((PyUnicodeObject *) left)->length !=
6953 ((PyUnicodeObject *) right)->length) {
6954 if (op == Py_EQ) {
6955 Py_INCREF(Py_False);
6956 return Py_False;
6957 }
6958 if (op == Py_NE) {
6959 Py_INCREF(Py_True);
6960 return Py_True;
6961 }
6962 }
6963 if (left == right)
6964 result = 0;
6965 else
6966 result = unicode_compare((PyUnicodeObject *)left,
6967 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006968
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00006969 /* Convert the return value to a Boolean */
6970 switch (op) {
6971 case Py_EQ:
6972 v = TEST_COND(result == 0);
6973 break;
6974 case Py_NE:
6975 v = TEST_COND(result != 0);
6976 break;
6977 case Py_LE:
6978 v = TEST_COND(result <= 0);
6979 break;
6980 case Py_GE:
6981 v = TEST_COND(result >= 0);
6982 break;
6983 case Py_LT:
6984 v = TEST_COND(result == -1);
6985 break;
6986 case Py_GT:
6987 v = TEST_COND(result == 1);
6988 break;
6989 default:
6990 PyErr_BadArgument();
6991 return NULL;
6992 }
6993 Py_INCREF(v);
6994 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00006995 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006996
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00006997 Py_INCREF(Py_NotImplemented);
6998 return Py_NotImplemented;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00006999}
7000
Guido van Rossum403d68b2000-03-13 15:55:09 +00007001int PyUnicode_Contains(PyObject *container,
Benjamin Peterson29060642009-01-31 22:14:21 +00007002 PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +00007003{
Thomas Wouters477c8d52006-05-27 19:21:47 +00007004 PyObject *str, *sub;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007005 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007006
7007 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +00007008 sub = PyUnicode_FromObject(element);
7009 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007010 PyErr_Format(PyExc_TypeError,
7011 "'in <string>' requires string as left operand, not %s",
7012 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007013 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007014 }
7015
Thomas Wouters477c8d52006-05-27 19:21:47 +00007016 str = PyUnicode_FromObject(container);
7017 if (!str) {
7018 Py_DECREF(sub);
7019 return -1;
7020 }
7021
7022 result = stringlib_contains_obj(str, sub);
7023
7024 Py_DECREF(str);
7025 Py_DECREF(sub);
7026
Guido van Rossum403d68b2000-03-13 15:55:09 +00007027 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007028}
7029
Guido van Rossumd57fd912000-03-10 22:53:23 +00007030/* Concat to string or Unicode object giving a new Unicode object. */
7031
7032PyObject *PyUnicode_Concat(PyObject *left,
Benjamin Peterson29060642009-01-31 22:14:21 +00007033 PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007034{
7035 PyUnicodeObject *u = NULL, *v = NULL, *w;
7036
7037 /* Coerce the two arguments */
7038 u = (PyUnicodeObject *)PyUnicode_FromObject(left);
7039 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007040 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007041 v = (PyUnicodeObject *)PyUnicode_FromObject(right);
7042 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007043 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007044
7045 /* Shortcuts */
7046 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007047 Py_DECREF(v);
7048 return (PyObject *)u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007049 }
7050 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007051 Py_DECREF(u);
7052 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007053 }
7054
7055 /* Concat the two Unicode strings */
7056 w = _PyUnicode_New(u->length + v->length);
7057 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007058 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007059 Py_UNICODE_COPY(w->str, u->str, u->length);
7060 Py_UNICODE_COPY(w->str + u->length, v->str, v->length);
7061
7062 Py_DECREF(u);
7063 Py_DECREF(v);
7064 return (PyObject *)w;
7065
Benjamin Peterson29060642009-01-31 22:14:21 +00007066 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007067 Py_XDECREF(u);
7068 Py_XDECREF(v);
7069 return NULL;
7070}
7071
Walter Dörwald1ab83302007-05-18 17:15:44 +00007072void
7073PyUnicode_Append(PyObject **pleft, PyObject *right)
7074{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007075 PyObject *new;
7076 if (*pleft == NULL)
7077 return;
7078 if (right == NULL || !PyUnicode_Check(*pleft)) {
7079 Py_DECREF(*pleft);
7080 *pleft = NULL;
7081 return;
7082 }
7083 new = PyUnicode_Concat(*pleft, right);
7084 Py_DECREF(*pleft);
7085 *pleft = new;
Walter Dörwald1ab83302007-05-18 17:15:44 +00007086}
7087
7088void
7089PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
7090{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007091 PyUnicode_Append(pleft, right);
7092 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +00007093}
7094
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007095PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007096 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007097\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00007098Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007099string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007100interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007101
7102static PyObject *
7103unicode_count(PyUnicodeObject *self, PyObject *args)
7104{
7105 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007106 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007107 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007108 PyObject *result;
7109
Guido van Rossumb8872e62000-05-09 14:14:27 +00007110 if (!PyArg_ParseTuple(args, "O|O&O&:count", &substring,
Benjamin Peterson29060642009-01-31 22:14:21 +00007111 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007112 return NULL;
7113
7114 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Thomas Wouters477c8d52006-05-27 19:21:47 +00007115 (PyObject *)substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007116 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007117 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007118
Thomas Wouters477c8d52006-05-27 19:21:47 +00007119 FIX_START_END(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007120
Christian Heimes217cfd12007-12-02 14:31:20 +00007121 result = PyLong_FromSsize_t(
Thomas Wouters477c8d52006-05-27 19:21:47 +00007122 stringlib_count(self->str + start, end - start,
7123 substring->str, substring->length)
7124 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007125
7126 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007127
Guido van Rossumd57fd912000-03-10 22:53:23 +00007128 return result;
7129}
7130
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007131PyDoc_STRVAR(encode__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007132 "S.encode([encoding[, errors]]) -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007133\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00007134Encode S using the codec registered for encoding. encoding defaults\n\
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007135to the default encoding. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +00007136handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007137a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
7138'xmlcharrefreplace' as well as any other name registered with\n\
7139codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007140
7141static PyObject *
7142unicode_encode(PyUnicodeObject *self, PyObject *args)
7143{
7144 char *encoding = NULL;
7145 char *errors = NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007146 PyObject *v;
Guido van Rossum35d94282007-08-27 18:20:11 +00007147
Guido van Rossumd57fd912000-03-10 22:53:23 +00007148 if (!PyArg_ParseTuple(args, "|ss:encode", &encoding, &errors))
7149 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00007150 v = PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00007151 if (v == NULL)
7152 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00007153 if (!PyBytes_Check(v)) {
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007154 PyErr_Format(PyExc_TypeError,
Guido van Rossumf15a29f2007-05-04 00:41:39 +00007155 "encoder did not return a bytes object "
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007156 "(type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00007157 Py_TYPE(v)->tp_name);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007158 Py_DECREF(v);
7159 return NULL;
7160 }
7161 return v;
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00007162
Benjamin Peterson29060642009-01-31 22:14:21 +00007163 onError:
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00007164 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007165}
7166
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007167PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007168 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007169\n\
7170Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007171If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007172
7173static PyObject*
7174unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
7175{
7176 Py_UNICODE *e;
7177 Py_UNICODE *p;
7178 Py_UNICODE *q;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007179 Py_UNICODE *qe;
7180 Py_ssize_t i, j, incr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007181 PyUnicodeObject *u;
7182 int tabsize = 8;
7183
7184 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00007185 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007186
Thomas Wouters7e474022000-07-16 12:04:32 +00007187 /* First pass: determine size of output string */
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007188 i = 0; /* chars up to and including most recent \n or \r */
7189 j = 0; /* chars since most recent \n or \r (use in tab calculations) */
7190 e = self->str + self->length; /* end of input */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007191 for (p = self->str; p < e; p++)
7192 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007193 if (tabsize > 0) {
7194 incr = tabsize - (j % tabsize); /* cannot overflow */
7195 if (j > PY_SSIZE_T_MAX - incr)
7196 goto overflow1;
7197 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007198 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007199 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007200 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007201 if (j > PY_SSIZE_T_MAX - 1)
7202 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007203 j++;
7204 if (*p == '\n' || *p == '\r') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007205 if (i > PY_SSIZE_T_MAX - j)
7206 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007207 i += j;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007208 j = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007209 }
7210 }
7211
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007212 if (i > PY_SSIZE_T_MAX - j)
Benjamin Peterson29060642009-01-31 22:14:21 +00007213 goto overflow1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007214
Guido van Rossumd57fd912000-03-10 22:53:23 +00007215 /* Second pass: create output string and fill it */
7216 u = _PyUnicode_New(i + j);
7217 if (!u)
7218 return NULL;
7219
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007220 j = 0; /* same as in first pass */
7221 q = u->str; /* next output char */
7222 qe = u->str + u->length; /* end of output */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007223
7224 for (p = self->str; p < e; p++)
7225 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007226 if (tabsize > 0) {
7227 i = tabsize - (j % tabsize);
7228 j += i;
7229 while (i--) {
7230 if (q >= qe)
7231 goto overflow2;
7232 *q++ = ' ';
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007233 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007234 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007235 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007236 else {
7237 if (q >= qe)
7238 goto overflow2;
7239 *q++ = *p;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007240 j++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007241 if (*p == '\n' || *p == '\r')
7242 j = 0;
7243 }
7244
7245 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007246
7247 overflow2:
7248 Py_DECREF(u);
7249 overflow1:
7250 PyErr_SetString(PyExc_OverflowError, "new string is too long");
7251 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007252}
7253
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007254PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007255 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007256\n\
7257Return the lowest index in S where substring sub is found,\n\
Guido van Rossum806c2462007-08-06 23:33:07 +00007258such that sub is contained within s[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007259arguments start and end are interpreted as in slice notation.\n\
7260\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007261Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007262
7263static PyObject *
7264unicode_find(PyUnicodeObject *self, PyObject *args)
7265{
Thomas Wouters477c8d52006-05-27 19:21:47 +00007266 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00007267 Py_ssize_t start;
7268 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007269 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007270
Christian Heimes9cd17752007-11-18 19:35:23 +00007271 if (!_ParseTupleFinds(args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007272 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007273
Thomas Wouters477c8d52006-05-27 19:21:47 +00007274 result = stringlib_find_slice(
7275 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
7276 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
7277 start, end
7278 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007279
7280 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007281
Christian Heimes217cfd12007-12-02 14:31:20 +00007282 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007283}
7284
7285static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00007286unicode_getitem(PyUnicodeObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007287{
7288 if (index < 0 || index >= self->length) {
7289 PyErr_SetString(PyExc_IndexError, "string index out of range");
7290 return NULL;
7291 }
7292
7293 return (PyObject*) PyUnicode_FromUnicode(&self->str[index], 1);
7294}
7295
Guido van Rossumc2504932007-09-18 19:42:40 +00007296/* Believe it or not, this produces the same value for ASCII strings
7297 as string_hash(). */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007298static long
Neil Schemenauerf8c37d12007-09-07 20:49:04 +00007299unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007300{
Guido van Rossumc2504932007-09-18 19:42:40 +00007301 Py_ssize_t len;
7302 Py_UNICODE *p;
7303 long x;
7304
7305 if (self->hash != -1)
7306 return self->hash;
Christian Heimes90aa7642007-12-19 02:45:37 +00007307 len = Py_SIZE(self);
Guido van Rossumc2504932007-09-18 19:42:40 +00007308 p = self->str;
7309 x = *p << 7;
7310 while (--len >= 0)
7311 x = (1000003*x) ^ *p++;
Christian Heimes90aa7642007-12-19 02:45:37 +00007312 x ^= Py_SIZE(self);
Guido van Rossumc2504932007-09-18 19:42:40 +00007313 if (x == -1)
7314 x = -2;
7315 self->hash = x;
7316 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007317}
7318
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007319PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007320 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007321\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007322Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007323
7324static PyObject *
7325unicode_index(PyUnicodeObject *self, PyObject *args)
7326{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007327 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007328 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00007329 Py_ssize_t start;
7330 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007331
Christian Heimes9cd17752007-11-18 19:35:23 +00007332 if (!_ParseTupleFinds(args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007333 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007334
Thomas Wouters477c8d52006-05-27 19:21:47 +00007335 result = stringlib_find_slice(
7336 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
7337 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
7338 start, end
7339 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007340
7341 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007342
Guido van Rossumd57fd912000-03-10 22:53:23 +00007343 if (result < 0) {
7344 PyErr_SetString(PyExc_ValueError, "substring not found");
7345 return NULL;
7346 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00007347
Christian Heimes217cfd12007-12-02 14:31:20 +00007348 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007349}
7350
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007351PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007352 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007353\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007354Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007355at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007356
7357static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007358unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007359{
7360 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7361 register const Py_UNICODE *e;
7362 int cased;
7363
Guido van Rossumd57fd912000-03-10 22:53:23 +00007364 /* Shortcut for single character strings */
7365 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007366 return PyBool_FromLong(Py_UNICODE_ISLOWER(*p));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007367
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007368 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007369 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007370 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007371
Guido van Rossumd57fd912000-03-10 22:53:23 +00007372 e = p + PyUnicode_GET_SIZE(self);
7373 cased = 0;
7374 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007375 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007376
Benjamin Peterson29060642009-01-31 22:14:21 +00007377 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
7378 return PyBool_FromLong(0);
7379 else if (!cased && Py_UNICODE_ISLOWER(ch))
7380 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007381 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007382 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007383}
7384
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007385PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007386 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007387\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007388Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007389at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007390
7391static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007392unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007393{
7394 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7395 register const Py_UNICODE *e;
7396 int cased;
7397
Guido van Rossumd57fd912000-03-10 22:53:23 +00007398 /* Shortcut for single character strings */
7399 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007400 return PyBool_FromLong(Py_UNICODE_ISUPPER(*p) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007401
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007402 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007403 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007404 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007405
Guido van Rossumd57fd912000-03-10 22:53:23 +00007406 e = p + PyUnicode_GET_SIZE(self);
7407 cased = 0;
7408 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007409 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007410
Benjamin Peterson29060642009-01-31 22:14:21 +00007411 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
7412 return PyBool_FromLong(0);
7413 else if (!cased && Py_UNICODE_ISUPPER(ch))
7414 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007415 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007416 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007417}
7418
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007419PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007420 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007421\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007422Return True if S is a titlecased string and there is at least one\n\
7423character in S, i.e. upper- and titlecase characters may only\n\
7424follow uncased characters and lowercase characters only cased ones.\n\
7425Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007426
7427static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007428unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007429{
7430 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7431 register const Py_UNICODE *e;
7432 int cased, previous_is_cased;
7433
Guido van Rossumd57fd912000-03-10 22:53:23 +00007434 /* Shortcut for single character strings */
7435 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007436 return PyBool_FromLong((Py_UNICODE_ISTITLE(*p) != 0) ||
7437 (Py_UNICODE_ISUPPER(*p) != 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007438
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007439 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007440 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007441 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007442
Guido van Rossumd57fd912000-03-10 22:53:23 +00007443 e = p + PyUnicode_GET_SIZE(self);
7444 cased = 0;
7445 previous_is_cased = 0;
7446 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007447 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007448
Benjamin Peterson29060642009-01-31 22:14:21 +00007449 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
7450 if (previous_is_cased)
7451 return PyBool_FromLong(0);
7452 previous_is_cased = 1;
7453 cased = 1;
7454 }
7455 else if (Py_UNICODE_ISLOWER(ch)) {
7456 if (!previous_is_cased)
7457 return PyBool_FromLong(0);
7458 previous_is_cased = 1;
7459 cased = 1;
7460 }
7461 else
7462 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007463 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007464 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007465}
7466
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007467PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007468 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007469\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007470Return True if all characters in S are whitespace\n\
7471and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007472
7473static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007474unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007475{
7476 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7477 register const Py_UNICODE *e;
7478
Guido van Rossumd57fd912000-03-10 22:53:23 +00007479 /* Shortcut for single character strings */
7480 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007481 Py_UNICODE_ISSPACE(*p))
7482 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007483
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007484 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007485 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007486 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007487
Guido van Rossumd57fd912000-03-10 22:53:23 +00007488 e = p + PyUnicode_GET_SIZE(self);
7489 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007490 if (!Py_UNICODE_ISSPACE(*p))
7491 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007492 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007493 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007494}
7495
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007496PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007497 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007498\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007499Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007500and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007501
7502static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007503unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007504{
7505 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7506 register const Py_UNICODE *e;
7507
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007508 /* Shortcut for single character strings */
7509 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007510 Py_UNICODE_ISALPHA(*p))
7511 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007512
7513 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007514 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007515 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007516
7517 e = p + PyUnicode_GET_SIZE(self);
7518 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007519 if (!Py_UNICODE_ISALPHA(*p))
7520 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007521 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007522 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007523}
7524
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007525PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007526 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007527\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007528Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007529and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007530
7531static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007532unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007533{
7534 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7535 register const Py_UNICODE *e;
7536
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007537 /* Shortcut for single character strings */
7538 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007539 Py_UNICODE_ISALNUM(*p))
7540 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007541
7542 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007543 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007544 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007545
7546 e = p + PyUnicode_GET_SIZE(self);
7547 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007548 if (!Py_UNICODE_ISALNUM(*p))
7549 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007550 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007551 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007552}
7553
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007554PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007555 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007556\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007557Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007558False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007559
7560static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007561unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007562{
7563 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7564 register const Py_UNICODE *e;
7565
Guido van Rossumd57fd912000-03-10 22:53:23 +00007566 /* Shortcut for single character strings */
7567 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007568 Py_UNICODE_ISDECIMAL(*p))
7569 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007570
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007571 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007572 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007573 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007574
Guido van Rossumd57fd912000-03-10 22:53:23 +00007575 e = p + PyUnicode_GET_SIZE(self);
7576 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007577 if (!Py_UNICODE_ISDECIMAL(*p))
7578 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007579 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007580 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007581}
7582
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007583PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007584 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007585\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007586Return True if all characters in S are digits\n\
7587and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007588
7589static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007590unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007591{
7592 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7593 register const Py_UNICODE *e;
7594
Guido van Rossumd57fd912000-03-10 22:53:23 +00007595 /* Shortcut for single character strings */
7596 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007597 Py_UNICODE_ISDIGIT(*p))
7598 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007599
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007600 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007601 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007602 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007603
Guido van Rossumd57fd912000-03-10 22:53:23 +00007604 e = p + PyUnicode_GET_SIZE(self);
7605 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007606 if (!Py_UNICODE_ISDIGIT(*p))
7607 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007608 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007609 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007610}
7611
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007612PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007613 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007614\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007615Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007616False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007617
7618static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007619unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007620{
7621 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7622 register const Py_UNICODE *e;
7623
Guido van Rossumd57fd912000-03-10 22:53:23 +00007624 /* Shortcut for single character strings */
7625 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007626 Py_UNICODE_ISNUMERIC(*p))
7627 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007628
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007629 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007630 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007631 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007632
Guido van Rossumd57fd912000-03-10 22:53:23 +00007633 e = p + PyUnicode_GET_SIZE(self);
7634 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007635 if (!Py_UNICODE_ISNUMERIC(*p))
7636 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007637 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007638 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007639}
7640
Martin v. Löwis47383402007-08-15 07:32:56 +00007641int
7642PyUnicode_IsIdentifier(PyObject *self)
7643{
7644 register const Py_UNICODE *p = PyUnicode_AS_UNICODE((PyUnicodeObject*)self);
7645 register const Py_UNICODE *e;
7646
7647 /* Special case for empty strings */
7648 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007649 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +00007650
7651 /* PEP 3131 says that the first character must be in
7652 XID_Start and subsequent characters in XID_Continue,
7653 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +00007654 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +00007655 letters, digits, underscore). However, given the current
7656 definition of XID_Start and XID_Continue, it is sufficient
7657 to check just for these, except that _ must be allowed
7658 as starting an identifier. */
7659 if (!_PyUnicode_IsXidStart(*p) && *p != 0x5F /* LOW LINE */)
7660 return 0;
7661
7662 e = p + PyUnicode_GET_SIZE(self);
7663 for (p++; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007664 if (!_PyUnicode_IsXidContinue(*p))
7665 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +00007666 }
7667 return 1;
7668}
7669
7670PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007671 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +00007672\n\
7673Return True if S is a valid identifier according\n\
7674to the language definition.");
7675
7676static PyObject*
7677unicode_isidentifier(PyObject *self)
7678{
7679 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
7680}
7681
Georg Brandl559e5d72008-06-11 18:37:52 +00007682PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007683 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +00007684\n\
7685Return True if all characters in S are considered\n\
7686printable in repr() or S is empty, False otherwise.");
7687
7688static PyObject*
7689unicode_isprintable(PyObject *self)
7690{
7691 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7692 register const Py_UNICODE *e;
7693
7694 /* Shortcut for single character strings */
7695 if (PyUnicode_GET_SIZE(self) == 1 && Py_UNICODE_ISPRINTABLE(*p)) {
7696 Py_RETURN_TRUE;
7697 }
7698
7699 e = p + PyUnicode_GET_SIZE(self);
7700 for (; p < e; p++) {
7701 if (!Py_UNICODE_ISPRINTABLE(*p)) {
7702 Py_RETURN_FALSE;
7703 }
7704 }
7705 Py_RETURN_TRUE;
7706}
7707
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007708PyDoc_STRVAR(join__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007709 "S.join(sequence) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007710\n\
7711Return a string which is the concatenation of the strings in the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007712sequence. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007713
7714static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007715unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007716{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007717 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007718}
7719
Martin v. Löwis18e16552006-02-15 17:27:45 +00007720static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +00007721unicode_length(PyUnicodeObject *self)
7722{
7723 return self->length;
7724}
7725
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007726PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007727 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007728\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00007729Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007730done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007731
7732static PyObject *
7733unicode_ljust(PyUnicodeObject *self, PyObject *args)
7734{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007735 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007736 Py_UNICODE fillchar = ' ';
7737
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007738 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007739 return NULL;
7740
Tim Peters7a29bd52001-09-12 03:03:31 +00007741 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00007742 Py_INCREF(self);
7743 return (PyObject*) self;
7744 }
7745
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007746 return (PyObject*) pad(self, 0, width - self->length, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007747}
7748
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007749PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007750 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007751\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007752Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007753
7754static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007755unicode_lower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007756{
Guido van Rossumd57fd912000-03-10 22:53:23 +00007757 return fixup(self, fixlower);
7758}
7759
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007760#define LEFTSTRIP 0
7761#define RIGHTSTRIP 1
7762#define BOTHSTRIP 2
7763
7764/* Arrays indexed by above */
7765static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
7766
7767#define STRIPNAME(i) (stripformat[i]+3)
7768
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007769/* externally visible for str.strip(unicode) */
7770PyObject *
7771_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
7772{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007773 Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
7774 Py_ssize_t len = PyUnicode_GET_SIZE(self);
7775 Py_UNICODE *sep = PyUnicode_AS_UNICODE(sepobj);
7776 Py_ssize_t seplen = PyUnicode_GET_SIZE(sepobj);
7777 Py_ssize_t i, j;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007778
Benjamin Peterson29060642009-01-31 22:14:21 +00007779 BLOOM_MASK sepmask = make_bloom_mask(sep, seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007780
Benjamin Peterson14339b62009-01-31 16:36:08 +00007781 i = 0;
7782 if (striptype != RIGHTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007783 while (i < len && BLOOM_MEMBER(sepmask, s[i], sep, seplen)) {
7784 i++;
7785 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007786 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007787
Benjamin Peterson14339b62009-01-31 16:36:08 +00007788 j = len;
7789 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007790 do {
7791 j--;
7792 } while (j >= i && BLOOM_MEMBER(sepmask, s[j], sep, seplen));
7793 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007794 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007795
Benjamin Peterson14339b62009-01-31 16:36:08 +00007796 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007797 Py_INCREF(self);
7798 return (PyObject*)self;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007799 }
7800 else
Benjamin Peterson29060642009-01-31 22:14:21 +00007801 return PyUnicode_FromUnicode(s+i, j-i);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007802}
7803
Guido van Rossumd57fd912000-03-10 22:53:23 +00007804
7805static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007806do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007807{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007808 Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
7809 Py_ssize_t len = PyUnicode_GET_SIZE(self), i, j;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007810
Benjamin Peterson14339b62009-01-31 16:36:08 +00007811 i = 0;
7812 if (striptype != RIGHTSTRIP) {
7813 while (i < len && Py_UNICODE_ISSPACE(s[i])) {
7814 i++;
7815 }
7816 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007817
Benjamin Peterson14339b62009-01-31 16:36:08 +00007818 j = len;
7819 if (striptype != LEFTSTRIP) {
7820 do {
7821 j--;
7822 } while (j >= i && Py_UNICODE_ISSPACE(s[j]));
7823 j++;
7824 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007825
Benjamin Peterson14339b62009-01-31 16:36:08 +00007826 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
7827 Py_INCREF(self);
7828 return (PyObject*)self;
7829 }
7830 else
7831 return PyUnicode_FromUnicode(s+i, j-i);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007832}
7833
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007834
7835static PyObject *
7836do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
7837{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007838 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007839
Benjamin Peterson14339b62009-01-31 16:36:08 +00007840 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
7841 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007842
Benjamin Peterson14339b62009-01-31 16:36:08 +00007843 if (sep != NULL && sep != Py_None) {
7844 if (PyUnicode_Check(sep))
7845 return _PyUnicode_XStrip(self, striptype, sep);
7846 else {
7847 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00007848 "%s arg must be None or str",
7849 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +00007850 return NULL;
7851 }
7852 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007853
Benjamin Peterson14339b62009-01-31 16:36:08 +00007854 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007855}
7856
7857
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007858PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007859 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007860\n\
7861Return a copy of the string S with leading and trailing\n\
7862whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007863If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007864
7865static PyObject *
7866unicode_strip(PyUnicodeObject *self, PyObject *args)
7867{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007868 if (PyTuple_GET_SIZE(args) == 0)
7869 return do_strip(self, BOTHSTRIP); /* Common case */
7870 else
7871 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007872}
7873
7874
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007875PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007876 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007877\n\
7878Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007879If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007880
7881static PyObject *
7882unicode_lstrip(PyUnicodeObject *self, PyObject *args)
7883{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007884 if (PyTuple_GET_SIZE(args) == 0)
7885 return do_strip(self, LEFTSTRIP); /* Common case */
7886 else
7887 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007888}
7889
7890
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007891PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007892 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007893\n\
7894Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007895If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007896
7897static PyObject *
7898unicode_rstrip(PyUnicodeObject *self, PyObject *args)
7899{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007900 if (PyTuple_GET_SIZE(args) == 0)
7901 return do_strip(self, RIGHTSTRIP); /* Common case */
7902 else
7903 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007904}
7905
7906
Guido van Rossumd57fd912000-03-10 22:53:23 +00007907static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +00007908unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007909{
7910 PyUnicodeObject *u;
7911 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007912 Py_ssize_t nchars;
Tim Peters8f422462000-09-09 06:13:41 +00007913 size_t nbytes;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007914
Georg Brandl222de0f2009-04-12 12:01:50 +00007915 if (len < 1) {
7916 Py_INCREF(unicode_empty);
7917 return (PyObject *)unicode_empty;
7918 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007919
Tim Peters7a29bd52001-09-12 03:03:31 +00007920 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00007921 /* no repeat, return original string */
7922 Py_INCREF(str);
7923 return (PyObject*) str;
7924 }
Tim Peters8f422462000-09-09 06:13:41 +00007925
7926 /* ensure # of chars needed doesn't overflow int and # of bytes
7927 * needed doesn't overflow size_t
7928 */
7929 nchars = len * str->length;
Georg Brandl222de0f2009-04-12 12:01:50 +00007930 if (nchars / len != str->length) {
Tim Peters8f422462000-09-09 06:13:41 +00007931 PyErr_SetString(PyExc_OverflowError,
7932 "repeated string is too long");
7933 return NULL;
7934 }
7935 nbytes = (nchars + 1) * sizeof(Py_UNICODE);
7936 if (nbytes / sizeof(Py_UNICODE) != (size_t)(nchars + 1)) {
7937 PyErr_SetString(PyExc_OverflowError,
7938 "repeated string is too long");
7939 return NULL;
7940 }
7941 u = _PyUnicode_New(nchars);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007942 if (!u)
7943 return NULL;
7944
7945 p = u->str;
7946
Georg Brandl222de0f2009-04-12 12:01:50 +00007947 if (str->length == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00007948 Py_UNICODE_FILL(p, str->str[0], len);
7949 } else {
Georg Brandl222de0f2009-04-12 12:01:50 +00007950 Py_ssize_t done = str->length; /* number of characters copied this far */
7951 Py_UNICODE_COPY(p, str->str, str->length);
Benjamin Peterson29060642009-01-31 22:14:21 +00007952 while (done < nchars) {
Christian Heimescc47b052008-03-25 14:56:36 +00007953 Py_ssize_t n = (done <= nchars-done) ? done : nchars-done;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007954 Py_UNICODE_COPY(p+done, p, n);
7955 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00007956 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007957 }
7958
7959 return (PyObject*) u;
7960}
7961
7962PyObject *PyUnicode_Replace(PyObject *obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00007963 PyObject *subobj,
7964 PyObject *replobj,
7965 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007966{
7967 PyObject *self;
7968 PyObject *str1;
7969 PyObject *str2;
7970 PyObject *result;
7971
7972 self = PyUnicode_FromObject(obj);
7973 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007974 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007975 str1 = PyUnicode_FromObject(subobj);
7976 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007977 Py_DECREF(self);
7978 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007979 }
7980 str2 = PyUnicode_FromObject(replobj);
7981 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007982 Py_DECREF(self);
7983 Py_DECREF(str1);
7984 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007985 }
Tim Petersced69f82003-09-16 20:30:58 +00007986 result = replace((PyUnicodeObject *)self,
Benjamin Peterson29060642009-01-31 22:14:21 +00007987 (PyUnicodeObject *)str1,
7988 (PyUnicodeObject *)str2,
7989 maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007990 Py_DECREF(self);
7991 Py_DECREF(str1);
7992 Py_DECREF(str2);
7993 return result;
7994}
7995
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007996PyDoc_STRVAR(replace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007997 "S.replace (old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007998\n\
7999Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +00008000old replaced by new. If the optional argument count is\n\
8001given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008002
8003static PyObject*
8004unicode_replace(PyUnicodeObject *self, PyObject *args)
8005{
8006 PyUnicodeObject *str1;
8007 PyUnicodeObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008008 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008009 PyObject *result;
8010
Martin v. Löwis18e16552006-02-15 17:27:45 +00008011 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008012 return NULL;
8013 str1 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str1);
8014 if (str1 == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008015 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008016 str2 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str2);
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +00008017 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008018 Py_DECREF(str1);
8019 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +00008020 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008021
8022 result = replace(self, str1, str2, maxcount);
8023
8024 Py_DECREF(str1);
8025 Py_DECREF(str2);
8026 return result;
8027}
8028
8029static
8030PyObject *unicode_repr(PyObject *unicode)
8031{
Walter Dörwald79e913e2007-05-12 11:08:06 +00008032 PyObject *repr;
Walter Dörwald1ab83302007-05-18 17:15:44 +00008033 Py_UNICODE *p;
Walter Dörwald79e913e2007-05-12 11:08:06 +00008034 Py_UNICODE *s = PyUnicode_AS_UNICODE(unicode);
8035 Py_ssize_t size = PyUnicode_GET_SIZE(unicode);
8036
8037 /* XXX(nnorwitz): rather than over-allocating, it would be
8038 better to choose a different scheme. Perhaps scan the
8039 first N-chars of the string and allocate based on that size.
8040 */
8041 /* Initial allocation is based on the longest-possible unichr
8042 escape.
8043
8044 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
8045 unichr, so in this case it's the longest unichr escape. In
8046 narrow (UTF-16) builds this is five chars per source unichr
8047 since there are two unichrs in the surrogate pair, so in narrow
8048 (UTF-16) builds it's not the longest unichr escape.
8049
8050 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
8051 so in the narrow (UTF-16) build case it's the longest unichr
8052 escape.
8053 */
8054
Walter Dörwald1ab83302007-05-18 17:15:44 +00008055 repr = PyUnicode_FromUnicode(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00008056 2 /* quotes */
Walter Dörwald79e913e2007-05-12 11:08:06 +00008057#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00008058 + 10*size
Walter Dörwald79e913e2007-05-12 11:08:06 +00008059#else
Benjamin Peterson29060642009-01-31 22:14:21 +00008060 + 6*size
Walter Dörwald79e913e2007-05-12 11:08:06 +00008061#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00008062 + 1);
Walter Dörwald79e913e2007-05-12 11:08:06 +00008063 if (repr == NULL)
8064 return NULL;
8065
Walter Dörwald1ab83302007-05-18 17:15:44 +00008066 p = PyUnicode_AS_UNICODE(repr);
Walter Dörwald79e913e2007-05-12 11:08:06 +00008067
8068 /* Add quote */
8069 *p++ = (findchar(s, size, '\'') &&
8070 !findchar(s, size, '"')) ? '"' : '\'';
8071 while (size-- > 0) {
8072 Py_UNICODE ch = *s++;
8073
8074 /* Escape quotes and backslashes */
Walter Dörwald1ab83302007-05-18 17:15:44 +00008075 if ((ch == PyUnicode_AS_UNICODE(repr)[0]) || (ch == '\\')) {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008076 *p++ = '\\';
Walter Dörwald1ab83302007-05-18 17:15:44 +00008077 *p++ = ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00008078 continue;
8079 }
8080
Benjamin Peterson29060642009-01-31 22:14:21 +00008081 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +00008082 if (ch == '\t') {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008083 *p++ = '\\';
8084 *p++ = 't';
8085 }
8086 else if (ch == '\n') {
8087 *p++ = '\\';
8088 *p++ = 'n';
8089 }
8090 else if (ch == '\r') {
8091 *p++ = '\\';
8092 *p++ = 'r';
8093 }
8094
8095 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +00008096 else if (ch < ' ' || ch == 0x7F) {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008097 *p++ = '\\';
8098 *p++ = 'x';
8099 *p++ = hexdigits[(ch >> 4) & 0x000F];
8100 *p++ = hexdigits[ch & 0x000F];
8101 }
8102
Georg Brandl559e5d72008-06-11 18:37:52 +00008103 /* Copy ASCII characters as-is */
8104 else if (ch < 0x7F) {
8105 *p++ = ch;
8106 }
8107
Benjamin Peterson29060642009-01-31 22:14:21 +00008108 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +00008109 else {
8110 Py_UCS4 ucs = ch;
8111
8112#ifndef Py_UNICODE_WIDE
8113 Py_UNICODE ch2 = 0;
8114 /* Get code point from surrogate pair */
8115 if (size > 0) {
8116 ch2 = *s;
8117 if (ch >= 0xD800 && ch < 0xDC00 && ch2 >= 0xDC00
Benjamin Peterson29060642009-01-31 22:14:21 +00008118 && ch2 <= 0xDFFF) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008119 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF))
Benjamin Peterson29060642009-01-31 22:14:21 +00008120 + 0x00010000;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008121 s++;
Georg Brandl559e5d72008-06-11 18:37:52 +00008122 size--;
8123 }
8124 }
8125#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00008126 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +00008127 (categories Z* and C* except ASCII space)
8128 */
8129 if (!Py_UNICODE_ISPRINTABLE(ucs)) {
8130 /* Map 8-bit characters to '\xhh' */
8131 if (ucs <= 0xff) {
8132 *p++ = '\\';
8133 *p++ = 'x';
8134 *p++ = hexdigits[(ch >> 4) & 0x000F];
8135 *p++ = hexdigits[ch & 0x000F];
8136 }
8137 /* Map 21-bit characters to '\U00xxxxxx' */
8138 else if (ucs >= 0x10000) {
8139 *p++ = '\\';
8140 *p++ = 'U';
8141 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
8142 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
8143 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
8144 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
8145 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
8146 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
8147 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
8148 *p++ = hexdigits[ucs & 0x0000000F];
8149 }
8150 /* Map 16-bit characters to '\uxxxx' */
8151 else {
8152 *p++ = '\\';
8153 *p++ = 'u';
8154 *p++ = hexdigits[(ucs >> 12) & 0x000F];
8155 *p++ = hexdigits[(ucs >> 8) & 0x000F];
8156 *p++ = hexdigits[(ucs >> 4) & 0x000F];
8157 *p++ = hexdigits[ucs & 0x000F];
8158 }
8159 }
8160 /* Copy characters as-is */
8161 else {
8162 *p++ = ch;
8163#ifndef Py_UNICODE_WIDE
8164 if (ucs >= 0x10000)
8165 *p++ = ch2;
8166#endif
8167 }
8168 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00008169 }
8170 /* Add quote */
Walter Dörwald1ab83302007-05-18 17:15:44 +00008171 *p++ = PyUnicode_AS_UNICODE(repr)[0];
Walter Dörwald79e913e2007-05-12 11:08:06 +00008172
8173 *p = '\0';
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00008174 PyUnicode_Resize(&repr, p - PyUnicode_AS_UNICODE(repr));
Walter Dörwald79e913e2007-05-12 11:08:06 +00008175 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008176}
8177
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008178PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008179 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008180\n\
8181Return the highest index in S where substring sub is found,\n\
Guido van Rossum806c2462007-08-06 23:33:07 +00008182such that sub is contained within s[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008183arguments start and end are interpreted as in slice notation.\n\
8184\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008185Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008186
8187static PyObject *
8188unicode_rfind(PyUnicodeObject *self, PyObject *args)
8189{
Thomas Wouters477c8d52006-05-27 19:21:47 +00008190 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00008191 Py_ssize_t start;
8192 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008193 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008194
Christian Heimes9cd17752007-11-18 19:35:23 +00008195 if (!_ParseTupleFinds(args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008196 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008197
Thomas Wouters477c8d52006-05-27 19:21:47 +00008198 result = stringlib_rfind_slice(
8199 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
8200 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
8201 start, end
8202 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008203
8204 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008205
Christian Heimes217cfd12007-12-02 14:31:20 +00008206 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008207}
8208
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008209PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008210 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008211\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008212Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008213
8214static PyObject *
8215unicode_rindex(PyUnicodeObject *self, PyObject *args)
8216{
Thomas Wouters477c8d52006-05-27 19:21:47 +00008217 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00008218 Py_ssize_t start;
8219 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008220 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008221
Christian Heimes9cd17752007-11-18 19:35:23 +00008222 if (!_ParseTupleFinds(args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008223 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008224
Thomas Wouters477c8d52006-05-27 19:21:47 +00008225 result = stringlib_rfind_slice(
8226 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
8227 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
8228 start, end
8229 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008230
8231 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008232
Guido van Rossumd57fd912000-03-10 22:53:23 +00008233 if (result < 0) {
8234 PyErr_SetString(PyExc_ValueError, "substring not found");
8235 return NULL;
8236 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008237 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008238}
8239
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008240PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008241 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008242\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008243Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008244done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008245
8246static PyObject *
8247unicode_rjust(PyUnicodeObject *self, PyObject *args)
8248{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008249 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008250 Py_UNICODE fillchar = ' ';
8251
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008252 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008253 return NULL;
8254
Tim Peters7a29bd52001-09-12 03:03:31 +00008255 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008256 Py_INCREF(self);
8257 return (PyObject*) self;
8258 }
8259
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008260 return (PyObject*) pad(self, width - self->length, 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008261}
8262
Guido van Rossumd57fd912000-03-10 22:53:23 +00008263PyObject *PyUnicode_Split(PyObject *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00008264 PyObject *sep,
8265 Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008266{
8267 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008268
Guido van Rossumd57fd912000-03-10 22:53:23 +00008269 s = PyUnicode_FromObject(s);
8270 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008271 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00008272 if (sep != NULL) {
8273 sep = PyUnicode_FromObject(sep);
8274 if (sep == NULL) {
8275 Py_DECREF(s);
8276 return NULL;
8277 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008278 }
8279
8280 result = split((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
8281
8282 Py_DECREF(s);
8283 Py_XDECREF(sep);
8284 return result;
8285}
8286
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008287PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008288 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008289\n\
8290Return a list of the words in S, using sep as the\n\
8291delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00008292splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00008293whitespace string is a separator and empty strings are\n\
8294removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008295
8296static PyObject*
8297unicode_split(PyUnicodeObject *self, PyObject *args)
8298{
8299 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008300 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008301
Martin v. Löwis18e16552006-02-15 17:27:45 +00008302 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008303 return NULL;
8304
8305 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008306 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008307 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00008308 return split(self, (PyUnicodeObject *)substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008309 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008310 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008311}
8312
Thomas Wouters477c8d52006-05-27 19:21:47 +00008313PyObject *
8314PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
8315{
8316 PyObject* str_obj;
8317 PyObject* sep_obj;
8318 PyObject* out;
8319
8320 str_obj = PyUnicode_FromObject(str_in);
8321 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008322 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008323 sep_obj = PyUnicode_FromObject(sep_in);
8324 if (!sep_obj) {
8325 Py_DECREF(str_obj);
8326 return NULL;
8327 }
8328
8329 out = stringlib_partition(
8330 str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
8331 sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
8332 );
8333
8334 Py_DECREF(sep_obj);
8335 Py_DECREF(str_obj);
8336
8337 return out;
8338}
8339
8340
8341PyObject *
8342PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
8343{
8344 PyObject* str_obj;
8345 PyObject* sep_obj;
8346 PyObject* out;
8347
8348 str_obj = PyUnicode_FromObject(str_in);
8349 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008350 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008351 sep_obj = PyUnicode_FromObject(sep_in);
8352 if (!sep_obj) {
8353 Py_DECREF(str_obj);
8354 return NULL;
8355 }
8356
8357 out = stringlib_rpartition(
8358 str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
8359 sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
8360 );
8361
8362 Py_DECREF(sep_obj);
8363 Py_DECREF(str_obj);
8364
8365 return out;
8366}
8367
8368PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008369 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008370\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00008371Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008372the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008373found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00008374
8375static PyObject*
8376unicode_partition(PyUnicodeObject *self, PyObject *separator)
8377{
8378 return PyUnicode_Partition((PyObject *)self, separator);
8379}
8380
8381PyDoc_STRVAR(rpartition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008382 "S.rpartition(sep) -> (tail, sep, head)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008383\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00008384Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008385the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008386separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00008387
8388static PyObject*
8389unicode_rpartition(PyUnicodeObject *self, PyObject *separator)
8390{
8391 return PyUnicode_RPartition((PyObject *)self, separator);
8392}
8393
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008394PyObject *PyUnicode_RSplit(PyObject *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00008395 PyObject *sep,
8396 Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008397{
8398 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008399
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008400 s = PyUnicode_FromObject(s);
8401 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008402 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00008403 if (sep != NULL) {
8404 sep = PyUnicode_FromObject(sep);
8405 if (sep == NULL) {
8406 Py_DECREF(s);
8407 return NULL;
8408 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008409 }
8410
8411 result = rsplit((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
8412
8413 Py_DECREF(s);
8414 Py_XDECREF(sep);
8415 return result;
8416}
8417
8418PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008419 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008420\n\
8421Return a list of the words in S, using sep as the\n\
8422delimiter string, starting at the end of the string and\n\
8423working to the front. If maxsplit is given, at most maxsplit\n\
8424splits are done. If sep is not specified, any whitespace string\n\
8425is a separator.");
8426
8427static PyObject*
8428unicode_rsplit(PyUnicodeObject *self, PyObject *args)
8429{
8430 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008431 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008432
Martin v. Löwis18e16552006-02-15 17:27:45 +00008433 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008434 return NULL;
8435
8436 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008438 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00008439 return rsplit(self, (PyUnicodeObject *)substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008440 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008441 return PyUnicode_RSplit((PyObject *)self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008442}
8443
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008444PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008445 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008446\n\
8447Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +00008448Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008449is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008450
8451static PyObject*
8452unicode_splitlines(PyUnicodeObject *self, PyObject *args)
8453{
Guido van Rossum86662912000-04-11 15:38:46 +00008454 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008455
Guido van Rossum86662912000-04-11 15:38:46 +00008456 if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008457 return NULL;
8458
Guido van Rossum86662912000-04-11 15:38:46 +00008459 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008460}
8461
8462static
Guido van Rossumf15a29f2007-05-04 00:41:39 +00008463PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008464{
Walter Dörwald346737f2007-05-31 10:44:43 +00008465 if (PyUnicode_CheckExact(self)) {
8466 Py_INCREF(self);
8467 return self;
8468 } else
8469 /* Subtype -- return genuine unicode string with the same value. */
8470 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(self),
8471 PyUnicode_GET_SIZE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +00008472}
8473
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008474PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008475 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008476\n\
8477Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008478and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008479
8480static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008481unicode_swapcase(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008482{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008483 return fixup(self, fixswapcase);
8484}
8485
Georg Brandlceee0772007-11-27 23:48:05 +00008486PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008487 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +00008488\n\
8489Return a translation table usable for str.translate().\n\
8490If there is only one argument, it must be a dictionary mapping Unicode\n\
8491ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008492Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +00008493If there are two arguments, they must be strings of equal length, and\n\
8494in the resulting dictionary, each character in x will be mapped to the\n\
8495character at the same position in y. If there is a third argument, it\n\
8496must be a string, whose characters will be mapped to None in the result.");
8497
8498static PyObject*
8499unicode_maketrans(PyUnicodeObject *null, PyObject *args)
8500{
8501 PyObject *x, *y = NULL, *z = NULL;
8502 PyObject *new = NULL, *key, *value;
8503 Py_ssize_t i = 0;
8504 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008505
Georg Brandlceee0772007-11-27 23:48:05 +00008506 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
8507 return NULL;
8508 new = PyDict_New();
8509 if (!new)
8510 return NULL;
8511 if (y != NULL) {
8512 /* x must be a string too, of equal length */
8513 Py_ssize_t ylen = PyUnicode_GET_SIZE(y);
8514 if (!PyUnicode_Check(x)) {
8515 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
8516 "be a string if there is a second argument");
8517 goto err;
8518 }
8519 if (PyUnicode_GET_SIZE(x) != ylen) {
8520 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
8521 "arguments must have equal length");
8522 goto err;
8523 }
8524 /* create entries for translating chars in x to those in y */
8525 for (i = 0; i < PyUnicode_GET_SIZE(x); i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +00008526 key = PyLong_FromLong(PyUnicode_AS_UNICODE(x)[i]);
8527 value = PyLong_FromLong(PyUnicode_AS_UNICODE(y)[i]);
Georg Brandlceee0772007-11-27 23:48:05 +00008528 if (!key || !value)
8529 goto err;
8530 res = PyDict_SetItem(new, key, value);
8531 Py_DECREF(key);
8532 Py_DECREF(value);
8533 if (res < 0)
8534 goto err;
8535 }
8536 /* create entries for deleting chars in z */
8537 if (z != NULL) {
8538 for (i = 0; i < PyUnicode_GET_SIZE(z); i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +00008539 key = PyLong_FromLong(PyUnicode_AS_UNICODE(z)[i]);
Georg Brandlceee0772007-11-27 23:48:05 +00008540 if (!key)
8541 goto err;
8542 res = PyDict_SetItem(new, key, Py_None);
8543 Py_DECREF(key);
8544 if (res < 0)
8545 goto err;
8546 }
8547 }
8548 } else {
8549 /* x must be a dict */
8550 if (!PyDict_Check(x)) {
8551 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
8552 "to maketrans it must be a dict");
8553 goto err;
8554 }
8555 /* copy entries into the new dict, converting string keys to int keys */
8556 while (PyDict_Next(x, &i, &key, &value)) {
8557 if (PyUnicode_Check(key)) {
8558 /* convert string keys to integer keys */
8559 PyObject *newkey;
8560 if (PyUnicode_GET_SIZE(key) != 1) {
8561 PyErr_SetString(PyExc_ValueError, "string keys in translate "
8562 "table must be of length 1");
8563 goto err;
8564 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008565 newkey = PyLong_FromLong(PyUnicode_AS_UNICODE(key)[0]);
Georg Brandlceee0772007-11-27 23:48:05 +00008566 if (!newkey)
8567 goto err;
8568 res = PyDict_SetItem(new, newkey, value);
8569 Py_DECREF(newkey);
8570 if (res < 0)
8571 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +00008572 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +00008573 /* just keep integer keys */
8574 if (PyDict_SetItem(new, key, value) < 0)
8575 goto err;
8576 } else {
8577 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
8578 "be strings or integers");
8579 goto err;
8580 }
8581 }
8582 }
8583 return new;
8584 err:
8585 Py_DECREF(new);
8586 return NULL;
8587}
8588
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008589PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008590 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008591\n\
8592Return a copy of the string S, where all characters have been mapped\n\
8593through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008594Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +00008595Unmapped characters are left untouched. Characters mapped to None\n\
8596are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008597
8598static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008599unicode_translate(PyUnicodeObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008600{
Georg Brandlceee0772007-11-27 23:48:05 +00008601 return PyUnicode_TranslateCharmap(self->str, self->length, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008602}
8603
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008604PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008605 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008606\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008607Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008608
8609static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008610unicode_upper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008611{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008612 return fixup(self, fixupper);
8613}
8614
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008615PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008616 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008617\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +00008618Pad a numeric string S with zeros on the left, to fill a field\n\
8619of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008620
8621static PyObject *
8622unicode_zfill(PyUnicodeObject *self, PyObject *args)
8623{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008624 Py_ssize_t fill;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008625 PyUnicodeObject *u;
8626
Martin v. Löwis18e16552006-02-15 17:27:45 +00008627 Py_ssize_t width;
8628 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008629 return NULL;
8630
8631 if (self->length >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +00008632 if (PyUnicode_CheckExact(self)) {
8633 Py_INCREF(self);
8634 return (PyObject*) self;
8635 }
8636 else
8637 return PyUnicode_FromUnicode(
8638 PyUnicode_AS_UNICODE(self),
8639 PyUnicode_GET_SIZE(self)
Benjamin Peterson29060642009-01-31 22:14:21 +00008640 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008641 }
8642
8643 fill = width - self->length;
8644
8645 u = pad(self, fill, 0, '0');
8646
Walter Dörwald068325e2002-04-15 13:36:47 +00008647 if (u == NULL)
8648 return NULL;
8649
Guido van Rossumd57fd912000-03-10 22:53:23 +00008650 if (u->str[fill] == '+' || u->str[fill] == '-') {
8651 /* move sign to beginning of string */
8652 u->str[0] = u->str[fill];
8653 u->str[fill] = '0';
8654 }
8655
8656 return (PyObject*) u;
8657}
Guido van Rossumd57fd912000-03-10 22:53:23 +00008658
8659#if 0
8660static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008661unicode_freelistsize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008662{
Christian Heimes2202f872008-02-06 14:31:34 +00008663 return PyLong_FromLong(numfree);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008664}
8665#endif
8666
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008667PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008668 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008669\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00008670Return True if S starts with the specified prefix, False otherwise.\n\
8671With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008672With optional end, stop comparing S at that position.\n\
8673prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008674
8675static PyObject *
8676unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00008677 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008678{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008679 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008680 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008681 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008682 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008683 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008684
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008685 if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
Benjamin Peterson29060642009-01-31 22:14:21 +00008686 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
8687 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008688 if (PyTuple_Check(subobj)) {
8689 Py_ssize_t i;
8690 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
8691 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +00008692 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008693 if (substring == NULL)
8694 return NULL;
8695 result = tailmatch(self, substring, start, end, -1);
8696 Py_DECREF(substring);
8697 if (result) {
8698 Py_RETURN_TRUE;
8699 }
8700 }
8701 /* nothing matched */
8702 Py_RETURN_FALSE;
8703 }
8704 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008705 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008706 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008707 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008708 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008709 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008710}
8711
8712
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008713PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008714 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008715\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00008716Return True if S ends with the specified suffix, False otherwise.\n\
8717With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008718With optional end, stop comparing S at that position.\n\
8719suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008720
8721static PyObject *
8722unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00008723 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008724{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008725 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008726 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008727 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008728 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008729 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008730
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008731 if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
Benjamin Peterson29060642009-01-31 22:14:21 +00008732 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
8733 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008734 if (PyTuple_Check(subobj)) {
8735 Py_ssize_t i;
8736 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
8737 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +00008738 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008739 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008740 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008741 result = tailmatch(self, substring, start, end, +1);
8742 Py_DECREF(substring);
8743 if (result) {
8744 Py_RETURN_TRUE;
8745 }
8746 }
8747 Py_RETURN_FALSE;
8748 }
8749 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008750 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008751 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008752
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008753 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008754 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008755 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008756}
8757
Eric Smith8c663262007-08-25 02:26:07 +00008758#include "stringlib/string_format.h"
8759
8760PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008761 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +00008762\n\
8763");
8764
Eric Smith4a7d76d2008-05-30 18:10:19 +00008765static PyObject *
8766unicode__format__(PyObject* self, PyObject* args)
8767{
8768 PyObject *format_spec;
8769
8770 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
8771 return NULL;
8772
8773 return _PyUnicode_FormatAdvanced(self,
8774 PyUnicode_AS_UNICODE(format_spec),
8775 PyUnicode_GET_SIZE(format_spec));
8776}
8777
Eric Smith8c663262007-08-25 02:26:07 +00008778PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008779 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +00008780\n\
8781");
8782
8783static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +00008784unicode__sizeof__(PyUnicodeObject *v)
8785{
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00008786 return PyLong_FromSsize_t(sizeof(PyUnicodeObject) +
8787 sizeof(Py_UNICODE) * (v->length + 1));
Georg Brandlc28e1fa2008-06-10 19:20:26 +00008788}
8789
8790PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008791 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00008792
8793static PyObject *
Guido van Rossum5d9113d2003-01-29 17:58:45 +00008794unicode_getnewargs(PyUnicodeObject *v)
8795{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008796 return Py_BuildValue("(u#)", v->str, v->length);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00008797}
8798
8799
Guido van Rossumd57fd912000-03-10 22:53:23 +00008800static PyMethodDef unicode_methods[] = {
8801
8802 /* Order is according to common usage: often used methods should
8803 appear first, since lookup is done sequentially. */
8804
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008805 {"encode", (PyCFunction) unicode_encode, METH_VARARGS, encode__doc__},
8806 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
8807 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008808 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008809 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
8810 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
8811 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
8812 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
8813 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
8814 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
8815 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00008816 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008817 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
8818 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
8819 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008820 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008821 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
8822 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
8823 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008824 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00008825 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008826 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008827 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008828 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
8829 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
8830 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
8831 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
8832 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
8833 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
8834 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
8835 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
8836 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
8837 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
8838 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
8839 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
8840 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
8841 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +00008842 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +00008843 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008844 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +00008845 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +00008846 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Eric Smithf6db4092007-08-27 23:52:26 +00008847 {"_formatter_field_name_split", (PyCFunction) formatter_field_name_split, METH_NOARGS},
8848 {"_formatter_parser", (PyCFunction) formatter_parser, METH_NOARGS},
Georg Brandlceee0772007-11-27 23:48:05 +00008849 {"maketrans", (PyCFunction) unicode_maketrans,
8850 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +00008851 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +00008852#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008853 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +00008854#endif
8855
8856#if 0
8857 /* This one is just used for debugging the implementation. */
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008858 {"freelistsize", (PyCFunction) unicode_freelistsize, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +00008859#endif
8860
Benjamin Peterson14339b62009-01-31 16:36:08 +00008861 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +00008862 {NULL, NULL}
8863};
8864
Neil Schemenauerce30bc92002-11-18 16:10:18 +00008865static PyObject *
8866unicode_mod(PyObject *v, PyObject *w)
8867{
Benjamin Peterson29060642009-01-31 22:14:21 +00008868 if (!PyUnicode_Check(v)) {
8869 Py_INCREF(Py_NotImplemented);
8870 return Py_NotImplemented;
8871 }
8872 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +00008873}
8874
8875static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008876 0, /*nb_add*/
8877 0, /*nb_subtract*/
8878 0, /*nb_multiply*/
8879 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +00008880};
8881
Guido van Rossumd57fd912000-03-10 22:53:23 +00008882static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008883 (lenfunc) unicode_length, /* sq_length */
8884 PyUnicode_Concat, /* sq_concat */
8885 (ssizeargfunc) unicode_repeat, /* sq_repeat */
8886 (ssizeargfunc) unicode_getitem, /* sq_item */
8887 0, /* sq_slice */
8888 0, /* sq_ass_item */
8889 0, /* sq_ass_slice */
8890 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +00008891};
8892
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008893static PyObject*
8894unicode_subscript(PyUnicodeObject* self, PyObject* item)
8895{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00008896 if (PyIndex_Check(item)) {
8897 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008898 if (i == -1 && PyErr_Occurred())
8899 return NULL;
8900 if (i < 0)
Martin v. Löwisdea59e52006-01-05 10:00:36 +00008901 i += PyUnicode_GET_SIZE(self);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008902 return unicode_getitem(self, i);
8903 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00008904 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008905 Py_UNICODE* source_buf;
8906 Py_UNICODE* result_buf;
8907 PyObject* result;
8908
Martin v. Löwisdea59e52006-01-05 10:00:36 +00008909 if (PySlice_GetIndicesEx((PySliceObject*)item, PyUnicode_GET_SIZE(self),
Benjamin Peterson29060642009-01-31 22:14:21 +00008910 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008911 return NULL;
8912 }
8913
8914 if (slicelength <= 0) {
8915 return PyUnicode_FromUnicode(NULL, 0);
Thomas Woutersed03b412007-08-28 21:37:11 +00008916 } else if (start == 0 && step == 1 && slicelength == self->length &&
8917 PyUnicode_CheckExact(self)) {
8918 Py_INCREF(self);
8919 return (PyObject *)self;
8920 } else if (step == 1) {
8921 return PyUnicode_FromUnicode(self->str + start, slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008922 } else {
8923 source_buf = PyUnicode_AS_UNICODE((PyObject*)self);
Christian Heimesb186d002008-03-18 15:15:01 +00008924 result_buf = (Py_UNICODE *)PyObject_MALLOC(slicelength*
8925 sizeof(Py_UNICODE));
Benjamin Peterson14339b62009-01-31 16:36:08 +00008926
Benjamin Peterson29060642009-01-31 22:14:21 +00008927 if (result_buf == NULL)
8928 return PyErr_NoMemory();
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008929
8930 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
8931 result_buf[i] = source_buf[cur];
8932 }
Tim Petersced69f82003-09-16 20:30:58 +00008933
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008934 result = PyUnicode_FromUnicode(result_buf, slicelength);
Christian Heimesb186d002008-03-18 15:15:01 +00008935 PyObject_FREE(result_buf);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008936 return result;
8937 }
8938 } else {
8939 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
8940 return NULL;
8941 }
8942}
8943
8944static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008945 (lenfunc)unicode_length, /* mp_length */
8946 (binaryfunc)unicode_subscript, /* mp_subscript */
8947 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008948};
8949
Guido van Rossumd57fd912000-03-10 22:53:23 +00008950
Guido van Rossumd57fd912000-03-10 22:53:23 +00008951/* Helpers for PyUnicode_Format() */
8952
8953static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00008954getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008955{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008956 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008957 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008958 (*p_argidx)++;
8959 if (arglen < 0)
8960 return args;
8961 else
8962 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008963 }
8964 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00008965 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008966 return NULL;
8967}
8968
Mark Dickinsonf489caf2009-05-01 11:42:00 +00008969/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00008970
Mark Dickinsonf489caf2009-05-01 11:42:00 +00008971static PyObject *
8972formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008973{
Mark Dickinsonf489caf2009-05-01 11:42:00 +00008974 char *p;
8975 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008976 double x;
Tim Petersced69f82003-09-16 20:30:58 +00008977
Guido van Rossumd57fd912000-03-10 22:53:23 +00008978 x = PyFloat_AsDouble(v);
8979 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +00008980 return NULL;
8981
Guido van Rossumd57fd912000-03-10 22:53:23 +00008982 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008983 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +00008984
Eric Smith0923d1d2009-04-16 20:16:10 +00008985 p = PyOS_double_to_string(x, type, prec,
8986 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +00008987 if (p == NULL)
8988 return NULL;
8989 result = PyUnicode_FromStringAndSize(p, strlen(p));
Eric Smith0923d1d2009-04-16 20:16:10 +00008990 PyMem_Free(p);
8991 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008992}
8993
Tim Peters38fd5b62000-09-21 05:43:11 +00008994static PyObject*
8995formatlong(PyObject *val, int flags, int prec, int type)
8996{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008997 char *buf;
8998 int len;
8999 PyObject *str; /* temporary string object. */
9000 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +00009001
Benjamin Peterson14339b62009-01-31 16:36:08 +00009002 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
9003 if (!str)
9004 return NULL;
9005 result = PyUnicode_FromStringAndSize(buf, len);
9006 Py_DECREF(str);
9007 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +00009008}
9009
Guido van Rossumd57fd912000-03-10 22:53:23 +00009010static int
9011formatchar(Py_UNICODE *buf,
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009012 size_t buflen,
9013 PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009014{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00009015 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009016 if (PyUnicode_Check(v)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009017 if (PyUnicode_GET_SIZE(v) == 1) {
9018 buf[0] = PyUnicode_AS_UNICODE(v)[0];
9019 buf[1] = '\0';
9020 return 1;
9021 }
9022#ifndef Py_UNICODE_WIDE
9023 if (PyUnicode_GET_SIZE(v) == 2) {
9024 /* Decode a valid surrogate pair */
9025 int c0 = PyUnicode_AS_UNICODE(v)[0];
9026 int c1 = PyUnicode_AS_UNICODE(v)[1];
9027 if (0xD800 <= c0 && c0 <= 0xDBFF &&
9028 0xDC00 <= c1 && c1 <= 0xDFFF) {
9029 buf[0] = c0;
9030 buf[1] = c1;
9031 buf[2] = '\0';
9032 return 2;
9033 }
9034 }
9035#endif
9036 goto onError;
9037 }
9038 else {
9039 /* Integer input truncated to a character */
9040 long x;
9041 x = PyLong_AsLong(v);
9042 if (x == -1 && PyErr_Occurred())
9043 goto onError;
9044
9045 if (x < 0 || x > 0x10ffff) {
9046 PyErr_SetString(PyExc_OverflowError,
9047 "%c arg not in range(0x110000)");
9048 return -1;
9049 }
9050
9051#ifndef Py_UNICODE_WIDE
9052 if (x > 0xffff) {
9053 x -= 0x10000;
9054 buf[0] = (Py_UNICODE)(0xD800 | (x >> 10));
9055 buf[1] = (Py_UNICODE)(0xDC00 | (x & 0x3FF));
9056 return 2;
9057 }
9058#endif
9059 buf[0] = (Py_UNICODE) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009060 buf[1] = '\0';
9061 return 1;
9062 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00009063
Benjamin Peterson29060642009-01-31 22:14:21 +00009064 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009065 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009066 "%c requires int or char");
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009067 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009068}
9069
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009070/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009071 FORMATBUFLEN is the length of the buffer in which chars are formatted.
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009072*/
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009073#define FORMATBUFLEN (size_t)10
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009074
Guido van Rossumd57fd912000-03-10 22:53:23 +00009075PyObject *PyUnicode_Format(PyObject *format,
Benjamin Peterson29060642009-01-31 22:14:21 +00009076 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009077{
9078 Py_UNICODE *fmt, *res;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009079 Py_ssize_t fmtcnt, rescnt, reslen, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009080 int args_owned = 0;
9081 PyUnicodeObject *result = NULL;
9082 PyObject *dict = NULL;
9083 PyObject *uformat;
Tim Petersced69f82003-09-16 20:30:58 +00009084
Guido van Rossumd57fd912000-03-10 22:53:23 +00009085 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009086 PyErr_BadInternalCall();
9087 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009088 }
9089 uformat = PyUnicode_FromObject(format);
Fred Drakee4315f52000-05-09 19:53:39 +00009090 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009091 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009092 fmt = PyUnicode_AS_UNICODE(uformat);
9093 fmtcnt = PyUnicode_GET_SIZE(uformat);
9094
9095 reslen = rescnt = fmtcnt + 100;
9096 result = _PyUnicode_New(reslen);
9097 if (result == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009098 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009099 res = PyUnicode_AS_UNICODE(result);
9100
9101 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009102 arglen = PyTuple_Size(args);
9103 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009104 }
9105 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009106 arglen = -1;
9107 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009108 }
Christian Heimes90aa7642007-12-19 02:45:37 +00009109 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +00009110 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +00009111 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009112
9113 while (--fmtcnt >= 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009114 if (*fmt != '%') {
9115 if (--rescnt < 0) {
9116 rescnt = fmtcnt + 100;
9117 reslen += rescnt;
9118 if (_PyUnicode_Resize(&result, reslen) < 0)
9119 goto onError;
9120 res = PyUnicode_AS_UNICODE(result) + reslen - rescnt;
9121 --rescnt;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009122 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009123 *res++ = *fmt++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009124 }
9125 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009126 /* Got a format specifier */
9127 int flags = 0;
9128 Py_ssize_t width = -1;
9129 int prec = -1;
9130 Py_UNICODE c = '\0';
9131 Py_UNICODE fill;
9132 int isnumok;
9133 PyObject *v = NULL;
9134 PyObject *temp = NULL;
9135 Py_UNICODE *pbuf;
9136 Py_UNICODE sign;
9137 Py_ssize_t len;
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009138 Py_UNICODE formatbuf[FORMATBUFLEN]; /* For formatchar() */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009139
Benjamin Peterson29060642009-01-31 22:14:21 +00009140 fmt++;
9141 if (*fmt == '(') {
9142 Py_UNICODE *keystart;
9143 Py_ssize_t keylen;
9144 PyObject *key;
9145 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +00009146
Benjamin Peterson29060642009-01-31 22:14:21 +00009147 if (dict == NULL) {
9148 PyErr_SetString(PyExc_TypeError,
9149 "format requires a mapping");
9150 goto onError;
9151 }
9152 ++fmt;
9153 --fmtcnt;
9154 keystart = fmt;
9155 /* Skip over balanced parentheses */
9156 while (pcount > 0 && --fmtcnt >= 0) {
9157 if (*fmt == ')')
9158 --pcount;
9159 else if (*fmt == '(')
9160 ++pcount;
9161 fmt++;
9162 }
9163 keylen = fmt - keystart - 1;
9164 if (fmtcnt < 0 || pcount > 0) {
9165 PyErr_SetString(PyExc_ValueError,
9166 "incomplete format key");
9167 goto onError;
9168 }
9169#if 0
9170 /* keys are converted to strings using UTF-8 and
9171 then looked up since Python uses strings to hold
9172 variables names etc. in its namespaces and we
9173 wouldn't want to break common idioms. */
9174 key = PyUnicode_EncodeUTF8(keystart,
9175 keylen,
9176 NULL);
9177#else
9178 key = PyUnicode_FromUnicode(keystart, keylen);
9179#endif
9180 if (key == NULL)
9181 goto onError;
9182 if (args_owned) {
9183 Py_DECREF(args);
9184 args_owned = 0;
9185 }
9186 args = PyObject_GetItem(dict, key);
9187 Py_DECREF(key);
9188 if (args == NULL) {
9189 goto onError;
9190 }
9191 args_owned = 1;
9192 arglen = -1;
9193 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009194 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009195 while (--fmtcnt >= 0) {
9196 switch (c = *fmt++) {
9197 case '-': flags |= F_LJUST; continue;
9198 case '+': flags |= F_SIGN; continue;
9199 case ' ': flags |= F_BLANK; continue;
9200 case '#': flags |= F_ALT; continue;
9201 case '0': flags |= F_ZERO; continue;
9202 }
9203 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009204 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009205 if (c == '*') {
9206 v = getnextarg(args, arglen, &argidx);
9207 if (v == NULL)
9208 goto onError;
9209 if (!PyLong_Check(v)) {
9210 PyErr_SetString(PyExc_TypeError,
9211 "* wants int");
9212 goto onError;
9213 }
9214 width = PyLong_AsLong(v);
9215 if (width == -1 && PyErr_Occurred())
9216 goto onError;
9217 if (width < 0) {
9218 flags |= F_LJUST;
9219 width = -width;
9220 }
9221 if (--fmtcnt >= 0)
9222 c = *fmt++;
9223 }
9224 else if (c >= '0' && c <= '9') {
9225 width = c - '0';
9226 while (--fmtcnt >= 0) {
9227 c = *fmt++;
9228 if (c < '0' || c > '9')
9229 break;
9230 if ((width*10) / 10 != width) {
9231 PyErr_SetString(PyExc_ValueError,
9232 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009233 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00009234 }
9235 width = width*10 + (c - '0');
9236 }
9237 }
9238 if (c == '.') {
9239 prec = 0;
9240 if (--fmtcnt >= 0)
9241 c = *fmt++;
9242 if (c == '*') {
9243 v = getnextarg(args, arglen, &argidx);
9244 if (v == NULL)
9245 goto onError;
9246 if (!PyLong_Check(v)) {
9247 PyErr_SetString(PyExc_TypeError,
9248 "* wants int");
9249 goto onError;
9250 }
9251 prec = PyLong_AsLong(v);
9252 if (prec == -1 && PyErr_Occurred())
9253 goto onError;
9254 if (prec < 0)
9255 prec = 0;
9256 if (--fmtcnt >= 0)
9257 c = *fmt++;
9258 }
9259 else if (c >= '0' && c <= '9') {
9260 prec = c - '0';
9261 while (--fmtcnt >= 0) {
9262 c = Py_CHARMASK(*fmt++);
9263 if (c < '0' || c > '9')
9264 break;
9265 if ((prec*10) / 10 != prec) {
9266 PyErr_SetString(PyExc_ValueError,
9267 "prec too big");
9268 goto onError;
9269 }
9270 prec = prec*10 + (c - '0');
9271 }
9272 }
9273 } /* prec */
9274 if (fmtcnt >= 0) {
9275 if (c == 'h' || c == 'l' || c == 'L') {
9276 if (--fmtcnt >= 0)
9277 c = *fmt++;
9278 }
9279 }
9280 if (fmtcnt < 0) {
9281 PyErr_SetString(PyExc_ValueError,
9282 "incomplete format");
9283 goto onError;
9284 }
9285 if (c != '%') {
9286 v = getnextarg(args, arglen, &argidx);
9287 if (v == NULL)
9288 goto onError;
9289 }
9290 sign = 0;
9291 fill = ' ';
9292 switch (c) {
9293
9294 case '%':
9295 pbuf = formatbuf;
9296 /* presume that buffer length is at least 1 */
9297 pbuf[0] = '%';
9298 len = 1;
9299 break;
9300
9301 case 's':
9302 case 'r':
9303 case 'a':
9304 if (PyUnicode_Check(v) && c == 's') {
9305 temp = v;
9306 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009307 }
9308 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009309 if (c == 's')
9310 temp = PyObject_Str(v);
9311 else if (c == 'r')
9312 temp = PyObject_Repr(v);
9313 else
9314 temp = PyObject_ASCII(v);
9315 if (temp == NULL)
9316 goto onError;
9317 if (PyUnicode_Check(temp))
9318 /* nothing to do */;
9319 else {
9320 Py_DECREF(temp);
9321 PyErr_SetString(PyExc_TypeError,
9322 "%s argument has non-string str()");
9323 goto onError;
9324 }
9325 }
9326 pbuf = PyUnicode_AS_UNICODE(temp);
9327 len = PyUnicode_GET_SIZE(temp);
9328 if (prec >= 0 && len > prec)
9329 len = prec;
9330 break;
9331
9332 case 'i':
9333 case 'd':
9334 case 'u':
9335 case 'o':
9336 case 'x':
9337 case 'X':
9338 if (c == 'i')
9339 c = 'd';
9340 isnumok = 0;
9341 if (PyNumber_Check(v)) {
9342 PyObject *iobj=NULL;
9343
9344 if (PyLong_Check(v)) {
9345 iobj = v;
9346 Py_INCREF(iobj);
9347 }
9348 else {
9349 iobj = PyNumber_Long(v);
9350 }
9351 if (iobj!=NULL) {
9352 if (PyLong_Check(iobj)) {
9353 isnumok = 1;
9354 temp = formatlong(iobj, flags, prec, c);
9355 Py_DECREF(iobj);
9356 if (!temp)
9357 goto onError;
9358 pbuf = PyUnicode_AS_UNICODE(temp);
9359 len = PyUnicode_GET_SIZE(temp);
9360 sign = 1;
9361 }
9362 else {
9363 Py_DECREF(iobj);
9364 }
9365 }
9366 }
9367 if (!isnumok) {
9368 PyErr_Format(PyExc_TypeError,
9369 "%%%c format: a number is required, "
9370 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
9371 goto onError;
9372 }
9373 if (flags & F_ZERO)
9374 fill = '0';
9375 break;
9376
9377 case 'e':
9378 case 'E':
9379 case 'f':
9380 case 'F':
9381 case 'g':
9382 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009383 temp = formatfloat(v, flags, prec, c);
9384 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +00009385 goto onError;
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009386 pbuf = PyUnicode_AS_UNICODE(temp);
9387 len = PyUnicode_GET_SIZE(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +00009388 sign = 1;
9389 if (flags & F_ZERO)
9390 fill = '0';
9391 break;
9392
9393 case 'c':
9394 pbuf = formatbuf;
9395 len = formatchar(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), v);
9396 if (len < 0)
9397 goto onError;
9398 break;
9399
9400 default:
9401 PyErr_Format(PyExc_ValueError,
9402 "unsupported format character '%c' (0x%x) "
9403 "at index %zd",
9404 (31<=c && c<=126) ? (char)c : '?',
9405 (int)c,
9406 (Py_ssize_t)(fmt - 1 -
9407 PyUnicode_AS_UNICODE(uformat)));
9408 goto onError;
9409 }
9410 if (sign) {
9411 if (*pbuf == '-' || *pbuf == '+') {
9412 sign = *pbuf++;
9413 len--;
9414 }
9415 else if (flags & F_SIGN)
9416 sign = '+';
9417 else if (flags & F_BLANK)
9418 sign = ' ';
9419 else
9420 sign = 0;
9421 }
9422 if (width < len)
9423 width = len;
9424 if (rescnt - (sign != 0) < width) {
9425 reslen -= rescnt;
9426 rescnt = width + fmtcnt + 100;
9427 reslen += rescnt;
9428 if (reslen < 0) {
9429 Py_XDECREF(temp);
9430 PyErr_NoMemory();
9431 goto onError;
9432 }
9433 if (_PyUnicode_Resize(&result, reslen) < 0) {
9434 Py_XDECREF(temp);
9435 goto onError;
9436 }
9437 res = PyUnicode_AS_UNICODE(result)
9438 + reslen - rescnt;
9439 }
9440 if (sign) {
9441 if (fill != ' ')
9442 *res++ = sign;
9443 rescnt--;
9444 if (width > len)
9445 width--;
9446 }
9447 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
9448 assert(pbuf[0] == '0');
9449 assert(pbuf[1] == c);
9450 if (fill != ' ') {
9451 *res++ = *pbuf++;
9452 *res++ = *pbuf++;
9453 }
9454 rescnt -= 2;
9455 width -= 2;
9456 if (width < 0)
9457 width = 0;
9458 len -= 2;
9459 }
9460 if (width > len && !(flags & F_LJUST)) {
9461 do {
9462 --rescnt;
9463 *res++ = fill;
9464 } while (--width > len);
9465 }
9466 if (fill == ' ') {
9467 if (sign)
9468 *res++ = sign;
9469 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
9470 assert(pbuf[0] == '0');
9471 assert(pbuf[1] == c);
9472 *res++ = *pbuf++;
9473 *res++ = *pbuf++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009474 }
9475 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009476 Py_UNICODE_COPY(res, pbuf, len);
9477 res += len;
9478 rescnt -= len;
9479 while (--width >= len) {
9480 --rescnt;
9481 *res++ = ' ';
9482 }
9483 if (dict && (argidx < arglen) && c != '%') {
9484 PyErr_SetString(PyExc_TypeError,
9485 "not all arguments converted during string formatting");
Thomas Woutersa96affe2006-03-12 00:29:36 +00009486 Py_XDECREF(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +00009487 goto onError;
9488 }
9489 Py_XDECREF(temp);
9490 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009491 } /* until end */
9492 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009493 PyErr_SetString(PyExc_TypeError,
9494 "not all arguments converted during string formatting");
9495 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009496 }
9497
Thomas Woutersa96affe2006-03-12 00:29:36 +00009498 if (_PyUnicode_Resize(&result, reslen - rescnt) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009499 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009500 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009501 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009502 }
9503 Py_DECREF(uformat);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009504 return (PyObject *)result;
9505
Benjamin Peterson29060642009-01-31 22:14:21 +00009506 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009507 Py_XDECREF(result);
9508 Py_DECREF(uformat);
9509 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009510 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009511 }
9512 return NULL;
9513}
9514
Jeremy Hylton938ace62002-07-17 16:30:39 +00009515static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +00009516unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
9517
Tim Peters6d6c1a32001-08-02 04:15:00 +00009518static PyObject *
9519unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9520{
Benjamin Peterson29060642009-01-31 22:14:21 +00009521 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009522 static char *kwlist[] = {"object", "encoding", "errors", 0};
9523 char *encoding = NULL;
9524 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00009525
Benjamin Peterson14339b62009-01-31 16:36:08 +00009526 if (type != &PyUnicode_Type)
9527 return unicode_subtype_new(type, args, kwds);
9528 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +00009529 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009530 return NULL;
9531 if (x == NULL)
9532 return (PyObject *)_PyUnicode_New(0);
9533 if (encoding == NULL && errors == NULL)
9534 return PyObject_Str(x);
9535 else
Benjamin Peterson29060642009-01-31 22:14:21 +00009536 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +00009537}
9538
Guido van Rossume023fe02001-08-30 03:12:59 +00009539static PyObject *
9540unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9541{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009542 PyUnicodeObject *tmp, *pnew;
9543 Py_ssize_t n;
Guido van Rossume023fe02001-08-30 03:12:59 +00009544
Benjamin Peterson14339b62009-01-31 16:36:08 +00009545 assert(PyType_IsSubtype(type, &PyUnicode_Type));
9546 tmp = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
9547 if (tmp == NULL)
9548 return NULL;
9549 assert(PyUnicode_Check(tmp));
9550 pnew = (PyUnicodeObject *) type->tp_alloc(type, n = tmp->length);
9551 if (pnew == NULL) {
9552 Py_DECREF(tmp);
9553 return NULL;
9554 }
9555 pnew->str = (Py_UNICODE*) PyObject_MALLOC(sizeof(Py_UNICODE) * (n+1));
9556 if (pnew->str == NULL) {
9557 _Py_ForgetReference((PyObject *)pnew);
9558 PyObject_Del(pnew);
9559 Py_DECREF(tmp);
9560 return PyErr_NoMemory();
9561 }
9562 Py_UNICODE_COPY(pnew->str, tmp->str, n+1);
9563 pnew->length = n;
9564 pnew->hash = tmp->hash;
9565 Py_DECREF(tmp);
9566 return (PyObject *)pnew;
Guido van Rossume023fe02001-08-30 03:12:59 +00009567}
9568
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009569PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +00009570 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00009571\n\
Collin Winterd474ce82007-08-07 19:42:11 +00009572Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +00009573encoding defaults to the current default string encoding.\n\
9574errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00009575
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009576static PyObject *unicode_iter(PyObject *seq);
9577
Guido van Rossumd57fd912000-03-10 22:53:23 +00009578PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00009579 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +00009580 "str", /* tp_name */
9581 sizeof(PyUnicodeObject), /* tp_size */
9582 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009583 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009584 (destructor)unicode_dealloc, /* tp_dealloc */
9585 0, /* tp_print */
9586 0, /* tp_getattr */
9587 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00009588 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009589 unicode_repr, /* tp_repr */
9590 &unicode_as_number, /* tp_as_number */
9591 &unicode_as_sequence, /* tp_as_sequence */
9592 &unicode_as_mapping, /* tp_as_mapping */
9593 (hashfunc) unicode_hash, /* tp_hash*/
9594 0, /* tp_call*/
9595 (reprfunc) unicode_str, /* tp_str */
9596 PyObject_GenericGetAttr, /* tp_getattro */
9597 0, /* tp_setattro */
9598 0, /* tp_as_buffer */
9599 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +00009600 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009601 unicode_doc, /* tp_doc */
9602 0, /* tp_traverse */
9603 0, /* tp_clear */
9604 PyUnicode_RichCompare, /* tp_richcompare */
9605 0, /* tp_weaklistoffset */
9606 unicode_iter, /* tp_iter */
9607 0, /* tp_iternext */
9608 unicode_methods, /* tp_methods */
9609 0, /* tp_members */
9610 0, /* tp_getset */
9611 &PyBaseObject_Type, /* tp_base */
9612 0, /* tp_dict */
9613 0, /* tp_descr_get */
9614 0, /* tp_descr_set */
9615 0, /* tp_dictoffset */
9616 0, /* tp_init */
9617 0, /* tp_alloc */
9618 unicode_new, /* tp_new */
9619 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009620};
9621
9622/* Initialize the Unicode implementation */
9623
Thomas Wouters78890102000-07-22 19:25:51 +00009624void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009625{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009626 int i;
9627
Thomas Wouters477c8d52006-05-27 19:21:47 +00009628 /* XXX - move this array to unicodectype.c ? */
9629 Py_UNICODE linebreak[] = {
9630 0x000A, /* LINE FEED */
9631 0x000D, /* CARRIAGE RETURN */
9632 0x001C, /* FILE SEPARATOR */
9633 0x001D, /* GROUP SEPARATOR */
9634 0x001E, /* RECORD SEPARATOR */
9635 0x0085, /* NEXT LINE */
9636 0x2028, /* LINE SEPARATOR */
9637 0x2029, /* PARAGRAPH SEPARATOR */
9638 };
9639
Fred Drakee4315f52000-05-09 19:53:39 +00009640 /* Init the implementation */
Christian Heimes2202f872008-02-06 14:31:34 +00009641 free_list = NULL;
9642 numfree = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009643 unicode_empty = _PyUnicode_New(0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009644 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00009645 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009646
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009647 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00009648 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +00009649 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009650 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +00009651
9652 /* initialize the linebreak bloom filter */
9653 bloom_linebreak = make_bloom_mask(
9654 linebreak, sizeof(linebreak) / sizeof(linebreak[0])
9655 );
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009656
9657 PyType_Ready(&EncodingMapType);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009658}
9659
9660/* Finalize the Unicode implementation */
9661
Christian Heimesa156e092008-02-16 07:38:31 +00009662int
9663PyUnicode_ClearFreeList(void)
9664{
9665 int freelist_size = numfree;
9666 PyUnicodeObject *u;
9667
9668 for (u = free_list; u != NULL;) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009669 PyUnicodeObject *v = u;
9670 u = *(PyUnicodeObject **)u;
9671 if (v->str)
9672 PyObject_DEL(v->str);
9673 Py_XDECREF(v->defenc);
9674 PyObject_Del(v);
9675 numfree--;
Christian Heimesa156e092008-02-16 07:38:31 +00009676 }
9677 free_list = NULL;
9678 assert(numfree == 0);
9679 return freelist_size;
9680}
9681
Guido van Rossumd57fd912000-03-10 22:53:23 +00009682void
Thomas Wouters78890102000-07-22 19:25:51 +00009683_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009684{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009685 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009686
Guido van Rossum4ae8ef82000-10-03 18:09:04 +00009687 Py_XDECREF(unicode_empty);
9688 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +00009689
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009690 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009691 if (unicode_latin1[i]) {
9692 Py_DECREF(unicode_latin1[i]);
9693 unicode_latin1[i] = NULL;
9694 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009695 }
Christian Heimesa156e092008-02-16 07:38:31 +00009696 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +00009697}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00009698
Walter Dörwald16807132007-05-25 13:52:07 +00009699void
9700PyUnicode_InternInPlace(PyObject **p)
9701{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009702 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
9703 PyObject *t;
9704 if (s == NULL || !PyUnicode_Check(s))
9705 Py_FatalError(
9706 "PyUnicode_InternInPlace: unicode strings only please!");
9707 /* If it's a subclass, we don't really know what putting
9708 it in the interned dict might do. */
9709 if (!PyUnicode_CheckExact(s))
9710 return;
9711 if (PyUnicode_CHECK_INTERNED(s))
9712 return;
9713 if (interned == NULL) {
9714 interned = PyDict_New();
9715 if (interned == NULL) {
9716 PyErr_Clear(); /* Don't leave an exception */
9717 return;
9718 }
9719 }
9720 /* It might be that the GetItem call fails even
9721 though the key is present in the dictionary,
9722 namely when this happens during a stack overflow. */
9723 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +00009724 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009725 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +00009726
Benjamin Peterson29060642009-01-31 22:14:21 +00009727 if (t) {
9728 Py_INCREF(t);
9729 Py_DECREF(*p);
9730 *p = t;
9731 return;
9732 }
Walter Dörwald16807132007-05-25 13:52:07 +00009733
Benjamin Peterson14339b62009-01-31 16:36:08 +00009734 PyThreadState_GET()->recursion_critical = 1;
9735 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
9736 PyErr_Clear();
9737 PyThreadState_GET()->recursion_critical = 0;
9738 return;
9739 }
9740 PyThreadState_GET()->recursion_critical = 0;
9741 /* The two references in interned are not counted by refcnt.
9742 The deallocator will take care of this */
9743 Py_REFCNT(s) -= 2;
9744 PyUnicode_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +00009745}
9746
9747void
9748PyUnicode_InternImmortal(PyObject **p)
9749{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009750 PyUnicode_InternInPlace(p);
9751 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
9752 PyUnicode_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
9753 Py_INCREF(*p);
9754 }
Walter Dörwald16807132007-05-25 13:52:07 +00009755}
9756
9757PyObject *
9758PyUnicode_InternFromString(const char *cp)
9759{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009760 PyObject *s = PyUnicode_FromString(cp);
9761 if (s == NULL)
9762 return NULL;
9763 PyUnicode_InternInPlace(&s);
9764 return s;
Walter Dörwald16807132007-05-25 13:52:07 +00009765}
9766
9767void _Py_ReleaseInternedUnicodeStrings(void)
9768{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009769 PyObject *keys;
9770 PyUnicodeObject *s;
9771 Py_ssize_t i, n;
9772 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +00009773
Benjamin Peterson14339b62009-01-31 16:36:08 +00009774 if (interned == NULL || !PyDict_Check(interned))
9775 return;
9776 keys = PyDict_Keys(interned);
9777 if (keys == NULL || !PyList_Check(keys)) {
9778 PyErr_Clear();
9779 return;
9780 }
Walter Dörwald16807132007-05-25 13:52:07 +00009781
Benjamin Peterson14339b62009-01-31 16:36:08 +00009782 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
9783 detector, interned unicode strings are not forcibly deallocated;
9784 rather, we give them their stolen references back, and then clear
9785 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +00009786
Benjamin Peterson14339b62009-01-31 16:36:08 +00009787 n = PyList_GET_SIZE(keys);
9788 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +00009789 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009790 for (i = 0; i < n; i++) {
9791 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
9792 switch (s->state) {
9793 case SSTATE_NOT_INTERNED:
9794 /* XXX Shouldn't happen */
9795 break;
9796 case SSTATE_INTERNED_IMMORTAL:
9797 Py_REFCNT(s) += 1;
9798 immortal_size += s->length;
9799 break;
9800 case SSTATE_INTERNED_MORTAL:
9801 Py_REFCNT(s) += 2;
9802 mortal_size += s->length;
9803 break;
9804 default:
9805 Py_FatalError("Inconsistent interned string state.");
9806 }
9807 s->state = SSTATE_NOT_INTERNED;
9808 }
9809 fprintf(stderr, "total size of all interned strings: "
9810 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
9811 "mortal/immortal\n", mortal_size, immortal_size);
9812 Py_DECREF(keys);
9813 PyDict_Clear(interned);
9814 Py_DECREF(interned);
9815 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +00009816}
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009817
9818
9819/********************* Unicode Iterator **************************/
9820
9821typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009822 PyObject_HEAD
9823 Py_ssize_t it_index;
9824 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009825} unicodeiterobject;
9826
9827static void
9828unicodeiter_dealloc(unicodeiterobject *it)
9829{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009830 _PyObject_GC_UNTRACK(it);
9831 Py_XDECREF(it->it_seq);
9832 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009833}
9834
9835static int
9836unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
9837{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009838 Py_VISIT(it->it_seq);
9839 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009840}
9841
9842static PyObject *
9843unicodeiter_next(unicodeiterobject *it)
9844{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009845 PyUnicodeObject *seq;
9846 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009847
Benjamin Peterson14339b62009-01-31 16:36:08 +00009848 assert(it != NULL);
9849 seq = it->it_seq;
9850 if (seq == NULL)
9851 return NULL;
9852 assert(PyUnicode_Check(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009853
Benjamin Peterson14339b62009-01-31 16:36:08 +00009854 if (it->it_index < PyUnicode_GET_SIZE(seq)) {
9855 item = PyUnicode_FromUnicode(
Benjamin Peterson29060642009-01-31 22:14:21 +00009856 PyUnicode_AS_UNICODE(seq)+it->it_index, 1);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009857 if (item != NULL)
9858 ++it->it_index;
9859 return item;
9860 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009861
Benjamin Peterson14339b62009-01-31 16:36:08 +00009862 Py_DECREF(seq);
9863 it->it_seq = NULL;
9864 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009865}
9866
9867static PyObject *
9868unicodeiter_len(unicodeiterobject *it)
9869{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009870 Py_ssize_t len = 0;
9871 if (it->it_seq)
9872 len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index;
9873 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009874}
9875
9876PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
9877
9878static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009879 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00009880 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +00009881 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009882};
9883
9884PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009885 PyVarObject_HEAD_INIT(&PyType_Type, 0)
9886 "str_iterator", /* tp_name */
9887 sizeof(unicodeiterobject), /* tp_basicsize */
9888 0, /* tp_itemsize */
9889 /* methods */
9890 (destructor)unicodeiter_dealloc, /* tp_dealloc */
9891 0, /* tp_print */
9892 0, /* tp_getattr */
9893 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00009894 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009895 0, /* tp_repr */
9896 0, /* tp_as_number */
9897 0, /* tp_as_sequence */
9898 0, /* tp_as_mapping */
9899 0, /* tp_hash */
9900 0, /* tp_call */
9901 0, /* tp_str */
9902 PyObject_GenericGetAttr, /* tp_getattro */
9903 0, /* tp_setattro */
9904 0, /* tp_as_buffer */
9905 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
9906 0, /* tp_doc */
9907 (traverseproc)unicodeiter_traverse, /* tp_traverse */
9908 0, /* tp_clear */
9909 0, /* tp_richcompare */
9910 0, /* tp_weaklistoffset */
9911 PyObject_SelfIter, /* tp_iter */
9912 (iternextfunc)unicodeiter_next, /* tp_iternext */
9913 unicodeiter_methods, /* tp_methods */
9914 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009915};
9916
9917static PyObject *
9918unicode_iter(PyObject *seq)
9919{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009920 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009921
Benjamin Peterson14339b62009-01-31 16:36:08 +00009922 if (!PyUnicode_Check(seq)) {
9923 PyErr_BadInternalCall();
9924 return NULL;
9925 }
9926 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
9927 if (it == NULL)
9928 return NULL;
9929 it->it_index = 0;
9930 Py_INCREF(seq);
9931 it->it_seq = (PyUnicodeObject *)seq;
9932 _PyObject_GC_TRACK(it);
9933 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009934}
9935
Martin v. Löwis5b222132007-06-10 09:51:05 +00009936size_t
9937Py_UNICODE_strlen(const Py_UNICODE *u)
9938{
9939 int res = 0;
9940 while(*u++)
9941 res++;
9942 return res;
9943}
9944
9945Py_UNICODE*
9946Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
9947{
9948 Py_UNICODE *u = s1;
9949 while ((*u++ = *s2++));
9950 return s1;
9951}
9952
9953Py_UNICODE*
9954Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
9955{
9956 Py_UNICODE *u = s1;
9957 while ((*u++ = *s2++))
9958 if (n-- == 0)
9959 break;
9960 return s1;
9961}
9962
9963int
9964Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
9965{
9966 while (*s1 && *s2 && *s1 == *s2)
9967 s1++, s2++;
9968 if (*s1 && *s2)
9969 return (*s1 < *s2) ? -1 : +1;
9970 if (*s1)
9971 return 1;
9972 if (*s2)
9973 return -1;
9974 return 0;
9975}
9976
9977Py_UNICODE*
9978Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
9979{
9980 const Py_UNICODE *p;
9981 for (p = s; *p; p++)
9982 if (*p == c)
9983 return (Py_UNICODE*)p;
9984 return NULL;
9985}
9986
9987
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009988#ifdef __cplusplus
9989}
9990#endif
9991
9992
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00009993/*
Benjamin Peterson29060642009-01-31 22:14:21 +00009994 Local variables:
9995 c-basic-offset: 4
9996 indent-tabs-mode: nil
9997 End:
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00009998*/