blob: a9ff3b34c424d6884a0811f94c934c117e3167d5 [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
Victor Stinner158701d2010-04-22 19:41:01 +0000162static void raise_encode_exception(PyObject **exceptionObject,
163 const char *encoding,
164 const Py_UNICODE *unicode, Py_ssize_t size,
165 Py_ssize_t startpos, Py_ssize_t endpos,
166 const char *reason);
167
Christian Heimes190d79e2008-01-30 11:58:22 +0000168/* Same for linebreaks */
169static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000170 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000171/* 0x000A, * LINE FEED */
172/* 0x000D, * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000173 0, 0, 1, 0, 0, 1, 0, 0,
174 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000175/* 0x001C, * FILE SEPARATOR */
176/* 0x001D, * GROUP SEPARATOR */
177/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000178 0, 0, 0, 0, 1, 1, 1, 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,
Christian Heimes190d79e2008-01-30 11:58:22 +0000183
Benjamin Peterson14339b62009-01-31 16:36:08 +0000184 0, 0, 0, 0, 0, 0, 0, 0,
185 0, 0, 0, 0, 0, 0, 0, 0,
186 0, 0, 0, 0, 0, 0, 0, 0,
187 0, 0, 0, 0, 0, 0, 0, 0,
188 0, 0, 0, 0, 0, 0, 0, 0,
189 0, 0, 0, 0, 0, 0, 0, 0,
190 0, 0, 0, 0, 0, 0, 0, 0,
191 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000192};
193
194
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000195Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000196PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000197{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000198#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000199 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000200#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000201 /* This is actually an illegal character, so it should
202 not be passed to unichr. */
203 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000204#endif
205}
206
Thomas Wouters477c8d52006-05-27 19:21:47 +0000207/* --- Bloom Filters ----------------------------------------------------- */
208
209/* stuff to implement simple "bloom filters" for Unicode characters.
210 to keep things simple, we use a single bitmask, using the least 5
211 bits from each unicode characters as the bit index. */
212
213/* the linebreak mask is set up by Unicode_Init below */
214
215#define BLOOM_MASK unsigned long
216
217static BLOOM_MASK bloom_linebreak;
218
219#define BLOOM(mask, ch) ((mask & (1 << ((ch) & 0x1F))))
220
Benjamin Peterson29060642009-01-31 22:14:21 +0000221#define BLOOM_LINEBREAK(ch) \
222 ((ch) < 128U ? ascii_linebreak[(ch)] : \
223 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000224
225Py_LOCAL_INLINE(BLOOM_MASK) make_bloom_mask(Py_UNICODE* ptr, Py_ssize_t len)
226{
227 /* calculate simple bloom-style bitmask for a given unicode string */
228
229 long mask;
230 Py_ssize_t i;
231
232 mask = 0;
233 for (i = 0; i < len; i++)
234 mask |= (1 << (ptr[i] & 0x1F));
235
236 return mask;
237}
238
239Py_LOCAL_INLINE(int) unicode_member(Py_UNICODE chr, Py_UNICODE* set, Py_ssize_t setlen)
240{
241 Py_ssize_t i;
242
243 for (i = 0; i < setlen; i++)
244 if (set[i] == chr)
245 return 1;
246
247 return 0;
248}
249
Benjamin Peterson29060642009-01-31 22:14:21 +0000250#define BLOOM_MEMBER(mask, chr, set, setlen) \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000251 BLOOM(mask, chr) && unicode_member(chr, set, setlen)
252
Guido van Rossumd57fd912000-03-10 22:53:23 +0000253/* --- Unicode Object ----------------------------------------------------- */
254
255static
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000256int unicode_resize(register PyUnicodeObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +0000257 Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000258{
259 void *oldstr;
Tim Petersced69f82003-09-16 20:30:58 +0000260
Guido van Rossumfd4b9572000-04-10 13:51:10 +0000261 /* Shortcut if there's nothing much to do. */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000262 if (unicode->length == length)
Benjamin Peterson29060642009-01-31 22:14:21 +0000263 goto reset;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000264
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000265 /* Resizing shared object (unicode_empty or single character
266 objects) in-place is not allowed. Use PyUnicode_Resize()
267 instead ! */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000268
Benjamin Peterson14339b62009-01-31 16:36:08 +0000269 if (unicode == unicode_empty ||
Benjamin Peterson29060642009-01-31 22:14:21 +0000270 (unicode->length == 1 &&
271 unicode->str[0] < 256U &&
272 unicode_latin1[unicode->str[0]] == unicode)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +0000273 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson142957c2008-07-04 19:55:29 +0000274 "can't resize shared str objects");
Guido van Rossumd57fd912000-03-10 22:53:23 +0000275 return -1;
276 }
277
Thomas Wouters477c8d52006-05-27 19:21:47 +0000278 /* We allocate one more byte to make sure the string is Ux0000 terminated.
279 The overallocation is also used by fastsearch, which assumes that it's
280 safe to look at str[length] (without making any assumptions about what
281 it contains). */
282
Guido van Rossumd57fd912000-03-10 22:53:23 +0000283 oldstr = unicode->str;
Christian Heimesb186d002008-03-18 15:15:01 +0000284 unicode->str = PyObject_REALLOC(unicode->str,
Benjamin Peterson29060642009-01-31 22:14:21 +0000285 sizeof(Py_UNICODE) * (length + 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000286 if (!unicode->str) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000287 unicode->str = (Py_UNICODE *)oldstr;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000288 PyErr_NoMemory();
289 return -1;
290 }
291 unicode->str[length] = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000292 unicode->length = length;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000293
Benjamin Peterson29060642009-01-31 22:14:21 +0000294 reset:
Guido van Rossumd57fd912000-03-10 22:53:23 +0000295 /* Reset the object caches */
Marc-André Lemburgbff879c2000-08-03 18:46:08 +0000296 if (unicode->defenc) {
297 Py_DECREF(unicode->defenc);
298 unicode->defenc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000299 }
300 unicode->hash = -1;
Tim Petersced69f82003-09-16 20:30:58 +0000301
Guido van Rossumd57fd912000-03-10 22:53:23 +0000302 return 0;
303}
304
305/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000306 Ux0000 terminated; some code (e.g. new_identifier)
307 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000308
309 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000310 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000311
312*/
313
314static
Martin v. Löwis18e16552006-02-15 17:27:45 +0000315PyUnicodeObject *_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000316{
317 register PyUnicodeObject *unicode;
318
Thomas Wouters477c8d52006-05-27 19:21:47 +0000319 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000320 if (length == 0 && unicode_empty != NULL) {
321 Py_INCREF(unicode_empty);
322 return unicode_empty;
323 }
324
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000325 /* Ensure we won't overflow the size. */
326 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
327 return (PyUnicodeObject *)PyErr_NoMemory();
328 }
329
Guido van Rossumd57fd912000-03-10 22:53:23 +0000330 /* Unicode freelist & memory allocation */
Christian Heimes2202f872008-02-06 14:31:34 +0000331 if (free_list) {
332 unicode = free_list;
333 free_list = *(PyUnicodeObject **)unicode;
334 numfree--;
Benjamin Peterson29060642009-01-31 22:14:21 +0000335 if (unicode->str) {
336 /* Keep-Alive optimization: we only upsize the buffer,
337 never downsize it. */
338 if ((unicode->length < length) &&
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +0000339 unicode_resize(unicode, length) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000340 PyObject_DEL(unicode->str);
341 unicode->str = NULL;
342 }
Benjamin Peterson14339b62009-01-31 16:36:08 +0000343 }
Guido van Rossumad98db12001-06-14 17:52:02 +0000344 else {
Benjamin Peterson29060642009-01-31 22:14:21 +0000345 size_t new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
346 unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
Guido van Rossumad98db12001-06-14 17:52:02 +0000347 }
348 PyObject_INIT(unicode, &PyUnicode_Type);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000349 }
350 else {
Benjamin Peterson29060642009-01-31 22:14:21 +0000351 size_t new_size;
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000352 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000353 if (unicode == NULL)
354 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +0000355 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
356 unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000357 }
358
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000359 if (!unicode->str) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000360 PyErr_NoMemory();
361 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000362 }
Jeremy Hyltond8082792003-09-16 19:41:39 +0000363 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000364 * the caller fails before initializing str -- unicode_resize()
365 * reads str[0], and the Keep-Alive optimization can keep memory
366 * allocated for str alive across a call to unicode_dealloc(unicode).
367 * We don't want unicode_resize to read uninitialized memory in
368 * that case.
369 */
Jeremy Hyltond8082792003-09-16 19:41:39 +0000370 unicode->str[0] = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000371 unicode->str[length] = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000372 unicode->length = length;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000373 unicode->hash = -1;
Walter Dörwald16807132007-05-25 13:52:07 +0000374 unicode->state = 0;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +0000375 unicode->defenc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000376 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000377
Benjamin Peterson29060642009-01-31 22:14:21 +0000378 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000379 /* XXX UNREF/NEWREF interface should be more symmetrical */
380 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000381 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000382 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000383 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000384}
385
386static
Guido van Rossum9475a232001-10-05 20:51:39 +0000387void unicode_dealloc(register PyUnicodeObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000388{
Walter Dörwald16807132007-05-25 13:52:07 +0000389 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000390 case SSTATE_NOT_INTERNED:
391 break;
Walter Dörwald16807132007-05-25 13:52:07 +0000392
Benjamin Peterson29060642009-01-31 22:14:21 +0000393 case SSTATE_INTERNED_MORTAL:
394 /* revive dead object temporarily for DelItem */
395 Py_REFCNT(unicode) = 3;
396 if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
397 Py_FatalError(
398 "deletion of interned string failed");
399 break;
Walter Dörwald16807132007-05-25 13:52:07 +0000400
Benjamin Peterson29060642009-01-31 22:14:21 +0000401 case SSTATE_INTERNED_IMMORTAL:
402 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +0000403
Benjamin Peterson29060642009-01-31 22:14:21 +0000404 default:
405 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +0000406 }
407
Guido van Rossum604ddf82001-12-06 20:03:56 +0000408 if (PyUnicode_CheckExact(unicode) &&
Benjamin Peterson29060642009-01-31 22:14:21 +0000409 numfree < PyUnicode_MAXFREELIST) {
Guido van Rossumfd4b9572000-04-10 13:51:10 +0000410 /* Keep-Alive optimization */
Benjamin Peterson29060642009-01-31 22:14:21 +0000411 if (unicode->length >= KEEPALIVE_SIZE_LIMIT) {
412 PyObject_DEL(unicode->str);
413 unicode->str = NULL;
414 unicode->length = 0;
415 }
416 if (unicode->defenc) {
417 Py_DECREF(unicode->defenc);
418 unicode->defenc = NULL;
419 }
420 /* Add to free list */
Christian Heimes2202f872008-02-06 14:31:34 +0000421 *(PyUnicodeObject **)unicode = free_list;
422 free_list = unicode;
423 numfree++;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000424 }
425 else {
Benjamin Peterson29060642009-01-31 22:14:21 +0000426 PyObject_DEL(unicode->str);
427 Py_XDECREF(unicode->defenc);
428 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000429 }
430}
431
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000432static
433int _PyUnicode_Resize(PyUnicodeObject **unicode, Py_ssize_t length)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000434{
435 register PyUnicodeObject *v;
436
437 /* Argument checks */
438 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000439 PyErr_BadInternalCall();
440 return -1;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000441 }
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000442 v = *unicode;
Christian Heimes90aa7642007-12-19 02:45:37 +0000443 if (v == NULL || !PyUnicode_Check(v) || Py_REFCNT(v) != 1 || length < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000444 PyErr_BadInternalCall();
445 return -1;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000446 }
447
448 /* Resizing unicode_empty and single character objects is not
449 possible since these are being shared. We simply return a fresh
450 copy with the same Unicode content. */
Tim Petersced69f82003-09-16 20:30:58 +0000451 if (v->length != length &&
Benjamin Peterson29060642009-01-31 22:14:21 +0000452 (v == unicode_empty || v->length == 1)) {
453 PyUnicodeObject *w = _PyUnicode_New(length);
454 if (w == NULL)
455 return -1;
456 Py_UNICODE_COPY(w->str, v->str,
457 length < v->length ? length : v->length);
458 Py_DECREF(*unicode);
459 *unicode = w;
460 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000461 }
462
463 /* Note that we don't have to modify *unicode for unshared Unicode
464 objects, since we can modify them in-place. */
465 return unicode_resize(v, length);
466}
467
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000468int PyUnicode_Resize(PyObject **unicode, Py_ssize_t length)
469{
470 return _PyUnicode_Resize((PyUnicodeObject **)unicode, length);
471}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000472
Guido van Rossumd57fd912000-03-10 22:53:23 +0000473PyObject *PyUnicode_FromUnicode(const Py_UNICODE *u,
Benjamin Peterson29060642009-01-31 22:14:21 +0000474 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000475{
476 PyUnicodeObject *unicode;
477
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000478 /* If the Unicode data is known at construction time, we can apply
479 some optimizations which share commonly used objects. */
480 if (u != NULL) {
481
Benjamin Peterson29060642009-01-31 22:14:21 +0000482 /* Optimization for empty strings */
483 if (size == 0 && unicode_empty != NULL) {
484 Py_INCREF(unicode_empty);
485 return (PyObject *)unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000486 }
Benjamin Peterson29060642009-01-31 22:14:21 +0000487
488 /* Single character Unicode objects in the Latin-1 range are
489 shared when using this constructor */
490 if (size == 1 && *u < 256) {
491 unicode = unicode_latin1[*u];
492 if (!unicode) {
493 unicode = _PyUnicode_New(1);
494 if (!unicode)
495 return NULL;
496 unicode->str[0] = *u;
497 unicode_latin1[*u] = unicode;
498 }
499 Py_INCREF(unicode);
500 return (PyObject *)unicode;
501 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000502 }
Tim Petersced69f82003-09-16 20:30:58 +0000503
Guido van Rossumd57fd912000-03-10 22:53:23 +0000504 unicode = _PyUnicode_New(size);
505 if (!unicode)
506 return NULL;
507
508 /* Copy the Unicode data into the new object */
509 if (u != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +0000510 Py_UNICODE_COPY(unicode->str, u, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000511
512 return (PyObject *)unicode;
513}
514
Walter Dörwaldd2034312007-05-18 16:29:38 +0000515PyObject *PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000516{
517 PyUnicodeObject *unicode;
Christian Heimes33fe8092008-04-13 13:53:33 +0000518
Benjamin Peterson14339b62009-01-31 16:36:08 +0000519 if (size < 0) {
520 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +0000521 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +0000522 return NULL;
523 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000524
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000525 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +0000526 some optimizations which share commonly used objects.
527 Also, this means the input must be UTF-8, so fall back to the
528 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000529 if (u != NULL) {
530
Benjamin Peterson29060642009-01-31 22:14:21 +0000531 /* Optimization for empty strings */
532 if (size == 0 && unicode_empty != NULL) {
533 Py_INCREF(unicode_empty);
534 return (PyObject *)unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000535 }
Benjamin Peterson29060642009-01-31 22:14:21 +0000536
537 /* Single characters are shared when using this constructor.
538 Restrict to ASCII, since the input must be UTF-8. */
539 if (size == 1 && Py_CHARMASK(*u) < 128) {
540 unicode = unicode_latin1[Py_CHARMASK(*u)];
541 if (!unicode) {
542 unicode = _PyUnicode_New(1);
543 if (!unicode)
544 return NULL;
545 unicode->str[0] = Py_CHARMASK(*u);
546 unicode_latin1[Py_CHARMASK(*u)] = unicode;
547 }
548 Py_INCREF(unicode);
549 return (PyObject *)unicode;
550 }
Martin v. Löwis9c121062007-08-05 20:26:11 +0000551
552 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000553 }
554
Walter Dörwald55507312007-05-18 13:12:10 +0000555 unicode = _PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000556 if (!unicode)
557 return NULL;
558
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000559 return (PyObject *)unicode;
560}
561
Walter Dörwaldd2034312007-05-18 16:29:38 +0000562PyObject *PyUnicode_FromString(const char *u)
563{
564 size_t size = strlen(u);
565 if (size > PY_SSIZE_T_MAX) {
566 PyErr_SetString(PyExc_OverflowError, "input too long");
567 return NULL;
568 }
569
570 return PyUnicode_FromStringAndSize(u, size);
571}
572
Guido van Rossumd57fd912000-03-10 22:53:23 +0000573#ifdef HAVE_WCHAR_H
574
Mark Dickinson081dfee2009-03-18 14:47:41 +0000575#if (Py_UNICODE_SIZE == 2) && defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4)
576# define CONVERT_WCHAR_TO_SURROGATES
577#endif
578
579#ifdef CONVERT_WCHAR_TO_SURROGATES
580
581/* Here sizeof(wchar_t) is 4 but Py_UNICODE_SIZE == 2, so we need
582 to convert from UTF32 to UTF16. */
583
584PyObject *PyUnicode_FromWideChar(register const wchar_t *w,
585 Py_ssize_t size)
586{
587 PyUnicodeObject *unicode;
588 register Py_ssize_t i;
589 Py_ssize_t alloc;
590 const wchar_t *orig_w;
591
592 if (w == NULL) {
593 if (size == 0)
594 return PyUnicode_FromStringAndSize(NULL, 0);
595 PyErr_BadInternalCall();
596 return NULL;
597 }
598
599 if (size == -1) {
600 size = wcslen(w);
601 }
602
603 alloc = size;
604 orig_w = w;
605 for (i = size; i > 0; i--) {
606 if (*w > 0xFFFF)
607 alloc++;
608 w++;
609 }
610 w = orig_w;
611 unicode = _PyUnicode_New(alloc);
612 if (!unicode)
613 return NULL;
614
615 /* Copy the wchar_t data into the new object */
616 {
617 register Py_UNICODE *u;
618 u = PyUnicode_AS_UNICODE(unicode);
619 for (i = size; i > 0; i--) {
620 if (*w > 0xFFFF) {
621 wchar_t ordinal = *w++;
622 ordinal -= 0x10000;
623 *u++ = 0xD800 | (ordinal >> 10);
624 *u++ = 0xDC00 | (ordinal & 0x3FF);
625 }
626 else
627 *u++ = *w++;
628 }
629 }
630 return (PyObject *)unicode;
631}
632
633#else
634
Guido van Rossumd57fd912000-03-10 22:53:23 +0000635PyObject *PyUnicode_FromWideChar(register const wchar_t *w,
Benjamin Peterson29060642009-01-31 22:14:21 +0000636 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000637{
638 PyUnicodeObject *unicode;
639
640 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +0000641 if (size == 0)
642 return PyUnicode_FromStringAndSize(NULL, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +0000643 PyErr_BadInternalCall();
644 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000645 }
646
Martin v. Löwis790465f2008-04-05 20:41:37 +0000647 if (size == -1) {
648 size = wcslen(w);
649 }
650
Guido van Rossumd57fd912000-03-10 22:53:23 +0000651 unicode = _PyUnicode_New(size);
652 if (!unicode)
653 return NULL;
654
655 /* Copy the wchar_t data into the new object */
656#ifdef HAVE_USABLE_WCHAR_T
657 memcpy(unicode->str, w, size * sizeof(wchar_t));
Tim Petersced69f82003-09-16 20:30:58 +0000658#else
Guido van Rossumd57fd912000-03-10 22:53:23 +0000659 {
Benjamin Peterson29060642009-01-31 22:14:21 +0000660 register Py_UNICODE *u;
661 register Py_ssize_t i;
662 u = PyUnicode_AS_UNICODE(unicode);
663 for (i = size; i > 0; i--)
664 *u++ = *w++;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000665 }
666#endif
667
668 return (PyObject *)unicode;
669}
670
Mark Dickinson081dfee2009-03-18 14:47:41 +0000671#endif /* CONVERT_WCHAR_TO_SURROGATES */
672
673#undef CONVERT_WCHAR_TO_SURROGATES
674
Walter Dörwald346737f2007-05-31 10:44:43 +0000675static void
676makefmt(char *fmt, int longflag, int size_tflag, int zeropad, int width, int precision, char c)
677{
Benjamin Peterson14339b62009-01-31 16:36:08 +0000678 *fmt++ = '%';
679 if (width) {
680 if (zeropad)
681 *fmt++ = '0';
682 fmt += sprintf(fmt, "%d", width);
683 }
684 if (precision)
685 fmt += sprintf(fmt, ".%d", precision);
686 if (longflag)
687 *fmt++ = 'l';
688 else if (size_tflag) {
689 char *f = PY_FORMAT_SIZE_T;
690 while (*f)
691 *fmt++ = *f++;
692 }
693 *fmt++ = c;
694 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +0000695}
696
Walter Dörwaldd2034312007-05-18 16:29:38 +0000697#define appendstring(string) {for (copy = string;*copy;) *s++ = *copy++;}
698
699PyObject *
700PyUnicode_FromFormatV(const char *format, va_list vargs)
701{
Benjamin Peterson14339b62009-01-31 16:36:08 +0000702 va_list count;
703 Py_ssize_t callcount = 0;
704 PyObject **callresults = NULL;
705 PyObject **callresult = NULL;
706 Py_ssize_t n = 0;
707 int width = 0;
708 int precision = 0;
709 int zeropad;
710 const char* f;
711 Py_UNICODE *s;
712 PyObject *string;
713 /* used by sprintf */
714 char buffer[21];
715 /* use abuffer instead of buffer, if we need more space
716 * (which can happen if there's a format specifier with width). */
717 char *abuffer = NULL;
718 char *realbuffer;
719 Py_ssize_t abuffersize = 0;
720 char fmt[60]; /* should be enough for %0width.precisionld */
721 const char *copy;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000722
723#ifdef VA_LIST_IS_ARRAY
Benjamin Peterson14339b62009-01-31 16:36:08 +0000724 Py_MEMCPY(count, vargs, sizeof(va_list));
Walter Dörwaldd2034312007-05-18 16:29:38 +0000725#else
726#ifdef __va_copy
Benjamin Peterson14339b62009-01-31 16:36:08 +0000727 __va_copy(count, vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +0000728#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000729 count = vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000730#endif
731#endif
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000732 /* step 1: count the number of %S/%R/%A/%s format specifications
733 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
734 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
735 * result in an array) */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000736 for (f = format; *f; f++) {
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000737 if (*f == '%') {
738 if (*(f+1)=='%')
739 continue;
740 if (*(f+1)=='S' || *(f+1)=='R' || *(f+1)=='A')
741 ++callcount;
742 while (ISDIGIT((unsigned)*f))
743 width = (width*10) + *f++ - '0';
744 while (*++f && *f != '%' && !ISALPHA((unsigned)*f))
745 ;
746 if (*f == 's')
747 ++callcount;
748 }
Benjamin Peterson14339b62009-01-31 16:36:08 +0000749 }
750 /* step 2: allocate memory for the results of
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000751 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000752 if (callcount) {
753 callresults = PyObject_Malloc(sizeof(PyObject *)*callcount);
754 if (!callresults) {
755 PyErr_NoMemory();
756 return NULL;
757 }
758 callresult = callresults;
759 }
760 /* step 3: figure out how large a buffer we need */
761 for (f = format; *f; f++) {
762 if (*f == '%') {
763 const char* p = f;
764 width = 0;
765 while (ISDIGIT((unsigned)*f))
766 width = (width*10) + *f++ - '0';
767 while (*++f && *f != '%' && !ISALPHA((unsigned)*f))
768 ;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000769
Benjamin Peterson14339b62009-01-31 16:36:08 +0000770 /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
771 * they don't affect the amount of space we reserve.
772 */
773 if ((*f == 'l' || *f == 'z') &&
Benjamin Peterson29060642009-01-31 22:14:21 +0000774 (f[1] == 'd' || f[1] == 'u'))
775 ++f;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000776
Benjamin Peterson14339b62009-01-31 16:36:08 +0000777 switch (*f) {
778 case 'c':
779 (void)va_arg(count, int);
780 /* fall through... */
781 case '%':
782 n++;
783 break;
784 case 'd': case 'u': case 'i': case 'x':
785 (void) va_arg(count, int);
786 /* 20 bytes is enough to hold a 64-bit
787 integer. Decimal takes the most space.
788 This isn't enough for octal.
789 If a width is specified we need more
790 (which we allocate later). */
791 if (width < 20)
792 width = 20;
793 n += width;
794 if (abuffersize < width)
795 abuffersize = width;
796 break;
797 case 's':
798 {
799 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +0000800 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000801 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
802 if (!str)
803 goto fail;
804 n += PyUnicode_GET_SIZE(str);
805 /* Remember the str and switch to the next slot */
806 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000807 break;
808 }
809 case 'U':
810 {
811 PyObject *obj = va_arg(count, PyObject *);
812 assert(obj && PyUnicode_Check(obj));
813 n += PyUnicode_GET_SIZE(obj);
814 break;
815 }
816 case 'V':
817 {
818 PyObject *obj = va_arg(count, PyObject *);
819 const char *str = va_arg(count, const char *);
820 assert(obj || str);
821 assert(!obj || PyUnicode_Check(obj));
822 if (obj)
823 n += PyUnicode_GET_SIZE(obj);
824 else
825 n += strlen(str);
826 break;
827 }
828 case 'S':
829 {
830 PyObject *obj = va_arg(count, PyObject *);
831 PyObject *str;
832 assert(obj);
833 str = PyObject_Str(obj);
834 if (!str)
835 goto fail;
836 n += PyUnicode_GET_SIZE(str);
837 /* Remember the str and switch to the next slot */
838 *callresult++ = str;
839 break;
840 }
841 case 'R':
842 {
843 PyObject *obj = va_arg(count, PyObject *);
844 PyObject *repr;
845 assert(obj);
846 repr = PyObject_Repr(obj);
847 if (!repr)
848 goto fail;
849 n += PyUnicode_GET_SIZE(repr);
850 /* Remember the repr and switch to the next slot */
851 *callresult++ = repr;
852 break;
853 }
854 case 'A':
855 {
856 PyObject *obj = va_arg(count, PyObject *);
857 PyObject *ascii;
858 assert(obj);
859 ascii = PyObject_ASCII(obj);
860 if (!ascii)
861 goto fail;
862 n += PyUnicode_GET_SIZE(ascii);
863 /* Remember the repr and switch to the next slot */
864 *callresult++ = ascii;
865 break;
866 }
867 case 'p':
868 (void) va_arg(count, int);
869 /* maximum 64-bit pointer representation:
870 * 0xffffffffffffffff
871 * so 19 characters is enough.
872 * XXX I count 18 -- what's the extra for?
873 */
874 n += 19;
875 break;
876 default:
877 /* if we stumble upon an unknown
878 formatting code, copy the rest of
879 the format string to the output
880 string. (we cannot just skip the
881 code, since there's no way to know
882 what's in the argument list) */
883 n += strlen(p);
884 goto expand;
885 }
886 } else
887 n++;
888 }
Benjamin Peterson29060642009-01-31 22:14:21 +0000889 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +0000890 if (abuffersize > 20) {
891 abuffer = PyObject_Malloc(abuffersize);
892 if (!abuffer) {
893 PyErr_NoMemory();
894 goto fail;
895 }
896 realbuffer = abuffer;
897 }
898 else
899 realbuffer = buffer;
900 /* step 4: fill the buffer */
901 /* Since we've analyzed how much space we need for the worst case,
902 we don't have to resize the string.
903 There can be no errors beyond this point. */
904 string = PyUnicode_FromUnicode(NULL, n);
905 if (!string)
906 goto fail;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000907
Benjamin Peterson14339b62009-01-31 16:36:08 +0000908 s = PyUnicode_AS_UNICODE(string);
909 callresult = callresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000910
Benjamin Peterson14339b62009-01-31 16:36:08 +0000911 for (f = format; *f; f++) {
912 if (*f == '%') {
913 const char* p = f++;
914 int longflag = 0;
915 int size_tflag = 0;
916 zeropad = (*f == '0');
917 /* parse the width.precision part */
918 width = 0;
919 while (ISDIGIT((unsigned)*f))
920 width = (width*10) + *f++ - '0';
921 precision = 0;
922 if (*f == '.') {
923 f++;
924 while (ISDIGIT((unsigned)*f))
925 precision = (precision*10) + *f++ - '0';
926 }
927 /* handle the long flag, but only for %ld and %lu.
928 others can be added when necessary. */
929 if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) {
930 longflag = 1;
931 ++f;
932 }
933 /* handle the size_t flag. */
934 if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
935 size_tflag = 1;
936 ++f;
937 }
Walter Dörwaldd2034312007-05-18 16:29:38 +0000938
Benjamin Peterson14339b62009-01-31 16:36:08 +0000939 switch (*f) {
940 case 'c':
941 *s++ = va_arg(vargs, int);
942 break;
943 case 'd':
944 makefmt(fmt, longflag, size_tflag, zeropad, width, precision, 'd');
945 if (longflag)
946 sprintf(realbuffer, fmt, va_arg(vargs, long));
947 else if (size_tflag)
948 sprintf(realbuffer, fmt, va_arg(vargs, Py_ssize_t));
949 else
950 sprintf(realbuffer, fmt, va_arg(vargs, int));
951 appendstring(realbuffer);
952 break;
953 case 'u':
954 makefmt(fmt, longflag, size_tflag, zeropad, width, precision, 'u');
955 if (longflag)
956 sprintf(realbuffer, fmt, va_arg(vargs, unsigned long));
957 else if (size_tflag)
958 sprintf(realbuffer, fmt, va_arg(vargs, size_t));
959 else
960 sprintf(realbuffer, fmt, va_arg(vargs, unsigned int));
961 appendstring(realbuffer);
962 break;
963 case 'i':
964 makefmt(fmt, 0, 0, zeropad, width, precision, 'i');
965 sprintf(realbuffer, fmt, va_arg(vargs, int));
966 appendstring(realbuffer);
967 break;
968 case 'x':
969 makefmt(fmt, 0, 0, zeropad, width, precision, 'x');
970 sprintf(realbuffer, fmt, va_arg(vargs, int));
971 appendstring(realbuffer);
972 break;
973 case 's':
974 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000975 /* unused, since we already have the result */
976 (void) va_arg(vargs, char *);
977 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(*callresult),
978 PyUnicode_GET_SIZE(*callresult));
979 s += PyUnicode_GET_SIZE(*callresult);
980 /* We're done with the unicode()/repr() => forget it */
981 Py_DECREF(*callresult);
982 /* switch to next unicode()/repr() result */
983 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000984 break;
985 }
986 case 'U':
987 {
988 PyObject *obj = va_arg(vargs, PyObject *);
989 Py_ssize_t size = PyUnicode_GET_SIZE(obj);
990 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size);
991 s += size;
992 break;
993 }
994 case 'V':
995 {
996 PyObject *obj = va_arg(vargs, PyObject *);
997 const char *str = va_arg(vargs, const char *);
998 if (obj) {
999 Py_ssize_t size = PyUnicode_GET_SIZE(obj);
1000 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size);
1001 s += size;
1002 } else {
1003 appendstring(str);
1004 }
1005 break;
1006 }
1007 case 'S':
1008 case 'R':
1009 {
1010 Py_UNICODE *ucopy;
1011 Py_ssize_t usize;
1012 Py_ssize_t upos;
1013 /* unused, since we already have the result */
1014 (void) va_arg(vargs, PyObject *);
1015 ucopy = PyUnicode_AS_UNICODE(*callresult);
1016 usize = PyUnicode_GET_SIZE(*callresult);
1017 for (upos = 0; upos<usize;)
1018 *s++ = ucopy[upos++];
1019 /* We're done with the unicode()/repr() => forget it */
1020 Py_DECREF(*callresult);
1021 /* switch to next unicode()/repr() result */
1022 ++callresult;
1023 break;
1024 }
1025 case 'p':
1026 sprintf(buffer, "%p", va_arg(vargs, void*));
1027 /* %p is ill-defined: ensure leading 0x. */
1028 if (buffer[1] == 'X')
1029 buffer[1] = 'x';
1030 else if (buffer[1] != 'x') {
1031 memmove(buffer+2, buffer, strlen(buffer)+1);
1032 buffer[0] = '0';
1033 buffer[1] = 'x';
1034 }
1035 appendstring(buffer);
1036 break;
1037 case '%':
1038 *s++ = '%';
1039 break;
1040 default:
1041 appendstring(p);
1042 goto end;
1043 }
1044 } else
1045 *s++ = *f;
1046 }
Walter Dörwaldd2034312007-05-18 16:29:38 +00001047
Benjamin Peterson29060642009-01-31 22:14:21 +00001048 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001049 if (callresults)
1050 PyObject_Free(callresults);
1051 if (abuffer)
1052 PyObject_Free(abuffer);
1053 PyUnicode_Resize(&string, s - PyUnicode_AS_UNICODE(string));
1054 return string;
Benjamin Peterson29060642009-01-31 22:14:21 +00001055 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001056 if (callresults) {
1057 PyObject **callresult2 = callresults;
1058 while (callresult2 < callresult) {
1059 Py_DECREF(*callresult2);
1060 ++callresult2;
1061 }
1062 PyObject_Free(callresults);
1063 }
1064 if (abuffer)
1065 PyObject_Free(abuffer);
1066 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001067}
1068
1069#undef appendstring
1070
1071PyObject *
1072PyUnicode_FromFormat(const char *format, ...)
1073{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001074 PyObject* ret;
1075 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001076
1077#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00001078 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001079#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00001080 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001081#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001082 ret = PyUnicode_FromFormatV(format, vargs);
1083 va_end(vargs);
1084 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001085}
1086
Martin v. Löwis18e16552006-02-15 17:27:45 +00001087Py_ssize_t PyUnicode_AsWideChar(PyUnicodeObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00001088 wchar_t *w,
1089 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001090{
1091 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001092 PyErr_BadInternalCall();
1093 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001094 }
Marc-André Lemburga9cadcd2004-11-22 13:02:31 +00001095
1096 /* If possible, try to copy the 0-termination as well */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001097 if (size > PyUnicode_GET_SIZE(unicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00001098 size = PyUnicode_GET_SIZE(unicode) + 1;
Marc-André Lemburga9cadcd2004-11-22 13:02:31 +00001099
Guido van Rossumd57fd912000-03-10 22:53:23 +00001100#ifdef HAVE_USABLE_WCHAR_T
1101 memcpy(w, unicode->str, size * sizeof(wchar_t));
1102#else
1103 {
Benjamin Peterson29060642009-01-31 22:14:21 +00001104 register Py_UNICODE *u;
1105 register Py_ssize_t i;
1106 u = PyUnicode_AS_UNICODE(unicode);
1107 for (i = size; i > 0; i--)
1108 *w++ = *u++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001109 }
1110#endif
1111
Marc-André Lemburga9cadcd2004-11-22 13:02:31 +00001112 if (size > PyUnicode_GET_SIZE(unicode))
1113 return PyUnicode_GET_SIZE(unicode);
1114 else
Benjamin Peterson29060642009-01-31 22:14:21 +00001115 return size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001116}
1117
1118#endif
1119
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001120PyObject *PyUnicode_FromOrdinal(int ordinal)
1121{
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001122 Py_UNICODE s[2];
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001123
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001124 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001125 PyErr_SetString(PyExc_ValueError,
1126 "chr() arg not in range(0x110000)");
1127 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001128 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001129
1130#ifndef Py_UNICODE_WIDE
1131 if (ordinal > 0xffff) {
1132 ordinal -= 0x10000;
1133 s[0] = 0xD800 | (ordinal >> 10);
1134 s[1] = 0xDC00 | (ordinal & 0x3FF);
1135 return PyUnicode_FromUnicode(s, 2);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001136 }
1137#endif
1138
Hye-Shik Chang40574832004-04-06 07:24:51 +00001139 s[0] = (Py_UNICODE)ordinal;
1140 return PyUnicode_FromUnicode(s, 1);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001141}
1142
Guido van Rossumd57fd912000-03-10 22:53:23 +00001143PyObject *PyUnicode_FromObject(register PyObject *obj)
1144{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001145 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00001146 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001147 if (PyUnicode_CheckExact(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001148 Py_INCREF(obj);
1149 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001150 }
1151 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001152 /* For a Unicode subtype that's not a Unicode object,
1153 return a true Unicode object with the same data. */
1154 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(obj),
1155 PyUnicode_GET_SIZE(obj));
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001156 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001157 PyErr_Format(PyExc_TypeError,
1158 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00001159 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001160 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001161}
1162
1163PyObject *PyUnicode_FromEncodedObject(register PyObject *obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00001164 const char *encoding,
1165 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001166{
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00001167 const char *s = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001168 Py_ssize_t len;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001169 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00001170
Guido van Rossumd57fd912000-03-10 22:53:23 +00001171 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001172 PyErr_BadInternalCall();
1173 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001174 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001175
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001176 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001177 PyErr_SetString(PyExc_TypeError,
1178 "decoding str is not supported");
1179 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001180 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001181
1182 /* Coerce object */
Christian Heimes72b710a2008-05-26 13:28:38 +00001183 if (PyBytes_Check(obj)) {
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001184 s = PyBytes_AS_STRING(obj);
1185 len = PyBytes_GET_SIZE(obj);
1186 }
1187 else if (PyByteArray_Check(obj)) {
1188 s = PyByteArray_AS_STRING(obj);
1189 len = PyByteArray_GET_SIZE(obj);
1190 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001191 else if (PyObject_AsCharBuffer(obj, &s, &len)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001192 /* Overwrite the error message with something more useful in
1193 case of a TypeError. */
1194 if (PyErr_ExceptionMatches(PyExc_TypeError))
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001195 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001196 "coercing to str: need string or buffer, "
1197 "%.80s found",
1198 Py_TYPE(obj)->tp_name);
1199 goto onError;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00001200 }
Tim Petersced69f82003-09-16 20:30:58 +00001201
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001202 /* Convert to Unicode */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001203 if (len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001204 Py_INCREF(unicode_empty);
1205 v = (PyObject *)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001206 }
Tim Petersced69f82003-09-16 20:30:58 +00001207 else
Benjamin Peterson29060642009-01-31 22:14:21 +00001208 v = PyUnicode_Decode(s, len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00001209
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001210 return v;
1211
Benjamin Peterson29060642009-01-31 22:14:21 +00001212 onError:
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001213 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001214}
1215
1216PyObject *PyUnicode_Decode(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00001217 Py_ssize_t size,
1218 const char *encoding,
1219 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001220{
1221 PyObject *buffer = NULL, *unicode;
Guido van Rossumbe801ac2007-10-08 03:32:34 +00001222 Py_buffer info;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001223 char lower[20]; /* Enough for any encoding name we recognize */
1224 char *l;
1225 const char *e;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001226
1227 if (encoding == NULL)
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001228 encoding = PyUnicode_GetDefaultEncoding();
1229
1230 /* Convert encoding to lower case and replace '_' with '-' in order to
1231 catch e.g. UTF_8 */
1232 e = encoding;
1233 l = lower;
1234 while (*e && l < &lower[(sizeof lower) - 2]) {
1235 if (ISUPPER(*e)) {
1236 *l++ = TOLOWER(*e++);
1237 }
1238 else if (*e == '_') {
1239 *l++ = '-';
1240 e++;
1241 }
1242 else {
1243 *l++ = *e++;
1244 }
1245 }
1246 *l = '\0';
Fred Drakee4315f52000-05-09 19:53:39 +00001247
1248 /* Shortcuts for common default encodings */
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001249 if (strcmp(lower, "utf-8") == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001250 return PyUnicode_DecodeUTF8(s, size, errors);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001251 else if ((strcmp(lower, "latin-1") == 0) ||
1252 (strcmp(lower, "iso-8859-1") == 0))
Fred Drakee4315f52000-05-09 19:53:39 +00001253 return PyUnicode_DecodeLatin1(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001254#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001255 else if (strcmp(lower, "mbcs") == 0)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001256 return PyUnicode_DecodeMBCS(s, size, errors);
1257#endif
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001258 else if (strcmp(lower, "ascii") == 0)
Fred Drakee4315f52000-05-09 19:53:39 +00001259 return PyUnicode_DecodeASCII(s, size, errors);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001260 else if (strcmp(lower, "utf-16") == 0)
1261 return PyUnicode_DecodeUTF16(s, size, errors, 0);
1262 else if (strcmp(lower, "utf-32") == 0)
1263 return PyUnicode_DecodeUTF32(s, size, errors, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001264
1265 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00001266 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00001267 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00001268 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00001269 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001270 if (buffer == NULL)
1271 goto onError;
1272 unicode = PyCodec_Decode(buffer, encoding, errors);
1273 if (unicode == NULL)
1274 goto onError;
1275 if (!PyUnicode_Check(unicode)) {
1276 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001277 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00001278 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001279 Py_DECREF(unicode);
1280 goto onError;
1281 }
1282 Py_DECREF(buffer);
1283 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00001284
Benjamin Peterson29060642009-01-31 22:14:21 +00001285 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001286 Py_XDECREF(buffer);
1287 return NULL;
1288}
1289
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001290PyObject *PyUnicode_AsDecodedObject(PyObject *unicode,
1291 const char *encoding,
1292 const char *errors)
1293{
1294 PyObject *v;
1295
1296 if (!PyUnicode_Check(unicode)) {
1297 PyErr_BadArgument();
1298 goto onError;
1299 }
1300
1301 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001302 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001303
1304 /* Decode via the codec registry */
1305 v = PyCodec_Decode(unicode, encoding, errors);
1306 if (v == NULL)
1307 goto onError;
1308 return v;
1309
Benjamin Peterson29060642009-01-31 22:14:21 +00001310 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001311 return NULL;
1312}
1313
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001314PyObject *PyUnicode_AsDecodedUnicode(PyObject *unicode,
1315 const char *encoding,
1316 const char *errors)
1317{
1318 PyObject *v;
1319
1320 if (!PyUnicode_Check(unicode)) {
1321 PyErr_BadArgument();
1322 goto onError;
1323 }
1324
1325 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001326 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001327
1328 /* Decode via the codec registry */
1329 v = PyCodec_Decode(unicode, encoding, errors);
1330 if (v == NULL)
1331 goto onError;
1332 if (!PyUnicode_Check(v)) {
1333 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001334 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001335 Py_TYPE(v)->tp_name);
1336 Py_DECREF(v);
1337 goto onError;
1338 }
1339 return v;
1340
Benjamin Peterson29060642009-01-31 22:14:21 +00001341 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001342 return NULL;
1343}
1344
Guido van Rossumd57fd912000-03-10 22:53:23 +00001345PyObject *PyUnicode_Encode(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00001346 Py_ssize_t size,
1347 const char *encoding,
1348 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001349{
1350 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00001351
Guido van Rossumd57fd912000-03-10 22:53:23 +00001352 unicode = PyUnicode_FromUnicode(s, size);
1353 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001354 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001355 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
1356 Py_DECREF(unicode);
1357 return v;
1358}
1359
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001360PyObject *PyUnicode_AsEncodedObject(PyObject *unicode,
1361 const char *encoding,
1362 const char *errors)
1363{
1364 PyObject *v;
1365
1366 if (!PyUnicode_Check(unicode)) {
1367 PyErr_BadArgument();
1368 goto onError;
1369 }
1370
1371 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001372 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001373
1374 /* Encode via the codec registry */
1375 v = PyCodec_Encode(unicode, encoding, errors);
1376 if (v == NULL)
1377 goto onError;
1378 return v;
1379
Benjamin Peterson29060642009-01-31 22:14:21 +00001380 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001381 return NULL;
1382}
1383
Guido van Rossumd57fd912000-03-10 22:53:23 +00001384PyObject *PyUnicode_AsEncodedString(PyObject *unicode,
1385 const char *encoding,
1386 const char *errors)
1387{
1388 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00001389
Guido van Rossumd57fd912000-03-10 22:53:23 +00001390 if (!PyUnicode_Check(unicode)) {
1391 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001392 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001393 }
Fred Drakee4315f52000-05-09 19:53:39 +00001394
Tim Petersced69f82003-09-16 20:30:58 +00001395 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001396 encoding = PyUnicode_GetDefaultEncoding();
Fred Drakee4315f52000-05-09 19:53:39 +00001397
1398 /* Shortcuts for common default encodings */
1399 if (errors == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001400 if (strcmp(encoding, "utf-8") == 0)
1401 return PyUnicode_AsUTF8String(unicode);
1402 else if (strcmp(encoding, "latin-1") == 0)
1403 return PyUnicode_AsLatin1String(unicode);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001404#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Benjamin Peterson29060642009-01-31 22:14:21 +00001405 else if (strcmp(encoding, "mbcs") == 0)
1406 return PyUnicode_AsMBCSString(unicode);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001407#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00001408 else if (strcmp(encoding, "ascii") == 0)
1409 return PyUnicode_AsASCIIString(unicode);
Christian Heimes6a27efa2008-10-30 21:48:26 +00001410 /* During bootstrap, we may need to find the encodings
1411 package, to load the file system encoding, and require the
1412 file system encoding in order to load the encodings
1413 package.
1414
1415 Break out of this dependency by assuming that the path to
1416 the encodings module is ASCII-only. XXX could try wcstombs
1417 instead, if the file system encoding is the locale's
1418 encoding. */
1419 else if (Py_FileSystemDefaultEncoding &&
1420 strcmp(encoding, Py_FileSystemDefaultEncoding) == 0 &&
1421 !PyThreadState_GET()->interp->codecs_initialized)
Benjamin Peterson29060642009-01-31 22:14:21 +00001422 return PyUnicode_AsASCIIString(unicode);
Fred Drakee4315f52000-05-09 19:53:39 +00001423 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001424
1425 /* Encode via the codec registry */
1426 v = PyCodec_Encode(unicode, encoding, errors);
1427 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001428 return NULL;
1429
1430 /* The normal path */
1431 if (PyBytes_Check(v))
1432 return v;
1433
1434 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001435 if (PyByteArray_Check(v)) {
1436 char msg[100];
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001437 PyObject *b;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001438 PyOS_snprintf(msg, sizeof(msg),
1439 "encoder %s returned buffer instead of bytes",
1440 encoding);
1441 if (PyErr_WarnEx(PyExc_RuntimeWarning, msg, 1) < 0) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001442 Py_DECREF(v);
1443 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001444 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001445
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001446 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
1447 Py_DECREF(v);
1448 return b;
1449 }
1450
1451 PyErr_Format(PyExc_TypeError,
1452 "encoder did not return a bytes object (type=%.400s)",
1453 Py_TYPE(v)->tp_name);
1454 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001455 return NULL;
1456}
1457
1458PyObject *PyUnicode_AsEncodedUnicode(PyObject *unicode,
1459 const char *encoding,
1460 const char *errors)
1461{
1462 PyObject *v;
1463
1464 if (!PyUnicode_Check(unicode)) {
1465 PyErr_BadArgument();
1466 goto onError;
1467 }
1468
1469 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001470 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001471
1472 /* Encode via the codec registry */
1473 v = PyCodec_Encode(unicode, encoding, errors);
1474 if (v == NULL)
1475 goto onError;
1476 if (!PyUnicode_Check(v)) {
1477 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001478 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001479 Py_TYPE(v)->tp_name);
1480 Py_DECREF(v);
1481 goto onError;
1482 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001483 return v;
Tim Petersced69f82003-09-16 20:30:58 +00001484
Benjamin Peterson29060642009-01-31 22:14:21 +00001485 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001486 return NULL;
1487}
1488
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001489PyObject *_PyUnicode_AsDefaultEncodedString(PyObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00001490 const char *errors)
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001491{
1492 PyObject *v = ((PyUnicodeObject *)unicode)->defenc;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001493 if (v)
1494 return v;
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001495 if (errors != NULL)
1496 Py_FatalError("non-NULL encoding in _PyUnicode_AsDefaultEncodedString");
Guido van Rossum98297ee2007-11-06 21:34:58 +00001497 v = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
Guido van Rossum06610092007-08-16 21:02:22 +00001498 PyUnicode_GET_SIZE(unicode),
1499 NULL);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001500 if (!v)
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001501 return NULL;
Guido van Rossume7a0d392007-07-12 07:53:00 +00001502 ((PyUnicodeObject *)unicode)->defenc = v;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001503 return v;
1504}
1505
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001506PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00001507PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001508 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00001509 return PyUnicode_DecodeFSDefaultAndSize(s, size);
1510}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001511
Christian Heimes5894ba72007-11-04 11:43:14 +00001512PyObject*
1513PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
1514{
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001515 /* During the early bootstrapping process, Py_FileSystemDefaultEncoding
1516 can be undefined. If it is case, decode using UTF-8. The following assumes
1517 that Py_FileSystemDefaultEncoding is set to a built-in encoding during the
1518 bootstrapping process where the codecs aren't ready yet.
1519 */
1520 if (Py_FileSystemDefaultEncoding) {
1521#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Christian Heimes5894ba72007-11-04 11:43:14 +00001522 if (strcmp(Py_FileSystemDefaultEncoding, "mbcs") == 0) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001523 return PyUnicode_DecodeMBCS(s, size, "replace");
1524 }
1525#elif defined(__APPLE__)
Christian Heimes5894ba72007-11-04 11:43:14 +00001526 if (strcmp(Py_FileSystemDefaultEncoding, "utf-8") == 0) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001527 return PyUnicode_DecodeUTF8(s, size, "replace");
1528 }
1529#endif
1530 return PyUnicode_Decode(s, size,
1531 Py_FileSystemDefaultEncoding,
1532 "replace");
1533 }
1534 else {
1535 return PyUnicode_DecodeUTF8(s, size, "replace");
1536 }
1537}
1538
Martin v. Löwis011e8422009-05-05 04:43:17 +00001539/* Convert the argument to a bytes object, according to the file
1540 system encoding */
1541
1542int
1543PyUnicode_FSConverter(PyObject* arg, void* addr)
1544{
1545 PyObject *output = NULL;
1546 Py_ssize_t size;
1547 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00001548 if (arg == NULL) {
1549 Py_DECREF(*(PyObject**)addr);
1550 return 1;
1551 }
Martin v. Löwis011e8422009-05-05 04:43:17 +00001552 if (PyBytes_Check(arg) || PyByteArray_Check(arg)) {
1553 output = arg;
1554 Py_INCREF(output);
1555 }
1556 else {
1557 arg = PyUnicode_FromObject(arg);
1558 if (!arg)
1559 return 0;
1560 output = PyUnicode_AsEncodedObject(arg,
1561 Py_FileSystemDefaultEncoding,
Martin v. Löwis43c57782009-05-10 08:15:24 +00001562 "surrogateescape");
Martin v. Löwis011e8422009-05-05 04:43:17 +00001563 Py_DECREF(arg);
1564 if (!output)
1565 return 0;
1566 if (!PyBytes_Check(output)) {
1567 Py_DECREF(output);
1568 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
1569 return 0;
1570 }
1571 }
1572 if (PyBytes_Check(output)) {
1573 size = PyBytes_GET_SIZE(output);
1574 data = PyBytes_AS_STRING(output);
1575 }
1576 else {
1577 size = PyByteArray_GET_SIZE(output);
1578 data = PyByteArray_AS_STRING(output);
1579 }
1580 if (size != strlen(data)) {
1581 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
1582 Py_DECREF(output);
1583 return 0;
1584 }
1585 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00001586 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00001587}
1588
1589
Martin v. Löwis5b222132007-06-10 09:51:05 +00001590char*
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001591_PyUnicode_AsStringAndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00001592{
Christian Heimesf3863112007-11-22 07:46:41 +00001593 PyObject *bytes;
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00001594 if (!PyUnicode_Check(unicode)) {
1595 PyErr_BadArgument();
1596 return NULL;
1597 }
Christian Heimesf3863112007-11-22 07:46:41 +00001598 bytes = _PyUnicode_AsDefaultEncodedString(unicode, NULL);
1599 if (bytes == NULL)
Martin v. Löwis5b222132007-06-10 09:51:05 +00001600 return NULL;
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001601 if (psize != NULL)
Christian Heimes72b710a2008-05-26 13:28:38 +00001602 *psize = PyBytes_GET_SIZE(bytes);
1603 return PyBytes_AS_STRING(bytes);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001604}
1605
1606char*
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001607_PyUnicode_AsString(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001608{
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001609 return _PyUnicode_AsStringAndSize(unicode, NULL);
Martin v. Löwis5b222132007-06-10 09:51:05 +00001610}
1611
Guido van Rossumd57fd912000-03-10 22:53:23 +00001612Py_UNICODE *PyUnicode_AsUnicode(PyObject *unicode)
1613{
1614 if (!PyUnicode_Check(unicode)) {
1615 PyErr_BadArgument();
1616 goto onError;
1617 }
1618 return PyUnicode_AS_UNICODE(unicode);
1619
Benjamin Peterson29060642009-01-31 22:14:21 +00001620 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001621 return NULL;
1622}
1623
Martin v. Löwis18e16552006-02-15 17:27:45 +00001624Py_ssize_t PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001625{
1626 if (!PyUnicode_Check(unicode)) {
1627 PyErr_BadArgument();
1628 goto onError;
1629 }
1630 return PyUnicode_GET_SIZE(unicode);
1631
Benjamin Peterson29060642009-01-31 22:14:21 +00001632 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001633 return -1;
1634}
1635
Thomas Wouters78890102000-07-22 19:25:51 +00001636const char *PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00001637{
1638 return unicode_default_encoding;
1639}
1640
1641int PyUnicode_SetDefaultEncoding(const char *encoding)
1642{
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001643 if (strcmp(encoding, unicode_default_encoding) != 0) {
1644 PyErr_Format(PyExc_ValueError,
1645 "Can only set default encoding to %s",
1646 unicode_default_encoding);
1647 return -1;
1648 }
Fred Drakee4315f52000-05-09 19:53:39 +00001649 return 0;
Fred Drakee4315f52000-05-09 19:53:39 +00001650}
1651
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001652/* error handling callback helper:
1653 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00001654 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001655 and adjust various state variables.
1656 return 0 on success, -1 on error
1657*/
1658
1659static
1660int unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00001661 const char *encoding, const char *reason,
1662 const char **input, const char **inend, Py_ssize_t *startinpos,
1663 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
1664 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001665{
Benjamin Peterson142957c2008-07-04 19:55:29 +00001666 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001667
1668 PyObject *restuple = NULL;
1669 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001670 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00001671 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001672 Py_ssize_t requiredsize;
1673 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001674 Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00001675 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001676 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001677 int res = -1;
1678
1679 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001680 *errorHandler = PyCodec_LookupError(errors);
1681 if (*errorHandler == NULL)
1682 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001683 }
1684
1685 if (*exceptionObject == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00001686 *exceptionObject = PyUnicodeDecodeError_Create(
Benjamin Peterson29060642009-01-31 22:14:21 +00001687 encoding, *input, *inend-*input, *startinpos, *endinpos, reason);
1688 if (*exceptionObject == NULL)
1689 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001690 }
1691 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00001692 if (PyUnicodeDecodeError_SetStart(*exceptionObject, *startinpos))
1693 goto onError;
1694 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, *endinpos))
1695 goto onError;
1696 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
1697 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001698 }
1699
1700 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
1701 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001702 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001703 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001704 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00001705 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001706 }
1707 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00001708 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00001709
1710 /* Copy back the bytes variables, which might have been modified by the
1711 callback */
1712 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
1713 if (!inputobj)
1714 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00001715 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001716 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00001717 }
Christian Heimes72b710a2008-05-26 13:28:38 +00001718 *input = PyBytes_AS_STRING(inputobj);
1719 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00001720 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00001721 /* we can DECREF safely, as the exception has another reference,
1722 so the object won't go away. */
1723 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00001724
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001725 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001726 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00001727 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001728 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
1729 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00001730 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001731
1732 /* need more space? (at least enough for what we
1733 have+the replacement+the rest of the string (starting
1734 at the new input position), so we won't have to check space
1735 when there are no errors in the rest of the string) */
1736 repptr = PyUnicode_AS_UNICODE(repunicode);
1737 repsize = PyUnicode_GET_SIZE(repunicode);
1738 requiredsize = *outpos + repsize + insize-newpos;
1739 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001740 if (requiredsize<2*outsize)
1741 requiredsize = 2*outsize;
1742 if (_PyUnicode_Resize(output, requiredsize) < 0)
1743 goto onError;
1744 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001745 }
1746 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00001747 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001748 Py_UNICODE_COPY(*outptr, repptr, repsize);
1749 *outptr += repsize;
1750 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00001751
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001752 /* we made it! */
1753 res = 0;
1754
Benjamin Peterson29060642009-01-31 22:14:21 +00001755 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001756 Py_XDECREF(restuple);
1757 return res;
1758}
1759
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001760/* --- UTF-7 Codec -------------------------------------------------------- */
1761
Antoine Pitrou244651a2009-05-04 18:56:13 +00001762/* See RFC2152 for details. We encode conservatively and decode liberally. */
1763
1764/* Three simple macros defining base-64. */
1765
1766/* Is c a base-64 character? */
1767
1768#define IS_BASE64(c) \
1769 (((c) >= 'A' && (c) <= 'Z') || \
1770 ((c) >= 'a' && (c) <= 'z') || \
1771 ((c) >= '0' && (c) <= '9') || \
1772 (c) == '+' || (c) == '/')
1773
1774/* given that c is a base-64 character, what is its base-64 value? */
1775
1776#define FROM_BASE64(c) \
1777 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
1778 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
1779 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
1780 (c) == '+' ? 62 : 63)
1781
1782/* What is the base-64 character of the bottom 6 bits of n? */
1783
1784#define TO_BASE64(n) \
1785 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
1786
1787/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
1788 * decoded as itself. We are permissive on decoding; the only ASCII
1789 * byte not decoding to itself is the + which begins a base64
1790 * string. */
1791
1792#define DECODE_DIRECT(c) \
1793 ((c) <= 127 && (c) != '+')
1794
1795/* The UTF-7 encoder treats ASCII characters differently according to
1796 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
1797 * the above). See RFC2152. This array identifies these different
1798 * sets:
1799 * 0 : "Set D"
1800 * alphanumeric and '(),-./:?
1801 * 1 : "Set O"
1802 * !"#$%&*;<=>@[]^_`{|}
1803 * 2 : "whitespace"
1804 * ht nl cr sp
1805 * 3 : special (must be base64 encoded)
1806 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
1807 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001808
Tim Petersced69f82003-09-16 20:30:58 +00001809static
Antoine Pitrou244651a2009-05-04 18:56:13 +00001810char utf7_category[128] = {
1811/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
1812 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
1813/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
1814 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
1815/* sp ! " # $ % & ' ( ) * + , - . / */
1816 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
1817/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1818 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
1819/* @ A B C D E F G H I J K L M N O */
1820 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1821/* P Q R S T U V W X Y Z [ \ ] ^ _ */
1822 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
1823/* ` a b c d e f g h i j k l m n o */
1824 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1825/* p q r s t u v w x y z { | } ~ del */
1826 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001827};
1828
Antoine Pitrou244651a2009-05-04 18:56:13 +00001829/* ENCODE_DIRECT: this character should be encoded as itself. The
1830 * answer depends on whether we are encoding set O as itself, and also
1831 * on whether we are encoding whitespace as itself. RFC2152 makes it
1832 * clear that the answers to these questions vary between
1833 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00001834
Antoine Pitrou244651a2009-05-04 18:56:13 +00001835#define ENCODE_DIRECT(c, directO, directWS) \
1836 ((c) < 128 && (c) > 0 && \
1837 ((utf7_category[(c)] == 0) || \
1838 (directWS && (utf7_category[(c)] == 2)) || \
1839 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001840
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001841PyObject *PyUnicode_DecodeUTF7(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00001842 Py_ssize_t size,
1843 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001844{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00001845 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
1846}
1847
Antoine Pitrou244651a2009-05-04 18:56:13 +00001848/* The decoder. The only state we preserve is our read position,
1849 * i.e. how many characters we have consumed. So if we end in the
1850 * middle of a shift sequence we have to back off the read position
1851 * and the output to the beginning of the sequence, otherwise we lose
1852 * all the shift state (seen bits, number of bits seen, high
1853 * surrogate). */
1854
Christian Heimes5d14c2b2007-11-20 23:38:09 +00001855PyObject *PyUnicode_DecodeUTF7Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00001856 Py_ssize_t size,
1857 const char *errors,
1858 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00001859{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001860 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001861 Py_ssize_t startinpos;
1862 Py_ssize_t endinpos;
1863 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001864 const char *e;
1865 PyUnicodeObject *unicode;
1866 Py_UNICODE *p;
1867 const char *errmsg = "";
1868 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00001869 Py_UNICODE *shiftOutStart;
1870 unsigned int base64bits = 0;
1871 unsigned long base64buffer = 0;
1872 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001873 PyObject *errorHandler = NULL;
1874 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001875
1876 unicode = _PyUnicode_New(size);
1877 if (!unicode)
1878 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00001879 if (size == 0) {
1880 if (consumed)
1881 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001882 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00001883 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001884
1885 p = unicode->str;
Antoine Pitrou244651a2009-05-04 18:56:13 +00001886 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001887 e = s + size;
1888
1889 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001890 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00001891 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00001892 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001893
Antoine Pitrou244651a2009-05-04 18:56:13 +00001894 if (inShift) { /* in a base-64 section */
1895 if (IS_BASE64(ch)) { /* consume a base-64 character */
1896 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
1897 base64bits += 6;
1898 s++;
1899 if (base64bits >= 16) {
1900 /* we have enough bits for a UTF-16 value */
1901 Py_UNICODE outCh = (Py_UNICODE)
1902 (base64buffer >> (base64bits-16));
1903 base64bits -= 16;
1904 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
1905 if (surrogate) {
1906 /* expecting a second surrogate */
1907 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
1908#ifdef Py_UNICODE_WIDE
1909 *p++ = (((surrogate & 0x3FF)<<10)
1910 | (outCh & 0x3FF)) + 0x10000;
1911#else
1912 *p++ = surrogate;
1913 *p++ = outCh;
1914#endif
1915 surrogate = 0;
1916 }
1917 else {
1918 surrogate = 0;
1919 errmsg = "second surrogate missing";
1920 goto utf7Error;
1921 }
1922 }
1923 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
1924 /* first surrogate */
1925 surrogate = outCh;
1926 }
1927 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
1928 errmsg = "unexpected second surrogate";
1929 goto utf7Error;
1930 }
1931 else {
1932 *p++ = outCh;
1933 }
1934 }
1935 }
1936 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001937 inShift = 0;
1938 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00001939 if (surrogate) {
1940 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00001941 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001942 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00001943 if (base64bits > 0) { /* left-over bits */
1944 if (base64bits >= 6) {
1945 /* We've seen at least one base-64 character */
1946 errmsg = "partial character in shift sequence";
1947 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001948 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00001949 else {
1950 /* Some bits remain; they should be zero */
1951 if (base64buffer != 0) {
1952 errmsg = "non-zero padding bits in shift sequence";
1953 goto utf7Error;
1954 }
1955 }
1956 }
1957 if (ch != '-') {
1958 /* '-' is absorbed; other terminating
1959 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001960 *p++ = ch;
1961 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001962 }
1963 }
1964 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001965 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00001966 s++; /* consume '+' */
1967 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001968 s++;
1969 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00001970 }
1971 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001972 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00001973 shiftOutStart = p;
1974 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001975 }
1976 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00001977 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001978 *p++ = ch;
1979 s++;
1980 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00001981 else {
1982 startinpos = s-starts;
1983 s++;
1984 errmsg = "unexpected special character";
1985 goto utf7Error;
1986 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001987 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00001988utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001989 outpos = p-PyUnicode_AS_UNICODE(unicode);
1990 endinpos = s-starts;
1991 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00001992 errors, &errorHandler,
1993 "utf7", errmsg,
1994 &starts, &e, &startinpos, &endinpos, &exc, &s,
1995 &unicode, &outpos, &p))
1996 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001997 }
1998
Antoine Pitrou244651a2009-05-04 18:56:13 +00001999 /* end of string */
2000
2001 if (inShift && !consumed) { /* in shift sequence, no more to follow */
2002 /* if we're in an inconsistent state, that's an error */
2003 if (surrogate ||
2004 (base64bits >= 6) ||
2005 (base64bits > 0 && base64buffer != 0)) {
2006 outpos = p-PyUnicode_AS_UNICODE(unicode);
2007 endinpos = size;
2008 if (unicode_decode_call_errorhandler(
2009 errors, &errorHandler,
2010 "utf7", "unterminated shift sequence",
2011 &starts, &e, &startinpos, &endinpos, &exc, &s,
2012 &unicode, &outpos, &p))
2013 goto onError;
2014 if (s < e)
2015 goto restart;
2016 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002017 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002018
2019 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002020 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00002021 if (inShift) {
2022 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002023 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002024 }
2025 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002026 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002027 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002028 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002029
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00002030 if (_PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002031 goto onError;
2032
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002033 Py_XDECREF(errorHandler);
2034 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002035 return (PyObject *)unicode;
2036
Benjamin Peterson29060642009-01-31 22:14:21 +00002037 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002038 Py_XDECREF(errorHandler);
2039 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002040 Py_DECREF(unicode);
2041 return NULL;
2042}
2043
2044
2045PyObject *PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002046 Py_ssize_t size,
Antoine Pitrou244651a2009-05-04 18:56:13 +00002047 int base64SetO,
2048 int base64WhiteSpace,
Benjamin Peterson29060642009-01-31 22:14:21 +00002049 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002050{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002051 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002052 /* It might be possible to tighten this worst case */
Georg Brandl194da4a2009-08-13 09:34:05 +00002053 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002054 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002055 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002056 unsigned int base64bits = 0;
2057 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002058 char * out;
2059 char * start;
2060
2061 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00002062 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002063
Georg Brandl194da4a2009-08-13 09:34:05 +00002064 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00002065 return PyErr_NoMemory();
2066
Antoine Pitrou244651a2009-05-04 18:56:13 +00002067 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002068 if (v == NULL)
2069 return NULL;
2070
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002071 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002072 for (;i < size; ++i) {
2073 Py_UNICODE ch = s[i];
2074
Antoine Pitrou244651a2009-05-04 18:56:13 +00002075 if (inShift) {
2076 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
2077 /* shifting out */
2078 if (base64bits) { /* output remaining bits */
2079 *out++ = TO_BASE64(base64buffer << (6-base64bits));
2080 base64buffer = 0;
2081 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002082 }
2083 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002084 /* Characters not in the BASE64 set implicitly unshift the sequence
2085 so no '-' is required, except if the character is itself a '-' */
2086 if (IS_BASE64(ch) || ch == '-') {
2087 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002088 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002089 *out++ = (char) ch;
2090 }
2091 else {
2092 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00002093 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002094 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002095 else { /* not in a shift sequence */
2096 if (ch == '+') {
2097 *out++ = '+';
2098 *out++ = '-';
2099 }
2100 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
2101 *out++ = (char) ch;
2102 }
2103 else {
2104 *out++ = '+';
2105 inShift = 1;
2106 goto encode_char;
2107 }
2108 }
2109 continue;
2110encode_char:
2111#ifdef Py_UNICODE_WIDE
2112 if (ch >= 0x10000) {
2113 /* code first surrogate */
2114 base64bits += 16;
2115 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
2116 while (base64bits >= 6) {
2117 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
2118 base64bits -= 6;
2119 }
2120 /* prepare second surrogate */
2121 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
2122 }
2123#endif
2124 base64bits += 16;
2125 base64buffer = (base64buffer << 16) | ch;
2126 while (base64bits >= 6) {
2127 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
2128 base64bits -= 6;
2129 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00002130 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002131 if (base64bits)
2132 *out++= TO_BASE64(base64buffer << (6-base64bits) );
2133 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002134 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002135 if (_PyBytes_Resize(&v, out - start) < 0)
2136 return NULL;
2137 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002138}
2139
Antoine Pitrou244651a2009-05-04 18:56:13 +00002140#undef IS_BASE64
2141#undef FROM_BASE64
2142#undef TO_BASE64
2143#undef DECODE_DIRECT
2144#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002145
Guido van Rossumd57fd912000-03-10 22:53:23 +00002146/* --- UTF-8 Codec -------------------------------------------------------- */
2147
Tim Petersced69f82003-09-16 20:30:58 +00002148static
Guido van Rossumd57fd912000-03-10 22:53:23 +00002149char utf8_code_length[256] = {
2150 /* Map UTF-8 encoded prefix byte to sequence length. zero means
2151 illegal prefix. see RFC 2279 for details */
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 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2155 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2156 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2157 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2158 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2159 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2160 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2161 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2162 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2163 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2164 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2165 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2166 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2167 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 0, 0
2168};
2169
Guido van Rossumd57fd912000-03-10 22:53:23 +00002170PyObject *PyUnicode_DecodeUTF8(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002171 Py_ssize_t size,
2172 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002173{
Walter Dörwald69652032004-09-07 20:24:22 +00002174 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
2175}
2176
Antoine Pitrouab868312009-01-10 15:40:25 +00002177/* Mask to check or force alignment of a pointer to C 'long' boundaries */
2178#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
2179
2180/* Mask to quickly check whether a C 'long' contains a
2181 non-ASCII, UTF8-encoded char. */
2182#if (SIZEOF_LONG == 8)
2183# define ASCII_CHAR_MASK 0x8080808080808080L
2184#elif (SIZEOF_LONG == 4)
2185# define ASCII_CHAR_MASK 0x80808080L
2186#else
2187# error C 'long' size should be either 4 or 8!
2188#endif
2189
Walter Dörwald69652032004-09-07 20:24:22 +00002190PyObject *PyUnicode_DecodeUTF8Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002191 Py_ssize_t size,
2192 const char *errors,
2193 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00002194{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002195 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002196 int n;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002197 Py_ssize_t startinpos;
2198 Py_ssize_t endinpos;
2199 Py_ssize_t outpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00002200 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002201 PyUnicodeObject *unicode;
2202 Py_UNICODE *p;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002203 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002204 PyObject *errorHandler = NULL;
2205 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002206
2207 /* Note: size will always be longer than the resulting Unicode
2208 character count */
2209 unicode = _PyUnicode_New(size);
2210 if (!unicode)
2211 return NULL;
Walter Dörwald69652032004-09-07 20:24:22 +00002212 if (size == 0) {
2213 if (consumed)
2214 *consumed = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002215 return (PyObject *)unicode;
Walter Dörwald69652032004-09-07 20:24:22 +00002216 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002217
2218 /* Unpack UTF-8 encoded data */
2219 p = unicode->str;
2220 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00002221 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002222
2223 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002224 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002225
2226 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00002227 /* Fast path for runs of ASCII characters. Given that common UTF-8
2228 input will consist of an overwhelming majority of ASCII
2229 characters, we try to optimize for this case by checking
2230 as many characters as a C 'long' can contain.
2231 First, check if we can do an aligned read, as most CPUs have
2232 a penalty for unaligned reads.
2233 */
2234 if (!((size_t) s & LONG_PTR_MASK)) {
2235 /* Help register allocation */
2236 register const char *_s = s;
2237 register Py_UNICODE *_p = p;
2238 while (_s < aligned_end) {
2239 /* Read a whole long at a time (either 4 or 8 bytes),
2240 and do a fast unrolled copy if it only contains ASCII
2241 characters. */
2242 unsigned long data = *(unsigned long *) _s;
2243 if (data & ASCII_CHAR_MASK)
2244 break;
2245 _p[0] = (unsigned char) _s[0];
2246 _p[1] = (unsigned char) _s[1];
2247 _p[2] = (unsigned char) _s[2];
2248 _p[3] = (unsigned char) _s[3];
2249#if (SIZEOF_LONG == 8)
2250 _p[4] = (unsigned char) _s[4];
2251 _p[5] = (unsigned char) _s[5];
2252 _p[6] = (unsigned char) _s[6];
2253 _p[7] = (unsigned char) _s[7];
2254#endif
2255 _s += SIZEOF_LONG;
2256 _p += SIZEOF_LONG;
2257 }
2258 s = _s;
2259 p = _p;
2260 if (s == e)
2261 break;
2262 ch = (unsigned char)*s;
2263 }
2264 }
2265
2266 if (ch < 0x80) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002267 *p++ = (Py_UNICODE)ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002268 s++;
2269 continue;
2270 }
2271
2272 n = utf8_code_length[ch];
2273
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002274 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002275 if (consumed)
2276 break;
2277 else {
2278 errmsg = "unexpected end of data";
2279 startinpos = s-starts;
2280 endinpos = size;
2281 goto utf8Error;
2282 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002283 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002284
2285 switch (n) {
2286
2287 case 0:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002288 errmsg = "unexpected code byte";
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 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002294 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00002295 startinpos = s-starts;
2296 endinpos = startinpos+1;
2297 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002298
2299 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002300 if ((s[1] & 0xc0) != 0x80) {
2301 errmsg = "invalid data";
Benjamin Peterson29060642009-01-31 22:14:21 +00002302 startinpos = s-starts;
2303 endinpos = startinpos+2;
2304 goto utf8Error;
2305 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002306 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002307 if (ch < 0x80) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002308 startinpos = s-starts;
2309 endinpos = startinpos+2;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002310 errmsg = "illegal encoding";
Benjamin Peterson29060642009-01-31 22:14:21 +00002311 goto utf8Error;
2312 }
2313 else
2314 *p++ = (Py_UNICODE)ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002315 break;
2316
2317 case 3:
Tim Petersced69f82003-09-16 20:30:58 +00002318 if ((s[1] & 0xc0) != 0x80 ||
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002319 (s[2] & 0xc0) != 0x80) {
2320 errmsg = "invalid data";
Benjamin Peterson29060642009-01-31 22:14:21 +00002321 startinpos = s-starts;
2322 endinpos = startinpos+3;
2323 goto utf8Error;
2324 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002325 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002326 if (ch < 0x0800 || (ch >= 0xd800 && ch <= 0xDFFF)) {
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002327 errmsg = "illegal encoding";
Benjamin Peterson29060642009-01-31 22:14:21 +00002328 startinpos = s-starts;
2329 endinpos = startinpos+3;
2330 goto utf8Error;
2331 }
2332 else
2333 *p++ = (Py_UNICODE)ch;
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002334 break;
2335
2336 case 4:
2337 if ((s[1] & 0xc0) != 0x80 ||
2338 (s[2] & 0xc0) != 0x80 ||
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002339 (s[3] & 0xc0) != 0x80) {
2340 errmsg = "invalid data";
Benjamin Peterson29060642009-01-31 22:14:21 +00002341 startinpos = s-starts;
2342 endinpos = startinpos+4;
2343 goto utf8Error;
2344 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002345 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Benjamin Peterson29060642009-01-31 22:14:21 +00002346 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002347 /* validate and convert to UTF-16 */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002348 if ((ch < 0x10000) /* minimum value allowed for 4
Benjamin Peterson29060642009-01-31 22:14:21 +00002349 byte encoding */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002350 || (ch > 0x10ffff)) /* maximum value allowed for
Benjamin Peterson29060642009-01-31 22:14:21 +00002351 UTF-16 */
2352 {
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002353 errmsg = "illegal encoding";
Benjamin Peterson29060642009-01-31 22:14:21 +00002354 startinpos = s-starts;
2355 endinpos = startinpos+4;
2356 goto utf8Error;
2357 }
Fredrik Lundh8f455852001-06-27 18:59:43 +00002358#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00002359 *p++ = (Py_UNICODE)ch;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002360#else
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002361 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00002362
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002363 /* translate from 10000..10FFFF to 0..FFFF */
2364 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00002365
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002366 /* high surrogate = top 10 bits added to D800 */
2367 *p++ = (Py_UNICODE)(0xD800 + (ch >> 10));
Tim Petersced69f82003-09-16 20:30:58 +00002368
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002369 /* low surrogate = bottom 10 bits added to DC00 */
Fredrik Lundh45714e92001-06-26 16:39:36 +00002370 *p++ = (Py_UNICODE)(0xDC00 + (ch & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002371#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00002372 break;
2373
2374 default:
2375 /* Other sizes are only needed for UCS-4 */
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002376 errmsg = "unsupported Unicode code range";
Benjamin Peterson29060642009-01-31 22:14:21 +00002377 startinpos = s-starts;
2378 endinpos = startinpos+n;
2379 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002380 }
2381 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00002382 continue;
Tim Petersced69f82003-09-16 20:30:58 +00002383
Benjamin Peterson29060642009-01-31 22:14:21 +00002384 utf8Error:
2385 outpos = p-PyUnicode_AS_UNICODE(unicode);
2386 if (unicode_decode_call_errorhandler(
2387 errors, &errorHandler,
2388 "utf8", errmsg,
2389 &starts, &e, &startinpos, &endinpos, &exc, &s,
2390 &unicode, &outpos, &p))
2391 goto onError;
2392 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002393 }
Walter Dörwald69652032004-09-07 20:24:22 +00002394 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00002395 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002396
2397 /* Adjust length */
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00002398 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002399 goto onError;
2400
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002401 Py_XDECREF(errorHandler);
2402 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002403 return (PyObject *)unicode;
2404
Benjamin Peterson29060642009-01-31 22:14:21 +00002405 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002406 Py_XDECREF(errorHandler);
2407 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002408 Py_DECREF(unicode);
2409 return NULL;
2410}
2411
Antoine Pitrouab868312009-01-10 15:40:25 +00002412#undef ASCII_CHAR_MASK
2413
2414
Tim Peters602f7402002-04-27 18:03:26 +00002415/* Allocation strategy: if the string is short, convert into a stack buffer
2416 and allocate exactly as much space needed at the end. Else allocate the
2417 maximum possible needed (4 result bytes per Unicode character), and return
2418 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002419*/
Tim Peters7e3d9612002-04-21 03:26:37 +00002420PyObject *
2421PyUnicode_EncodeUTF8(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002422 Py_ssize_t size,
2423 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002424{
Tim Peters602f7402002-04-27 18:03:26 +00002425#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00002426
Guido van Rossum98297ee2007-11-06 21:34:58 +00002427 Py_ssize_t i; /* index into s of next input byte */
2428 PyObject *result; /* result string object */
2429 char *p; /* next free byte in output buffer */
2430 Py_ssize_t nallocated; /* number of result bytes allocated */
2431 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00002432 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002433 PyObject *errorHandler = NULL;
2434 PyObject *exc = NULL;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00002435
Tim Peters602f7402002-04-27 18:03:26 +00002436 assert(s != NULL);
2437 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002438
Tim Peters602f7402002-04-27 18:03:26 +00002439 if (size <= MAX_SHORT_UNICHARS) {
2440 /* Write into the stack buffer; nallocated can't overflow.
2441 * At the end, we'll allocate exactly as much heap space as it
2442 * turns out we need.
2443 */
2444 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002445 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00002446 p = stackbuf;
2447 }
2448 else {
2449 /* Overallocate on the heap, and give the excess back at the end. */
2450 nallocated = size * 4;
2451 if (nallocated / 4 != size) /* overflow! */
2452 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00002453 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002454 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00002455 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00002456 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00002457 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002458
Tim Peters602f7402002-04-27 18:03:26 +00002459 for (i = 0; i < size;) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002460 Py_UCS4 ch = s[i++];
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002461
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002462 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00002463 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002464 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002465
Guido van Rossumd57fd912000-03-10 22:53:23 +00002466 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00002467 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00002468 *p++ = (char)(0xc0 | (ch >> 6));
2469 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner158701d2010-04-22 19:41:01 +00002470 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002471#ifndef Py_UNICODE_WIDE
Victor Stinner158701d2010-04-22 19:41:01 +00002472 /* Special case: check for high and low surrogate */
2473 if (ch <= 0xDBFF && i != size && 0xDC00 <= s[i] && s[i] <= 0xDFFF) {
2474 Py_UCS4 ch2 = s[i];
2475 /* Combine the two surrogates to form a UCS4 value */
2476 ch = ((ch - 0xD800) << 10 | (ch2 - 0xDC00)) + 0x10000;
2477 i++;
2478
2479 /* Encode UCS4 Unicode ordinals */
2480 *p++ = (char)(0xf0 | (ch >> 18));
2481 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
Tim Peters602f7402002-04-27 18:03:26 +00002482 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2483 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner158701d2010-04-22 19:41:01 +00002484 } else {
Victor Stinner0b79b762010-04-22 20:07:28 +00002485#endif
Victor Stinner158701d2010-04-22 19:41:01 +00002486 Py_ssize_t newpos;
2487 PyObject *rep;
2488 Py_ssize_t repsize, k;
2489 rep = unicode_encode_call_errorhandler
2490 (errors, &errorHandler, "utf-8", "surrogates not allowed",
2491 s, size, &exc, i-1, i, &newpos);
2492 if (!rep)
2493 goto error;
2494
2495 if (PyBytes_Check(rep))
2496 repsize = PyBytes_GET_SIZE(rep);
2497 else
2498 repsize = PyUnicode_GET_SIZE(rep);
2499
2500 if (repsize > 4) {
2501 Py_ssize_t offset;
2502
2503 if (result == NULL)
2504 offset = p - stackbuf;
2505 else
2506 offset = p - PyBytes_AS_STRING(result);
2507
2508 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
2509 /* integer overflow */
2510 PyErr_NoMemory();
2511 goto error;
2512 }
2513 nallocated += repsize - 4;
2514 if (result != NULL) {
2515 if (_PyBytes_Resize(&result, nallocated) < 0)
2516 goto error;
2517 } else {
2518 result = PyBytes_FromStringAndSize(NULL, nallocated);
2519 if (result == NULL)
2520 goto error;
2521 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
2522 }
2523 p = PyBytes_AS_STRING(result) + offset;
2524 }
2525
2526 if (PyBytes_Check(rep)) {
2527 char *prep = PyBytes_AS_STRING(rep);
2528 for(k = repsize; k > 0; k--)
2529 *p++ = *prep++;
2530 } else /* rep is unicode */ {
2531 Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
2532 Py_UNICODE c;
2533
2534 for(k=0; k<repsize; k++) {
2535 c = prep[k];
2536 if (0x80 <= c) {
2537 raise_encode_exception(&exc, "utf-8", s, size,
2538 i-1, i, "surrogates not allowed");
2539 goto error;
2540 }
2541 *p++ = (char)prep[k];
2542 }
2543 }
2544 Py_DECREF(rep);
Victor Stinner0b79b762010-04-22 20:07:28 +00002545#ifndef Py_UNICODE_WIDE
Victor Stinner158701d2010-04-22 19:41:01 +00002546 }
Victor Stinner0b79b762010-04-22 20:07:28 +00002547#endif
Victor Stinner158701d2010-04-22 19:41:01 +00002548 } else if (ch < 0x10000) {
2549 *p++ = (char)(0xe0 | (ch >> 12));
2550 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2551 *p++ = (char)(0x80 | (ch & 0x3f));
2552 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00002553 /* Encode UCS4 Unicode ordinals */
2554 *p++ = (char)(0xf0 | (ch >> 18));
2555 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
2556 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2557 *p++ = (char)(0x80 | (ch & 0x3f));
2558 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002559 }
Tim Peters0eca65c2002-04-21 17:28:06 +00002560
Guido van Rossum98297ee2007-11-06 21:34:58 +00002561 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00002562 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002563 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00002564 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00002565 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00002566 }
2567 else {
Christian Heimesf3863112007-11-22 07:46:41 +00002568 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00002569 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00002570 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00002571 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00002572 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002573 Py_XDECREF(errorHandler);
2574 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002575 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002576 error:
2577 Py_XDECREF(errorHandler);
2578 Py_XDECREF(exc);
2579 Py_XDECREF(result);
2580 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002581
Tim Peters602f7402002-04-27 18:03:26 +00002582#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00002583}
2584
Guido van Rossumd57fd912000-03-10 22:53:23 +00002585PyObject *PyUnicode_AsUTF8String(PyObject *unicode)
2586{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002587 if (!PyUnicode_Check(unicode)) {
2588 PyErr_BadArgument();
2589 return NULL;
2590 }
Barry Warsaw2dd4abf2000-08-18 06:58:15 +00002591 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00002592 PyUnicode_GET_SIZE(unicode),
2593 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002594}
2595
Walter Dörwald41980ca2007-08-16 21:55:45 +00002596/* --- UTF-32 Codec ------------------------------------------------------- */
2597
2598PyObject *
2599PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002600 Py_ssize_t size,
2601 const char *errors,
2602 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00002603{
2604 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
2605}
2606
2607PyObject *
2608PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002609 Py_ssize_t size,
2610 const char *errors,
2611 int *byteorder,
2612 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00002613{
2614 const char *starts = s;
2615 Py_ssize_t startinpos;
2616 Py_ssize_t endinpos;
2617 Py_ssize_t outpos;
2618 PyUnicodeObject *unicode;
2619 Py_UNICODE *p;
2620#ifndef Py_UNICODE_WIDE
2621 int i, pairs;
2622#else
2623 const int pairs = 0;
2624#endif
2625 const unsigned char *q, *e;
2626 int bo = 0; /* assume native ordering by default */
2627 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00002628 /* Offsets from q for retrieving bytes in the right order. */
2629#ifdef BYTEORDER_IS_LITTLE_ENDIAN
2630 int iorder[] = {0, 1, 2, 3};
2631#else
2632 int iorder[] = {3, 2, 1, 0};
2633#endif
2634 PyObject *errorHandler = NULL;
2635 PyObject *exc = NULL;
Guido van Rossum8d991ed2007-08-17 15:41:00 +00002636 /* On narrow builds we split characters outside the BMP into two
2637 codepoints => count how much extra space we need. */
2638#ifndef Py_UNICODE_WIDE
2639 for (i = pairs = 0; i < size/4; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00002640 if (((Py_UCS4 *)s)[i] >= 0x10000)
2641 pairs++;
Guido van Rossum8d991ed2007-08-17 15:41:00 +00002642#endif
Walter Dörwald41980ca2007-08-16 21:55:45 +00002643
2644 /* This might be one to much, because of a BOM */
2645 unicode = _PyUnicode_New((size+3)/4+pairs);
2646 if (!unicode)
2647 return NULL;
2648 if (size == 0)
2649 return (PyObject *)unicode;
2650
2651 /* Unpack UTF-32 encoded data */
2652 p = unicode->str;
2653 q = (unsigned char *)s;
2654 e = q + size;
2655
2656 if (byteorder)
2657 bo = *byteorder;
2658
2659 /* Check for BOM marks (U+FEFF) in the input and adjust current
2660 byte order setting accordingly. In native mode, the leading BOM
2661 mark is skipped, in all other modes, it is copied to the output
2662 stream as-is (giving a ZWNBSP character). */
2663 if (bo == 0) {
2664 if (size >= 4) {
2665 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00002666 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00002667#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00002668 if (bom == 0x0000FEFF) {
2669 q += 4;
2670 bo = -1;
2671 }
2672 else if (bom == 0xFFFE0000) {
2673 q += 4;
2674 bo = 1;
2675 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00002676#else
Benjamin Peterson29060642009-01-31 22:14:21 +00002677 if (bom == 0x0000FEFF) {
2678 q += 4;
2679 bo = 1;
2680 }
2681 else if (bom == 0xFFFE0000) {
2682 q += 4;
2683 bo = -1;
2684 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00002685#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00002686 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00002687 }
2688
2689 if (bo == -1) {
2690 /* force LE */
2691 iorder[0] = 0;
2692 iorder[1] = 1;
2693 iorder[2] = 2;
2694 iorder[3] = 3;
2695 }
2696 else if (bo == 1) {
2697 /* force BE */
2698 iorder[0] = 3;
2699 iorder[1] = 2;
2700 iorder[2] = 1;
2701 iorder[3] = 0;
2702 }
2703
2704 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002705 Py_UCS4 ch;
2706 /* remaining bytes at the end? (size should be divisible by 4) */
2707 if (e-q<4) {
2708 if (consumed)
2709 break;
2710 errmsg = "truncated data";
2711 startinpos = ((const char *)q)-starts;
2712 endinpos = ((const char *)e)-starts;
2713 goto utf32Error;
2714 /* The remaining input chars are ignored if the callback
2715 chooses to skip the input */
2716 }
2717 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
2718 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00002719
Benjamin Peterson29060642009-01-31 22:14:21 +00002720 if (ch >= 0x110000)
2721 {
2722 errmsg = "codepoint not in range(0x110000)";
2723 startinpos = ((const char *)q)-starts;
2724 endinpos = startinpos+4;
2725 goto utf32Error;
2726 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00002727#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00002728 if (ch >= 0x10000)
2729 {
2730 *p++ = 0xD800 | ((ch-0x10000) >> 10);
2731 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
2732 }
2733 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00002734#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00002735 *p++ = ch;
2736 q += 4;
2737 continue;
2738 utf32Error:
2739 outpos = p-PyUnicode_AS_UNICODE(unicode);
2740 if (unicode_decode_call_errorhandler(
2741 errors, &errorHandler,
2742 "utf32", errmsg,
2743 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
2744 &unicode, &outpos, &p))
2745 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002746 }
2747
2748 if (byteorder)
2749 *byteorder = bo;
2750
2751 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00002752 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002753
2754 /* Adjust length */
2755 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
2756 goto onError;
2757
2758 Py_XDECREF(errorHandler);
2759 Py_XDECREF(exc);
2760 return (PyObject *)unicode;
2761
Benjamin Peterson29060642009-01-31 22:14:21 +00002762 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00002763 Py_DECREF(unicode);
2764 Py_XDECREF(errorHandler);
2765 Py_XDECREF(exc);
2766 return NULL;
2767}
2768
2769PyObject *
2770PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002771 Py_ssize_t size,
2772 const char *errors,
2773 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00002774{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002775 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002776 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00002777 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002778#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00002779 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002780#else
2781 const int pairs = 0;
2782#endif
2783 /* Offsets from p for storing byte pairs in the right order. */
2784#ifdef BYTEORDER_IS_LITTLE_ENDIAN
2785 int iorder[] = {0, 1, 2, 3};
2786#else
2787 int iorder[] = {3, 2, 1, 0};
2788#endif
2789
Benjamin Peterson29060642009-01-31 22:14:21 +00002790#define STORECHAR(CH) \
2791 do { \
2792 p[iorder[3]] = ((CH) >> 24) & 0xff; \
2793 p[iorder[2]] = ((CH) >> 16) & 0xff; \
2794 p[iorder[1]] = ((CH) >> 8) & 0xff; \
2795 p[iorder[0]] = (CH) & 0xff; \
2796 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00002797 } while(0)
2798
2799 /* In narrow builds we can output surrogate pairs as one codepoint,
2800 so we need less space. */
2801#ifndef Py_UNICODE_WIDE
2802 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00002803 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
2804 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
2805 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002806#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00002807 nsize = (size - pairs + (byteorder == 0));
2808 bytesize = nsize * 4;
2809 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00002810 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002811 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00002812 if (v == NULL)
2813 return NULL;
2814
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002815 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00002816 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00002817 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00002818 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002819 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002820
2821 if (byteorder == -1) {
2822 /* force LE */
2823 iorder[0] = 0;
2824 iorder[1] = 1;
2825 iorder[2] = 2;
2826 iorder[3] = 3;
2827 }
2828 else if (byteorder == 1) {
2829 /* force BE */
2830 iorder[0] = 3;
2831 iorder[1] = 2;
2832 iorder[2] = 1;
2833 iorder[3] = 0;
2834 }
2835
2836 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002837 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002838#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00002839 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
2840 Py_UCS4 ch2 = *s;
2841 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
2842 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
2843 s++;
2844 size--;
2845 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002846 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00002847#endif
2848 STORECHAR(ch);
2849 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002850
2851 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002852 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002853#undef STORECHAR
2854}
2855
2856PyObject *PyUnicode_AsUTF32String(PyObject *unicode)
2857{
2858 if (!PyUnicode_Check(unicode)) {
2859 PyErr_BadArgument();
2860 return NULL;
2861 }
2862 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00002863 PyUnicode_GET_SIZE(unicode),
2864 NULL,
2865 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00002866}
2867
Guido van Rossumd57fd912000-03-10 22:53:23 +00002868/* --- UTF-16 Codec ------------------------------------------------------- */
2869
Tim Peters772747b2001-08-09 22:21:55 +00002870PyObject *
2871PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002872 Py_ssize_t size,
2873 const char *errors,
2874 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002875{
Walter Dörwald69652032004-09-07 20:24:22 +00002876 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
2877}
2878
Antoine Pitrouab868312009-01-10 15:40:25 +00002879/* Two masks for fast checking of whether a C 'long' may contain
2880 UTF16-encoded surrogate characters. This is an efficient heuristic,
2881 assuming that non-surrogate characters with a code point >= 0x8000 are
2882 rare in most input.
2883 FAST_CHAR_MASK is used when the input is in native byte ordering,
2884 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00002885*/
Antoine Pitrouab868312009-01-10 15:40:25 +00002886#if (SIZEOF_LONG == 8)
2887# define FAST_CHAR_MASK 0x8000800080008000L
2888# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
2889#elif (SIZEOF_LONG == 4)
2890# define FAST_CHAR_MASK 0x80008000L
2891# define SWAPPED_FAST_CHAR_MASK 0x00800080L
2892#else
2893# error C 'long' size should be either 4 or 8!
2894#endif
2895
Walter Dörwald69652032004-09-07 20:24:22 +00002896PyObject *
2897PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002898 Py_ssize_t size,
2899 const char *errors,
2900 int *byteorder,
2901 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00002902{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002903 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002904 Py_ssize_t startinpos;
2905 Py_ssize_t endinpos;
2906 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002907 PyUnicodeObject *unicode;
2908 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00002909 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00002910 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00002911 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002912 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00002913 /* Offsets from q for retrieving byte pairs in the right order. */
2914#ifdef BYTEORDER_IS_LITTLE_ENDIAN
2915 int ihi = 1, ilo = 0;
2916#else
2917 int ihi = 0, ilo = 1;
2918#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002919 PyObject *errorHandler = NULL;
2920 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002921
2922 /* Note: size will always be longer than the resulting Unicode
2923 character count */
2924 unicode = _PyUnicode_New(size);
2925 if (!unicode)
2926 return NULL;
2927 if (size == 0)
2928 return (PyObject *)unicode;
2929
2930 /* Unpack UTF-16 encoded data */
2931 p = unicode->str;
Tim Peters772747b2001-08-09 22:21:55 +00002932 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00002933 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002934
2935 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00002936 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002937
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00002938 /* Check for BOM marks (U+FEFF) in the input and adjust current
2939 byte order setting accordingly. In native mode, the leading BOM
2940 mark is skipped, in all other modes, it is copied to the output
2941 stream as-is (giving a ZWNBSP character). */
2942 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00002943 if (size >= 2) {
2944 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00002945#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00002946 if (bom == 0xFEFF) {
2947 q += 2;
2948 bo = -1;
2949 }
2950 else if (bom == 0xFFFE) {
2951 q += 2;
2952 bo = 1;
2953 }
Tim Petersced69f82003-09-16 20:30:58 +00002954#else
Benjamin Peterson29060642009-01-31 22:14:21 +00002955 if (bom == 0xFEFF) {
2956 q += 2;
2957 bo = 1;
2958 }
2959 else if (bom == 0xFFFE) {
2960 q += 2;
2961 bo = -1;
2962 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00002963#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00002964 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00002965 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002966
Tim Peters772747b2001-08-09 22:21:55 +00002967 if (bo == -1) {
2968 /* force LE */
2969 ihi = 1;
2970 ilo = 0;
2971 }
2972 else if (bo == 1) {
2973 /* force BE */
2974 ihi = 0;
2975 ilo = 1;
2976 }
Antoine Pitrouab868312009-01-10 15:40:25 +00002977#ifdef BYTEORDER_IS_LITTLE_ENDIAN
2978 native_ordering = ilo < ihi;
2979#else
2980 native_ordering = ilo > ihi;
2981#endif
Tim Peters772747b2001-08-09 22:21:55 +00002982
Antoine Pitrouab868312009-01-10 15:40:25 +00002983 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00002984 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002985 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00002986 /* First check for possible aligned read of a C 'long'. Unaligned
2987 reads are more expensive, better to defer to another iteration. */
2988 if (!((size_t) q & LONG_PTR_MASK)) {
2989 /* Fast path for runs of non-surrogate chars. */
2990 register const unsigned char *_q = q;
2991 Py_UNICODE *_p = p;
2992 if (native_ordering) {
2993 /* Native ordering is simple: as long as the input cannot
2994 possibly contain a surrogate char, do an unrolled copy
2995 of several 16-bit code points to the target object.
2996 The non-surrogate check is done on several input bytes
2997 at a time (as many as a C 'long' can contain). */
2998 while (_q < aligned_end) {
2999 unsigned long data = * (unsigned long *) _q;
3000 if (data & FAST_CHAR_MASK)
3001 break;
3002 _p[0] = ((unsigned short *) _q)[0];
3003 _p[1] = ((unsigned short *) _q)[1];
3004#if (SIZEOF_LONG == 8)
3005 _p[2] = ((unsigned short *) _q)[2];
3006 _p[3] = ((unsigned short *) _q)[3];
3007#endif
3008 _q += SIZEOF_LONG;
3009 _p += SIZEOF_LONG / 2;
3010 }
3011 }
3012 else {
3013 /* Byteswapped ordering is similar, but we must decompose
3014 the copy bytewise, and take care of zero'ing out the
3015 upper bytes if the target object is in 32-bit units
3016 (that is, in UCS-4 builds). */
3017 while (_q < aligned_end) {
3018 unsigned long data = * (unsigned long *) _q;
3019 if (data & SWAPPED_FAST_CHAR_MASK)
3020 break;
3021 /* Zero upper bytes in UCS-4 builds */
3022#if (Py_UNICODE_SIZE > 2)
3023 _p[0] = 0;
3024 _p[1] = 0;
3025#if (SIZEOF_LONG == 8)
3026 _p[2] = 0;
3027 _p[3] = 0;
3028#endif
3029#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00003030 /* Issue #4916; UCS-4 builds on big endian machines must
3031 fill the two last bytes of each 4-byte unit. */
3032#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
3033# define OFF 2
3034#else
3035# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00003036#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00003037 ((unsigned char *) _p)[OFF + 1] = _q[0];
3038 ((unsigned char *) _p)[OFF + 0] = _q[1];
3039 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
3040 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
3041#if (SIZEOF_LONG == 8)
3042 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
3043 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
3044 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
3045 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
3046#endif
3047#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00003048 _q += SIZEOF_LONG;
3049 _p += SIZEOF_LONG / 2;
3050 }
3051 }
3052 p = _p;
3053 q = _q;
3054 if (q >= e)
3055 break;
3056 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003057 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003058
Benjamin Peterson14339b62009-01-31 16:36:08 +00003059 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00003060
3061 if (ch < 0xD800 || ch > 0xDFFF) {
3062 *p++ = ch;
3063 continue;
3064 }
3065
3066 /* UTF-16 code pair: */
3067 if (q > e) {
3068 errmsg = "unexpected end of data";
3069 startinpos = (((const char *)q) - 2) - starts;
3070 endinpos = ((const char *)e) + 1 - starts;
3071 goto utf16Error;
3072 }
3073 if (0xD800 <= ch && ch <= 0xDBFF) {
3074 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
3075 q += 2;
3076 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00003077#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003078 *p++ = ch;
3079 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003080#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003081 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003082#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003083 continue;
3084 }
3085 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003086 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00003087 startinpos = (((const char *)q)-4)-starts;
3088 endinpos = startinpos+2;
3089 goto utf16Error;
3090 }
3091
Benjamin Peterson14339b62009-01-31 16:36:08 +00003092 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003093 errmsg = "illegal encoding";
3094 startinpos = (((const char *)q)-2)-starts;
3095 endinpos = startinpos+2;
3096 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003097
Benjamin Peterson29060642009-01-31 22:14:21 +00003098 utf16Error:
3099 outpos = p - PyUnicode_AS_UNICODE(unicode);
3100 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00003101 errors,
3102 &errorHandler,
3103 "utf16", errmsg,
3104 &starts,
3105 (const char **)&e,
3106 &startinpos,
3107 &endinpos,
3108 &exc,
3109 (const char **)&q,
3110 &unicode,
3111 &outpos,
3112 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00003113 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003114 }
Antoine Pitrouab868312009-01-10 15:40:25 +00003115 /* remaining byte at the end? (size should be even) */
3116 if (e == q) {
3117 if (!consumed) {
3118 errmsg = "truncated data";
3119 startinpos = ((const char *)q) - starts;
3120 endinpos = ((const char *)e) + 1 - starts;
3121 outpos = p - PyUnicode_AS_UNICODE(unicode);
3122 if (unicode_decode_call_errorhandler(
3123 errors,
3124 &errorHandler,
3125 "utf16", errmsg,
3126 &starts,
3127 (const char **)&e,
3128 &startinpos,
3129 &endinpos,
3130 &exc,
3131 (const char **)&q,
3132 &unicode,
3133 &outpos,
3134 &p))
3135 goto onError;
3136 /* The remaining input chars are ignored if the callback
3137 chooses to skip the input */
3138 }
3139 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003140
3141 if (byteorder)
3142 *byteorder = bo;
3143
Walter Dörwald69652032004-09-07 20:24:22 +00003144 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00003145 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00003146
Guido van Rossumd57fd912000-03-10 22:53:23 +00003147 /* Adjust length */
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00003148 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003149 goto onError;
3150
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003151 Py_XDECREF(errorHandler);
3152 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003153 return (PyObject *)unicode;
3154
Benjamin Peterson29060642009-01-31 22:14:21 +00003155 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003156 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003157 Py_XDECREF(errorHandler);
3158 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003159 return NULL;
3160}
3161
Antoine Pitrouab868312009-01-10 15:40:25 +00003162#undef FAST_CHAR_MASK
3163#undef SWAPPED_FAST_CHAR_MASK
3164
Tim Peters772747b2001-08-09 22:21:55 +00003165PyObject *
3166PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003167 Py_ssize_t size,
3168 const char *errors,
3169 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003170{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003171 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00003172 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003173 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003174#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003175 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003176#else
3177 const int pairs = 0;
3178#endif
Tim Peters772747b2001-08-09 22:21:55 +00003179 /* Offsets from p for storing byte pairs in the right order. */
3180#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3181 int ihi = 1, ilo = 0;
3182#else
3183 int ihi = 0, ilo = 1;
3184#endif
3185
Benjamin Peterson29060642009-01-31 22:14:21 +00003186#define STORECHAR(CH) \
3187 do { \
3188 p[ihi] = ((CH) >> 8) & 0xff; \
3189 p[ilo] = (CH) & 0xff; \
3190 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00003191 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003192
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003193#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003194 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00003195 if (s[i] >= 0x10000)
3196 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003197#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003198 /* 2 * (size + pairs + (byteorder == 0)) */
3199 if (size > PY_SSIZE_T_MAX ||
3200 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00003201 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003202 nsize = size + pairs + (byteorder == 0);
3203 bytesize = nsize * 2;
3204 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003205 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003206 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003207 if (v == NULL)
3208 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003209
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003210 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003211 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003212 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00003213 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00003214 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00003215
3216 if (byteorder == -1) {
3217 /* force LE */
3218 ihi = 1;
3219 ilo = 0;
3220 }
3221 else if (byteorder == 1) {
3222 /* force BE */
3223 ihi = 0;
3224 ilo = 1;
3225 }
3226
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003227 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003228 Py_UNICODE ch = *s++;
3229 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003230#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003231 if (ch >= 0x10000) {
3232 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
3233 ch = 0xD800 | ((ch-0x10000) >> 10);
3234 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003235#endif
Tim Peters772747b2001-08-09 22:21:55 +00003236 STORECHAR(ch);
3237 if (ch2)
3238 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003239 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003240
3241 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003242 return v;
Tim Peters772747b2001-08-09 22:21:55 +00003243#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00003244}
3245
3246PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
3247{
3248 if (!PyUnicode_Check(unicode)) {
3249 PyErr_BadArgument();
3250 return NULL;
3251 }
3252 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003253 PyUnicode_GET_SIZE(unicode),
3254 NULL,
3255 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003256}
3257
3258/* --- Unicode Escape Codec ----------------------------------------------- */
3259
Fredrik Lundh06d12682001-01-24 07:59:11 +00003260static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00003261
Guido van Rossumd57fd912000-03-10 22:53:23 +00003262PyObject *PyUnicode_DecodeUnicodeEscape(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003263 Py_ssize_t size,
3264 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003265{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003266 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003267 Py_ssize_t startinpos;
3268 Py_ssize_t endinpos;
3269 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003270 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003271 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003272 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003273 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003274 char* message;
3275 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003276 PyObject *errorHandler = NULL;
3277 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003278
Guido van Rossumd57fd912000-03-10 22:53:23 +00003279 /* Escaped strings will always be longer than the resulting
3280 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003281 length after conversion to the true value.
3282 (but if the error callback returns a long replacement string
3283 we'll have to allocate more space) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003284 v = _PyUnicode_New(size);
3285 if (v == NULL)
3286 goto onError;
3287 if (size == 0)
3288 return (PyObject *)v;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003289
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003290 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003291 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003292
Guido van Rossumd57fd912000-03-10 22:53:23 +00003293 while (s < end) {
3294 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00003295 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003296 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003297
3298 /* Non-escape characters are interpreted as Unicode ordinals */
3299 if (*s != '\\') {
Fredrik Lundhccc74732001-02-18 22:13:49 +00003300 *p++ = (unsigned char) *s++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003301 continue;
3302 }
3303
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003304 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003305 /* \ - Escapes */
3306 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003307 c = *s++;
3308 if (s > end)
3309 c = '\0'; /* Invalid after \ */
3310 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003311
Benjamin Peterson29060642009-01-31 22:14:21 +00003312 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003313 case '\n': break;
3314 case '\\': *p++ = '\\'; break;
3315 case '\'': *p++ = '\''; break;
3316 case '\"': *p++ = '\"'; break;
3317 case 'b': *p++ = '\b'; break;
3318 case 'f': *p++ = '\014'; break; /* FF */
3319 case 't': *p++ = '\t'; break;
3320 case 'n': *p++ = '\n'; break;
3321 case 'r': *p++ = '\r'; break;
3322 case 'v': *p++ = '\013'; break; /* VT */
3323 case 'a': *p++ = '\007'; break; /* BEL, not classic C */
3324
Benjamin Peterson29060642009-01-31 22:14:21 +00003325 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003326 case '0': case '1': case '2': case '3':
3327 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003328 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003329 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003330 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003331 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003332 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00003333 }
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003334 *p++ = x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003335 break;
3336
Benjamin Peterson29060642009-01-31 22:14:21 +00003337 /* hex escapes */
3338 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003339 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003340 digits = 2;
3341 message = "truncated \\xXX escape";
3342 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003343
Benjamin Peterson29060642009-01-31 22:14:21 +00003344 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003345 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003346 digits = 4;
3347 message = "truncated \\uXXXX escape";
3348 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003349
Benjamin Peterson29060642009-01-31 22:14:21 +00003350 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00003351 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003352 digits = 8;
3353 message = "truncated \\UXXXXXXXX escape";
3354 hexescape:
3355 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003356 outpos = p-PyUnicode_AS_UNICODE(v);
3357 if (s+digits>end) {
3358 endinpos = size;
3359 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003360 errors, &errorHandler,
3361 "unicodeescape", "end of string in escape sequence",
3362 &starts, &end, &startinpos, &endinpos, &exc, &s,
3363 &v, &outpos, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003364 goto onError;
3365 goto nextByte;
3366 }
3367 for (i = 0; i < digits; ++i) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00003368 c = (unsigned char) s[i];
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003369 if (!ISXDIGIT(c)) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003370 endinpos = (s+i+1)-starts;
3371 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003372 errors, &errorHandler,
3373 "unicodeescape", message,
3374 &starts, &end, &startinpos, &endinpos, &exc, &s,
3375 &v, &outpos, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00003376 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003377 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00003378 }
3379 chr = (chr<<4) & ~0xF;
3380 if (c >= '0' && c <= '9')
3381 chr += c - '0';
3382 else if (c >= 'a' && c <= 'f')
3383 chr += 10 + c - 'a';
3384 else
3385 chr += 10 + c - 'A';
3386 }
3387 s += i;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00003388 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003389 /* _decoding_error will have already written into the
3390 target buffer. */
3391 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003392 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00003393 /* when we get here, chr is a 32-bit unicode character */
3394 if (chr <= 0xffff)
3395 /* UCS-2 character */
3396 *p++ = (Py_UNICODE) chr;
3397 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00003398 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00003399 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00003400#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003401 *p++ = chr;
3402#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00003403 chr -= 0x10000L;
3404 *p++ = 0xD800 + (Py_UNICODE) (chr >> 10);
Fredrik Lundh45714e92001-06-26 16:39:36 +00003405 *p++ = 0xDC00 + (Py_UNICODE) (chr & 0x03FF);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003406#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00003407 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003408 endinpos = s-starts;
3409 outpos = p-PyUnicode_AS_UNICODE(v);
3410 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003411 errors, &errorHandler,
3412 "unicodeescape", "illegal Unicode character",
3413 &starts, &end, &startinpos, &endinpos, &exc, &s,
3414 &v, &outpos, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00003415 goto onError;
3416 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00003417 break;
3418
Benjamin Peterson29060642009-01-31 22:14:21 +00003419 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00003420 case 'N':
3421 message = "malformed \\N character escape";
3422 if (ucnhash_CAPI == NULL) {
3423 /* load the unicode data module */
Benjamin Petersonb173f782009-05-05 22:31:58 +00003424 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00003425 if (ucnhash_CAPI == NULL)
3426 goto ucnhashError;
3427 }
3428 if (*s == '{') {
3429 const char *start = s+1;
3430 /* look for the closing brace */
3431 while (*s != '}' && s < end)
3432 s++;
3433 if (s > start && s < end && *s == '}') {
3434 /* found a name. look it up in the unicode database */
3435 message = "unknown Unicode character name";
3436 s++;
Martin v. Löwis480f1bb2006-03-09 23:38:20 +00003437 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1), &chr))
Fredrik Lundhccc74732001-02-18 22:13:49 +00003438 goto store;
3439 }
3440 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003441 endinpos = s-starts;
3442 outpos = p-PyUnicode_AS_UNICODE(v);
3443 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003444 errors, &errorHandler,
3445 "unicodeescape", message,
3446 &starts, &end, &startinpos, &endinpos, &exc, &s,
3447 &v, &outpos, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00003448 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003449 break;
3450
3451 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00003452 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003453 message = "\\ at end of string";
3454 s--;
3455 endinpos = s-starts;
3456 outpos = p-PyUnicode_AS_UNICODE(v);
3457 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003458 errors, &errorHandler,
3459 "unicodeescape", message,
3460 &starts, &end, &startinpos, &endinpos, &exc, &s,
3461 &v, &outpos, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00003462 goto onError;
3463 }
3464 else {
3465 *p++ = '\\';
3466 *p++ = (unsigned char)s[-1];
3467 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00003468 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003469 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003470 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003471 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003472 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003473 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003474 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00003475 Py_XDECREF(errorHandler);
3476 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003477 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00003478
Benjamin Peterson29060642009-01-31 22:14:21 +00003479 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00003480 PyErr_SetString(
3481 PyExc_UnicodeError,
3482 "\\N escapes not supported (can't load unicodedata module)"
3483 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003484 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003485 Py_XDECREF(errorHandler);
3486 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00003487 return NULL;
3488
Benjamin Peterson29060642009-01-31 22:14:21 +00003489 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003490 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003491 Py_XDECREF(errorHandler);
3492 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003493 return NULL;
3494}
3495
3496/* Return a Unicode-Escape string version of the Unicode object.
3497
3498 If quotes is true, the string is enclosed in u"" or u'' quotes as
3499 appropriate.
3500
3501*/
3502
Thomas Wouters477c8d52006-05-27 19:21:47 +00003503Py_LOCAL_INLINE(const Py_UNICODE *) findchar(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003504 Py_ssize_t size,
3505 Py_UNICODE ch)
Thomas Wouters477c8d52006-05-27 19:21:47 +00003506{
3507 /* like wcschr, but doesn't stop at NULL characters */
3508
3509 while (size-- > 0) {
3510 if (*s == ch)
3511 return s;
3512 s++;
3513 }
3514
3515 return NULL;
3516}
Barry Warsaw51ac5802000-03-20 16:36:48 +00003517
Walter Dörwald79e913e2007-05-12 11:08:06 +00003518static const char *hexdigits = "0123456789abcdef";
3519
3520PyObject *PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003521 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003522{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003523 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003524 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003525
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003526#ifdef Py_UNICODE_WIDE
3527 const Py_ssize_t expandsize = 10;
3528#else
3529 const Py_ssize_t expandsize = 6;
3530#endif
3531
Thomas Wouters89f507f2006-12-13 04:49:30 +00003532 /* XXX(nnorwitz): rather than over-allocating, it would be
3533 better to choose a different scheme. Perhaps scan the
3534 first N-chars of the string and allocate based on that size.
3535 */
3536 /* Initial allocation is based on the longest-possible unichr
3537 escape.
3538
3539 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
3540 unichr, so in this case it's the longest unichr escape. In
3541 narrow (UTF-16) builds this is five chars per source unichr
3542 since there are two unichrs in the surrogate pair, so in narrow
3543 (UTF-16) builds it's not the longest unichr escape.
3544
3545 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
3546 so in the narrow (UTF-16) build case it's the longest unichr
3547 escape.
3548 */
3549
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003550 if (size == 0)
3551 return PyBytes_FromStringAndSize(NULL, 0);
3552
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003553 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003554 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003555
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003556 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00003557 2
3558 + expandsize*size
3559 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003560 if (repr == NULL)
3561 return NULL;
3562
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003563 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003564
Guido van Rossumd57fd912000-03-10 22:53:23 +00003565 while (size-- > 0) {
3566 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00003567
Walter Dörwald79e913e2007-05-12 11:08:06 +00003568 /* Escape backslashes */
3569 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003570 *p++ = '\\';
3571 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00003572 continue;
Tim Petersced69f82003-09-16 20:30:58 +00003573 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00003574
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00003575#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003576 /* Map 21-bit characters to '\U00xxxxxx' */
3577 else if (ch >= 0x10000) {
3578 *p++ = '\\';
3579 *p++ = 'U';
Walter Dörwald79e913e2007-05-12 11:08:06 +00003580 *p++ = hexdigits[(ch >> 28) & 0x0000000F];
3581 *p++ = hexdigits[(ch >> 24) & 0x0000000F];
3582 *p++ = hexdigits[(ch >> 20) & 0x0000000F];
3583 *p++ = hexdigits[(ch >> 16) & 0x0000000F];
3584 *p++ = hexdigits[(ch >> 12) & 0x0000000F];
3585 *p++ = hexdigits[(ch >> 8) & 0x0000000F];
3586 *p++ = hexdigits[(ch >> 4) & 0x0000000F];
3587 *p++ = hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00003588 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003589 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00003590#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003591 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
3592 else if (ch >= 0xD800 && ch < 0xDC00) {
3593 Py_UNICODE ch2;
3594 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00003595
Benjamin Peterson29060642009-01-31 22:14:21 +00003596 ch2 = *s++;
3597 size--;
3598 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
3599 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
3600 *p++ = '\\';
3601 *p++ = 'U';
3602 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
3603 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
3604 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
3605 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
3606 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
3607 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
3608 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
3609 *p++ = hexdigits[ucs & 0x0000000F];
3610 continue;
3611 }
3612 /* Fall through: isolated surrogates are copied as-is */
3613 s--;
3614 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003615 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00003616#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00003617
Guido van Rossumd57fd912000-03-10 22:53:23 +00003618 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00003619 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003620 *p++ = '\\';
3621 *p++ = 'u';
Walter Dörwald79e913e2007-05-12 11:08:06 +00003622 *p++ = hexdigits[(ch >> 12) & 0x000F];
3623 *p++ = hexdigits[(ch >> 8) & 0x000F];
3624 *p++ = hexdigits[(ch >> 4) & 0x000F];
3625 *p++ = hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00003626 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00003627
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00003628 /* Map special whitespace to '\t', \n', '\r' */
3629 else if (ch == '\t') {
3630 *p++ = '\\';
3631 *p++ = 't';
3632 }
3633 else if (ch == '\n') {
3634 *p++ = '\\';
3635 *p++ = 'n';
3636 }
3637 else if (ch == '\r') {
3638 *p++ = '\\';
3639 *p++ = 'r';
3640 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00003641
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00003642 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00003643 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003644 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00003645 *p++ = 'x';
Walter Dörwald79e913e2007-05-12 11:08:06 +00003646 *p++ = hexdigits[(ch >> 4) & 0x000F];
3647 *p++ = hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00003648 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00003649
Guido van Rossumd57fd912000-03-10 22:53:23 +00003650 /* Copy everything else as-is */
3651 else
3652 *p++ = (char) ch;
3653 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003654
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003655 assert(p - PyBytes_AS_STRING(repr) > 0);
3656 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
3657 return NULL;
3658 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003659}
3660
Alexandre Vassalotti2056bed2008-12-27 19:46:35 +00003661PyObject *PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003662{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00003663 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003664 if (!PyUnicode_Check(unicode)) {
3665 PyErr_BadArgument();
3666 return NULL;
3667 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00003668 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
3669 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00003670 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003671}
3672
3673/* --- Raw Unicode Escape Codec ------------------------------------------- */
3674
3675PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003676 Py_ssize_t size,
3677 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003678{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003679 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003680 Py_ssize_t startinpos;
3681 Py_ssize_t endinpos;
3682 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003683 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003684 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003685 const char *end;
3686 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003687 PyObject *errorHandler = NULL;
3688 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00003689
Guido van Rossumd57fd912000-03-10 22:53:23 +00003690 /* Escaped strings will always be longer than the resulting
3691 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003692 length after conversion to the true value. (But decoding error
3693 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003694 v = _PyUnicode_New(size);
3695 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003696 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003697 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003698 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003699 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003700 end = s + size;
3701 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003702 unsigned char c;
3703 Py_UCS4 x;
3704 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003705 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003706
Benjamin Peterson29060642009-01-31 22:14:21 +00003707 /* Non-escape characters are interpreted as Unicode ordinals */
3708 if (*s != '\\') {
3709 *p++ = (unsigned char)*s++;
3710 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003711 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003712 startinpos = s-starts;
3713
3714 /* \u-escapes are only interpreted iff the number of leading
3715 backslashes if odd */
3716 bs = s;
3717 for (;s < end;) {
3718 if (*s != '\\')
3719 break;
3720 *p++ = (unsigned char)*s++;
3721 }
3722 if (((s - bs) & 1) == 0 ||
3723 s >= end ||
3724 (*s != 'u' && *s != 'U')) {
3725 continue;
3726 }
3727 p--;
3728 count = *s=='u' ? 4 : 8;
3729 s++;
3730
3731 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
3732 outpos = p-PyUnicode_AS_UNICODE(v);
3733 for (x = 0, i = 0; i < count; ++i, ++s) {
3734 c = (unsigned char)*s;
3735 if (!ISXDIGIT(c)) {
3736 endinpos = s-starts;
3737 if (unicode_decode_call_errorhandler(
3738 errors, &errorHandler,
3739 "rawunicodeescape", "truncated \\uXXXX",
3740 &starts, &end, &startinpos, &endinpos, &exc, &s,
3741 &v, &outpos, &p))
3742 goto onError;
3743 goto nextByte;
3744 }
3745 x = (x<<4) & ~0xF;
3746 if (c >= '0' && c <= '9')
3747 x += c - '0';
3748 else if (c >= 'a' && c <= 'f')
3749 x += 10 + c - 'a';
3750 else
3751 x += 10 + c - 'A';
3752 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00003753 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00003754 /* UCS-2 character */
3755 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00003756 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003757 /* UCS-4 character. Either store directly, or as
3758 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00003759#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003760 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00003761#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003762 x -= 0x10000L;
3763 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
3764 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00003765#endif
3766 } else {
3767 endinpos = s-starts;
3768 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003769 if (unicode_decode_call_errorhandler(
3770 errors, &errorHandler,
3771 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00003772 &starts, &end, &startinpos, &endinpos, &exc, &s,
3773 &v, &outpos, &p))
3774 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003775 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003776 nextByte:
3777 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003778 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003779 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003780 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003781 Py_XDECREF(errorHandler);
3782 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003783 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00003784
Benjamin Peterson29060642009-01-31 22:14:21 +00003785 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003786 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003787 Py_XDECREF(errorHandler);
3788 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003789 return NULL;
3790}
3791
3792PyObject *PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003793 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003794{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003795 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003796 char *p;
3797 char *q;
3798
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003799#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003800 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003801#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003802 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003803#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00003804
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003805 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003806 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00003807
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003808 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003809 if (repr == NULL)
3810 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00003811 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003812 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003813
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003814 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003815 while (size-- > 0) {
3816 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003817#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003818 /* Map 32-bit characters to '\Uxxxxxxxx' */
3819 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003820 *p++ = '\\';
3821 *p++ = 'U';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00003822 *p++ = hexdigits[(ch >> 28) & 0xf];
3823 *p++ = hexdigits[(ch >> 24) & 0xf];
3824 *p++ = hexdigits[(ch >> 20) & 0xf];
3825 *p++ = hexdigits[(ch >> 16) & 0xf];
3826 *p++ = hexdigits[(ch >> 12) & 0xf];
3827 *p++ = hexdigits[(ch >> 8) & 0xf];
3828 *p++ = hexdigits[(ch >> 4) & 0xf];
3829 *p++ = hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00003830 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003831 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00003832#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003833 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
3834 if (ch >= 0xD800 && ch < 0xDC00) {
3835 Py_UNICODE ch2;
3836 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00003837
Benjamin Peterson29060642009-01-31 22:14:21 +00003838 ch2 = *s++;
3839 size--;
3840 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
3841 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
3842 *p++ = '\\';
3843 *p++ = 'U';
3844 *p++ = hexdigits[(ucs >> 28) & 0xf];
3845 *p++ = hexdigits[(ucs >> 24) & 0xf];
3846 *p++ = hexdigits[(ucs >> 20) & 0xf];
3847 *p++ = hexdigits[(ucs >> 16) & 0xf];
3848 *p++ = hexdigits[(ucs >> 12) & 0xf];
3849 *p++ = hexdigits[(ucs >> 8) & 0xf];
3850 *p++ = hexdigits[(ucs >> 4) & 0xf];
3851 *p++ = hexdigits[ucs & 0xf];
3852 continue;
3853 }
3854 /* Fall through: isolated surrogates are copied as-is */
3855 s--;
3856 size++;
3857 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003858#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003859 /* Map 16-bit characters to '\uxxxx' */
3860 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003861 *p++ = '\\';
3862 *p++ = 'u';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00003863 *p++ = hexdigits[(ch >> 12) & 0xf];
3864 *p++ = hexdigits[(ch >> 8) & 0xf];
3865 *p++ = hexdigits[(ch >> 4) & 0xf];
3866 *p++ = hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00003867 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003868 /* Copy everything else as-is */
3869 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00003870 *p++ = (char) ch;
3871 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003872 size = p - q;
3873
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003874 assert(size > 0);
3875 if (_PyBytes_Resize(&repr, size) < 0)
3876 return NULL;
3877 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003878}
3879
3880PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
3881{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00003882 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003883 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00003884 PyErr_BadArgument();
3885 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003886 }
Walter Dörwald711005d2007-05-12 12:03:26 +00003887 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
3888 PyUnicode_GET_SIZE(unicode));
3889
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00003890 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003891}
3892
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003893/* --- Unicode Internal Codec ------------------------------------------- */
3894
3895PyObject *_PyUnicode_DecodeUnicodeInternal(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003896 Py_ssize_t size,
3897 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003898{
3899 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003900 Py_ssize_t startinpos;
3901 Py_ssize_t endinpos;
3902 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003903 PyUnicodeObject *v;
3904 Py_UNICODE *p;
3905 const char *end;
3906 const char *reason;
3907 PyObject *errorHandler = NULL;
3908 PyObject *exc = NULL;
3909
Neal Norwitzd43069c2006-01-08 01:12:10 +00003910#ifdef Py_UNICODE_WIDE
3911 Py_UNICODE unimax = PyUnicode_GetMax();
3912#endif
3913
Thomas Wouters89f507f2006-12-13 04:49:30 +00003914 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003915 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
3916 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003917 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003918 if (PyUnicode_GetSize((PyObject *)v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003919 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003920 p = PyUnicode_AS_UNICODE(v);
3921 end = s + size;
3922
3923 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00003924 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003925 /* We have to sanity check the raw data, otherwise doom looms for
3926 some malformed UCS-4 data. */
3927 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00003928#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003929 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00003930#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003931 end-s < Py_UNICODE_SIZE
3932 )
Benjamin Peterson29060642009-01-31 22:14:21 +00003933 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003934 startinpos = s - starts;
3935 if (end-s < Py_UNICODE_SIZE) {
3936 endinpos = end-starts;
3937 reason = "truncated input";
3938 }
3939 else {
3940 endinpos = s - starts + Py_UNICODE_SIZE;
3941 reason = "illegal code point (> 0x10FFFF)";
3942 }
3943 outpos = p - PyUnicode_AS_UNICODE(v);
3944 if (unicode_decode_call_errorhandler(
3945 errors, &errorHandler,
3946 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00003947 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00003948 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003949 goto onError;
3950 }
3951 }
3952 else {
3953 p++;
3954 s += Py_UNICODE_SIZE;
3955 }
3956 }
3957
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003958 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003959 goto onError;
3960 Py_XDECREF(errorHandler);
3961 Py_XDECREF(exc);
3962 return (PyObject *)v;
3963
Benjamin Peterson29060642009-01-31 22:14:21 +00003964 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00003965 Py_XDECREF(v);
3966 Py_XDECREF(errorHandler);
3967 Py_XDECREF(exc);
3968 return NULL;
3969}
3970
Guido van Rossumd57fd912000-03-10 22:53:23 +00003971/* --- Latin-1 Codec ------------------------------------------------------ */
3972
3973PyObject *PyUnicode_DecodeLatin1(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003974 Py_ssize_t size,
3975 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003976{
3977 PyUnicodeObject *v;
3978 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00003979 const char *e, *unrolled_end;
Tim Petersced69f82003-09-16 20:30:58 +00003980
Guido van Rossumd57fd912000-03-10 22:53:23 +00003981 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003982 if (size == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003983 Py_UNICODE r = *(unsigned char*)s;
3984 return PyUnicode_FromUnicode(&r, 1);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00003985 }
3986
Guido van Rossumd57fd912000-03-10 22:53:23 +00003987 v = _PyUnicode_New(size);
3988 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003989 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003990 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003991 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003992 p = PyUnicode_AS_UNICODE(v);
Antoine Pitrouab868312009-01-10 15:40:25 +00003993 e = s + size;
3994 /* Unrolling the copy makes it much faster by reducing the looping
3995 overhead. This is similar to what many memcpy() implementations do. */
3996 unrolled_end = e - 4;
3997 while (s < unrolled_end) {
3998 p[0] = (unsigned char) s[0];
3999 p[1] = (unsigned char) s[1];
4000 p[2] = (unsigned char) s[2];
4001 p[3] = (unsigned char) s[3];
4002 s += 4;
4003 p += 4;
4004 }
4005 while (s < e)
4006 *p++ = (unsigned char) *s++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004007 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004008
Benjamin Peterson29060642009-01-31 22:14:21 +00004009 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004010 Py_XDECREF(v);
4011 return NULL;
4012}
4013
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004014/* create or adjust a UnicodeEncodeError */
4015static void make_encode_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004016 const char *encoding,
4017 const Py_UNICODE *unicode, Py_ssize_t size,
4018 Py_ssize_t startpos, Py_ssize_t endpos,
4019 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004020{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004021 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004022 *exceptionObject = PyUnicodeEncodeError_Create(
4023 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004024 }
4025 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004026 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
4027 goto onError;
4028 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
4029 goto onError;
4030 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
4031 goto onError;
4032 return;
4033 onError:
4034 Py_DECREF(*exceptionObject);
4035 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004036 }
4037}
4038
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004039/* raises a UnicodeEncodeError */
4040static void raise_encode_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004041 const char *encoding,
4042 const Py_UNICODE *unicode, Py_ssize_t size,
4043 Py_ssize_t startpos, Py_ssize_t endpos,
4044 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004045{
4046 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004047 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004048 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004049 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004050}
4051
4052/* error handling callback helper:
4053 build arguments, call the callback and check the arguments,
4054 put the result into newpos and return the replacement string, which
4055 has to be freed by the caller */
4056static PyObject *unicode_encode_call_errorhandler(const char *errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00004057 PyObject **errorHandler,
4058 const char *encoding, const char *reason,
4059 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
4060 Py_ssize_t startpos, Py_ssize_t endpos,
4061 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004062{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004063 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004064
4065 PyObject *restuple;
4066 PyObject *resunicode;
4067
4068 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004069 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004070 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004071 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004072 }
4073
4074 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004075 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004076 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004077 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004078
4079 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00004080 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004081 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004082 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004083 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004084 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004085 Py_DECREF(restuple);
4086 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004087 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004088 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00004089 &resunicode, newpos)) {
4090 Py_DECREF(restuple);
4091 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004092 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004093 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
4094 PyErr_SetString(PyExc_TypeError, &argparse[3]);
4095 Py_DECREF(restuple);
4096 return NULL;
4097 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004098 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004099 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004100 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004101 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
4102 Py_DECREF(restuple);
4103 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004104 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004105 Py_INCREF(resunicode);
4106 Py_DECREF(restuple);
4107 return resunicode;
4108}
4109
4110static PyObject *unicode_encode_ucs1(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004111 Py_ssize_t size,
4112 const char *errors,
4113 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004114{
4115 /* output object */
4116 PyObject *res;
4117 /* pointers to the beginning and end+1 of input */
4118 const Py_UNICODE *startp = p;
4119 const Py_UNICODE *endp = p + size;
4120 /* pointer to the beginning of the unencodable characters */
4121 /* const Py_UNICODE *badp = NULL; */
4122 /* pointer into the output */
4123 char *str;
4124 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00004125 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004126 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
4127 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004128 PyObject *errorHandler = NULL;
4129 PyObject *exc = NULL;
4130 /* the following variable is used for caching string comparisons
4131 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
4132 int known_errorHandler = -1;
4133
4134 /* allocate enough for a simple encoding without
4135 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00004136 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00004137 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004138 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004139 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00004140 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004141 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004142 ressize = size;
4143
4144 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004145 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004146
Benjamin Peterson29060642009-01-31 22:14:21 +00004147 /* can we encode this? */
4148 if (c<limit) {
4149 /* no overflow check, because we know that the space is enough */
4150 *str++ = (char)c;
4151 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004152 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004153 else {
4154 Py_ssize_t unicodepos = p-startp;
4155 Py_ssize_t requiredsize;
4156 PyObject *repunicode;
4157 Py_ssize_t repsize;
4158 Py_ssize_t newpos;
4159 Py_ssize_t respos;
4160 Py_UNICODE *uni2;
4161 /* startpos for collecting unencodable chars */
4162 const Py_UNICODE *collstart = p;
4163 const Py_UNICODE *collend = p;
4164 /* find all unecodable characters */
4165 while ((collend < endp) && ((*collend)>=limit))
4166 ++collend;
4167 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
4168 if (known_errorHandler==-1) {
4169 if ((errors==NULL) || (!strcmp(errors, "strict")))
4170 known_errorHandler = 1;
4171 else if (!strcmp(errors, "replace"))
4172 known_errorHandler = 2;
4173 else if (!strcmp(errors, "ignore"))
4174 known_errorHandler = 3;
4175 else if (!strcmp(errors, "xmlcharrefreplace"))
4176 known_errorHandler = 4;
4177 else
4178 known_errorHandler = 0;
4179 }
4180 switch (known_errorHandler) {
4181 case 1: /* strict */
4182 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
4183 goto onError;
4184 case 2: /* replace */
4185 while (collstart++<collend)
4186 *str++ = '?'; /* fall through */
4187 case 3: /* ignore */
4188 p = collend;
4189 break;
4190 case 4: /* xmlcharrefreplace */
4191 respos = str - PyBytes_AS_STRING(res);
4192 /* determine replacement size (temporarily (mis)uses p) */
4193 for (p = collstart, repsize = 0; p < collend; ++p) {
4194 if (*p<10)
4195 repsize += 2+1+1;
4196 else if (*p<100)
4197 repsize += 2+2+1;
4198 else if (*p<1000)
4199 repsize += 2+3+1;
4200 else if (*p<10000)
4201 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00004202#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004203 else
4204 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00004205#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004206 else if (*p<100000)
4207 repsize += 2+5+1;
4208 else if (*p<1000000)
4209 repsize += 2+6+1;
4210 else
4211 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004212#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004213 }
4214 requiredsize = respos+repsize+(endp-collend);
4215 if (requiredsize > ressize) {
4216 if (requiredsize<2*ressize)
4217 requiredsize = 2*ressize;
4218 if (_PyBytes_Resize(&res, requiredsize))
4219 goto onError;
4220 str = PyBytes_AS_STRING(res) + respos;
4221 ressize = requiredsize;
4222 }
4223 /* generate replacement (temporarily (mis)uses p) */
4224 for (p = collstart; p < collend; ++p) {
4225 str += sprintf(str, "&#%d;", (int)*p);
4226 }
4227 p = collend;
4228 break;
4229 default:
4230 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
4231 encoding, reason, startp, size, &exc,
4232 collstart-startp, collend-startp, &newpos);
4233 if (repunicode == NULL)
4234 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004235 if (PyBytes_Check(repunicode)) {
4236 /* Directly copy bytes result to output. */
4237 repsize = PyBytes_Size(repunicode);
4238 if (repsize > 1) {
4239 /* Make room for all additional bytes. */
Amaury Forgeot d'Arce5344d62009-06-29 22:38:54 +00004240 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00004241 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
4242 Py_DECREF(repunicode);
4243 goto onError;
4244 }
Amaury Forgeot d'Arce5344d62009-06-29 22:38:54 +00004245 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004246 ressize += repsize-1;
4247 }
4248 memcpy(str, PyBytes_AsString(repunicode), repsize);
4249 str += repsize;
4250 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004251 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00004252 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004253 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004254 /* need more space? (at least enough for what we
4255 have+the replacement+the rest of the string, so
4256 we won't have to check space for encodable characters) */
4257 respos = str - PyBytes_AS_STRING(res);
4258 repsize = PyUnicode_GET_SIZE(repunicode);
4259 requiredsize = respos+repsize+(endp-collend);
4260 if (requiredsize > ressize) {
4261 if (requiredsize<2*ressize)
4262 requiredsize = 2*ressize;
4263 if (_PyBytes_Resize(&res, requiredsize)) {
4264 Py_DECREF(repunicode);
4265 goto onError;
4266 }
4267 str = PyBytes_AS_STRING(res) + respos;
4268 ressize = requiredsize;
4269 }
4270 /* check if there is anything unencodable in the replacement
4271 and copy it to the output */
4272 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
4273 c = *uni2;
4274 if (c >= limit) {
4275 raise_encode_exception(&exc, encoding, startp, size,
4276 unicodepos, unicodepos+1, reason);
4277 Py_DECREF(repunicode);
4278 goto onError;
4279 }
4280 *str = (char)c;
4281 }
4282 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004283 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00004284 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004285 }
4286 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004287 /* Resize if we allocated to much */
4288 size = str - PyBytes_AS_STRING(res);
4289 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00004290 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004291 if (_PyBytes_Resize(&res, size) < 0)
4292 goto onError;
4293 }
4294
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004295 Py_XDECREF(errorHandler);
4296 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004297 return res;
4298
4299 onError:
4300 Py_XDECREF(res);
4301 Py_XDECREF(errorHandler);
4302 Py_XDECREF(exc);
4303 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004304}
4305
Guido van Rossumd57fd912000-03-10 22:53:23 +00004306PyObject *PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004307 Py_ssize_t size,
4308 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004309{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004310 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004311}
4312
4313PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
4314{
4315 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004316 PyErr_BadArgument();
4317 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004318 }
4319 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004320 PyUnicode_GET_SIZE(unicode),
4321 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004322}
4323
4324/* --- 7-bit ASCII Codec -------------------------------------------------- */
4325
Guido van Rossumd57fd912000-03-10 22:53:23 +00004326PyObject *PyUnicode_DecodeASCII(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004327 Py_ssize_t size,
4328 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004329{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004330 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004331 PyUnicodeObject *v;
4332 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004333 Py_ssize_t startinpos;
4334 Py_ssize_t endinpos;
4335 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004336 const char *e;
4337 PyObject *errorHandler = NULL;
4338 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00004339
Guido van Rossumd57fd912000-03-10 22:53:23 +00004340 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004341 if (size == 1 && *(unsigned char*)s < 128) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004342 Py_UNICODE r = *(unsigned char*)s;
4343 return PyUnicode_FromUnicode(&r, 1);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004344 }
Tim Petersced69f82003-09-16 20:30:58 +00004345
Guido van Rossumd57fd912000-03-10 22:53:23 +00004346 v = _PyUnicode_New(size);
4347 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004348 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004349 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004350 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004351 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004352 e = s + size;
4353 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004354 register unsigned char c = (unsigned char)*s;
4355 if (c < 128) {
4356 *p++ = c;
4357 ++s;
4358 }
4359 else {
4360 startinpos = s-starts;
4361 endinpos = startinpos + 1;
4362 outpos = p - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
4363 if (unicode_decode_call_errorhandler(
4364 errors, &errorHandler,
4365 "ascii", "ordinal not in range(128)",
4366 &starts, &e, &startinpos, &endinpos, &exc, &s,
4367 &v, &outpos, &p))
4368 goto onError;
4369 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004370 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00004371 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00004372 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
4373 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004374 Py_XDECREF(errorHandler);
4375 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004376 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004377
Benjamin Peterson29060642009-01-31 22:14:21 +00004378 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004379 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004380 Py_XDECREF(errorHandler);
4381 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004382 return NULL;
4383}
4384
Guido van Rossumd57fd912000-03-10 22:53:23 +00004385PyObject *PyUnicode_EncodeASCII(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004386 Py_ssize_t size,
4387 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004388{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004389 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004390}
4391
4392PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
4393{
4394 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004395 PyErr_BadArgument();
4396 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004397 }
4398 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004399 PyUnicode_GET_SIZE(unicode),
4400 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004401}
4402
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004403#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004404
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004405/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004406
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00004407#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004408#define NEED_RETRY
4409#endif
4410
4411/* XXX This code is limited to "true" double-byte encodings, as
4412 a) it assumes an incomplete character consists of a single byte, and
4413 b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
Benjamin Peterson29060642009-01-31 22:14:21 +00004414 encodings, see IsDBCSLeadByteEx documentation. */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004415
4416static int is_dbcs_lead_byte(const char *s, int offset)
4417{
4418 const char *curr = s + offset;
4419
4420 if (IsDBCSLeadByte(*curr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004421 const char *prev = CharPrev(s, curr);
4422 return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004423 }
4424 return 0;
4425}
4426
4427/*
4428 * Decode MBCS string into unicode object. If 'final' is set, converts
4429 * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
4430 */
4431static int decode_mbcs(PyUnicodeObject **v,
Benjamin Peterson29060642009-01-31 22:14:21 +00004432 const char *s, /* MBCS string */
4433 int size, /* sizeof MBCS string */
4434 int final)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004435{
4436 Py_UNICODE *p;
4437 Py_ssize_t n = 0;
4438 int usize = 0;
4439
4440 assert(size >= 0);
4441
4442 /* Skip trailing lead-byte unless 'final' is set */
4443 if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
Benjamin Peterson29060642009-01-31 22:14:21 +00004444 --size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004445
4446 /* First get the size of the result */
4447 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004448 usize = MultiByteToWideChar(CP_ACP, 0, s, size, NULL, 0);
4449 if (usize == 0) {
4450 PyErr_SetFromWindowsErrWithFilename(0, NULL);
4451 return -1;
4452 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004453 }
4454
4455 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004456 /* Create unicode object */
4457 *v = _PyUnicode_New(usize);
4458 if (*v == NULL)
4459 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004460 }
4461 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004462 /* Extend unicode object */
4463 n = PyUnicode_GET_SIZE(*v);
4464 if (_PyUnicode_Resize(v, n + usize) < 0)
4465 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004466 }
4467
4468 /* Do the conversion */
4469 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004470 p = PyUnicode_AS_UNICODE(*v) + n;
4471 if (0 == MultiByteToWideChar(CP_ACP, 0, s, size, p, usize)) {
4472 PyErr_SetFromWindowsErrWithFilename(0, NULL);
4473 return -1;
4474 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004475 }
4476
4477 return size;
4478}
4479
4480PyObject *PyUnicode_DecodeMBCSStateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004481 Py_ssize_t size,
4482 const char *errors,
4483 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004484{
4485 PyUnicodeObject *v = NULL;
4486 int done;
4487
4488 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004489 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004490
4491#ifdef NEED_RETRY
4492 retry:
4493 if (size > INT_MAX)
Benjamin Peterson29060642009-01-31 22:14:21 +00004494 done = decode_mbcs(&v, s, INT_MAX, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004495 else
4496#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004497 done = decode_mbcs(&v, s, (int)size, !consumed);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004498
4499 if (done < 0) {
4500 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00004501 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004502 }
4503
4504 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004505 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004506
4507#ifdef NEED_RETRY
4508 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004509 s += done;
4510 size -= done;
4511 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004512 }
4513#endif
4514
4515 return (PyObject *)v;
4516}
4517
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004518PyObject *PyUnicode_DecodeMBCS(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004519 Py_ssize_t size,
4520 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004521{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004522 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
4523}
4524
4525/*
4526 * Convert unicode into string object (MBCS).
4527 * Returns 0 if succeed, -1 otherwise.
4528 */
4529static int encode_mbcs(PyObject **repr,
Benjamin Peterson29060642009-01-31 22:14:21 +00004530 const Py_UNICODE *p, /* unicode */
4531 int size) /* size of unicode */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004532{
4533 int mbcssize = 0;
4534 Py_ssize_t n = 0;
4535
4536 assert(size >= 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004537
4538 /* First get the size of the result */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004539 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004540 mbcssize = WideCharToMultiByte(CP_ACP, 0, p, size, NULL, 0, NULL, NULL);
4541 if (mbcssize == 0) {
4542 PyErr_SetFromWindowsErrWithFilename(0, NULL);
4543 return -1;
4544 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004545 }
4546
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004547 if (*repr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004548 /* Create string object */
4549 *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
4550 if (*repr == NULL)
4551 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004552 }
4553 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004554 /* Extend string object */
4555 n = PyBytes_Size(*repr);
4556 if (_PyBytes_Resize(repr, n + mbcssize) < 0)
4557 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004558 }
4559
4560 /* Do the conversion */
4561 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004562 char *s = PyBytes_AS_STRING(*repr) + n;
4563 if (0 == WideCharToMultiByte(CP_ACP, 0, p, size, s, mbcssize, NULL, NULL)) {
4564 PyErr_SetFromWindowsErrWithFilename(0, NULL);
4565 return -1;
4566 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004567 }
4568
4569 return 0;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004570}
4571
4572PyObject *PyUnicode_EncodeMBCS(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004573 Py_ssize_t size,
4574 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004575{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004576 PyObject *repr = NULL;
4577 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00004578
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004579#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00004580 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004581 if (size > INT_MAX)
Benjamin Peterson29060642009-01-31 22:14:21 +00004582 ret = encode_mbcs(&repr, p, INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004583 else
4584#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004585 ret = encode_mbcs(&repr, p, (int)size);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004586
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004587 if (ret < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004588 Py_XDECREF(repr);
4589 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004590 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004591
4592#ifdef NEED_RETRY
4593 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004594 p += INT_MAX;
4595 size -= INT_MAX;
4596 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004597 }
4598#endif
4599
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004600 return repr;
4601}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004602
Mark Hammond0ccda1e2003-07-01 00:13:27 +00004603PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
4604{
4605 if (!PyUnicode_Check(unicode)) {
4606 PyErr_BadArgument();
4607 return NULL;
4608 }
4609 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004610 PyUnicode_GET_SIZE(unicode),
4611 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00004612}
4613
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004614#undef NEED_RETRY
4615
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004616#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004617
Guido van Rossumd57fd912000-03-10 22:53:23 +00004618/* --- Character Mapping Codec -------------------------------------------- */
4619
Guido van Rossumd57fd912000-03-10 22:53:23 +00004620PyObject *PyUnicode_DecodeCharmap(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004621 Py_ssize_t size,
4622 PyObject *mapping,
4623 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004624{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004625 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004626 Py_ssize_t startinpos;
4627 Py_ssize_t endinpos;
4628 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004629 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004630 PyUnicodeObject *v;
4631 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004632 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004633 PyObject *errorHandler = NULL;
4634 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00004635 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004636 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00004637
Guido van Rossumd57fd912000-03-10 22:53:23 +00004638 /* Default to Latin-1 */
4639 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004640 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004641
4642 v = _PyUnicode_New(size);
4643 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004644 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004645 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004646 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004647 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004648 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00004649 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004650 mapstring = PyUnicode_AS_UNICODE(mapping);
4651 maplen = PyUnicode_GET_SIZE(mapping);
4652 while (s < e) {
4653 unsigned char ch = *s;
4654 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004655
Benjamin Peterson29060642009-01-31 22:14:21 +00004656 if (ch < maplen)
4657 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00004658
Benjamin Peterson29060642009-01-31 22:14:21 +00004659 if (x == 0xfffe) {
4660 /* undefined mapping */
4661 outpos = p-PyUnicode_AS_UNICODE(v);
4662 startinpos = s-starts;
4663 endinpos = startinpos+1;
4664 if (unicode_decode_call_errorhandler(
4665 errors, &errorHandler,
4666 "charmap", "character maps to <undefined>",
4667 &starts, &e, &startinpos, &endinpos, &exc, &s,
4668 &v, &outpos, &p)) {
4669 goto onError;
4670 }
4671 continue;
4672 }
4673 *p++ = x;
4674 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004675 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00004676 }
4677 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004678 while (s < e) {
4679 unsigned char ch = *s;
4680 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00004681
Benjamin Peterson29060642009-01-31 22:14:21 +00004682 /* Get mapping (char ordinal -> integer, Unicode char or None) */
4683 w = PyLong_FromLong((long)ch);
4684 if (w == NULL)
4685 goto onError;
4686 x = PyObject_GetItem(mapping, w);
4687 Py_DECREF(w);
4688 if (x == NULL) {
4689 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
4690 /* No mapping found means: mapping is undefined. */
4691 PyErr_Clear();
4692 x = Py_None;
4693 Py_INCREF(x);
4694 } else
4695 goto onError;
4696 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004697
Benjamin Peterson29060642009-01-31 22:14:21 +00004698 /* Apply mapping */
4699 if (PyLong_Check(x)) {
4700 long value = PyLong_AS_LONG(x);
4701 if (value < 0 || value > 65535) {
4702 PyErr_SetString(PyExc_TypeError,
4703 "character mapping must be in range(65536)");
4704 Py_DECREF(x);
4705 goto onError;
4706 }
4707 *p++ = (Py_UNICODE)value;
4708 }
4709 else if (x == Py_None) {
4710 /* undefined mapping */
4711 outpos = p-PyUnicode_AS_UNICODE(v);
4712 startinpos = s-starts;
4713 endinpos = startinpos+1;
4714 if (unicode_decode_call_errorhandler(
4715 errors, &errorHandler,
4716 "charmap", "character maps to <undefined>",
4717 &starts, &e, &startinpos, &endinpos, &exc, &s,
4718 &v, &outpos, &p)) {
4719 Py_DECREF(x);
4720 goto onError;
4721 }
4722 Py_DECREF(x);
4723 continue;
4724 }
4725 else if (PyUnicode_Check(x)) {
4726 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00004727
Benjamin Peterson29060642009-01-31 22:14:21 +00004728 if (targetsize == 1)
4729 /* 1-1 mapping */
4730 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00004731
Benjamin Peterson29060642009-01-31 22:14:21 +00004732 else if (targetsize > 1) {
4733 /* 1-n mapping */
4734 if (targetsize > extrachars) {
4735 /* resize first */
4736 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
4737 Py_ssize_t needed = (targetsize - extrachars) + \
4738 (targetsize << 2);
4739 extrachars += needed;
4740 /* XXX overflow detection missing */
4741 if (_PyUnicode_Resize(&v,
4742 PyUnicode_GET_SIZE(v) + needed) < 0) {
4743 Py_DECREF(x);
4744 goto onError;
4745 }
4746 p = PyUnicode_AS_UNICODE(v) + oldpos;
4747 }
4748 Py_UNICODE_COPY(p,
4749 PyUnicode_AS_UNICODE(x),
4750 targetsize);
4751 p += targetsize;
4752 extrachars -= targetsize;
4753 }
4754 /* 1-0 mapping: skip the character */
4755 }
4756 else {
4757 /* wrong return value */
4758 PyErr_SetString(PyExc_TypeError,
4759 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00004760 Py_DECREF(x);
4761 goto onError;
4762 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004763 Py_DECREF(x);
4764 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004765 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004766 }
4767 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00004768 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
4769 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004770 Py_XDECREF(errorHandler);
4771 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004772 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004773
Benjamin Peterson29060642009-01-31 22:14:21 +00004774 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004775 Py_XDECREF(errorHandler);
4776 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004777 Py_XDECREF(v);
4778 return NULL;
4779}
4780
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004781/* Charmap encoding: the lookup table */
4782
4783struct encoding_map{
Benjamin Peterson29060642009-01-31 22:14:21 +00004784 PyObject_HEAD
4785 unsigned char level1[32];
4786 int count2, count3;
4787 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004788};
4789
4790static PyObject*
4791encoding_map_size(PyObject *obj, PyObject* args)
4792{
4793 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004794 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00004795 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004796}
4797
4798static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00004799 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00004800 PyDoc_STR("Return the size (in bytes) of this object") },
4801 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004802};
4803
4804static void
4805encoding_map_dealloc(PyObject* o)
4806{
Benjamin Peterson14339b62009-01-31 16:36:08 +00004807 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004808}
4809
4810static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00004811 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004812 "EncodingMap", /*tp_name*/
4813 sizeof(struct encoding_map), /*tp_basicsize*/
4814 0, /*tp_itemsize*/
4815 /* methods */
4816 encoding_map_dealloc, /*tp_dealloc*/
4817 0, /*tp_print*/
4818 0, /*tp_getattr*/
4819 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00004820 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00004821 0, /*tp_repr*/
4822 0, /*tp_as_number*/
4823 0, /*tp_as_sequence*/
4824 0, /*tp_as_mapping*/
4825 0, /*tp_hash*/
4826 0, /*tp_call*/
4827 0, /*tp_str*/
4828 0, /*tp_getattro*/
4829 0, /*tp_setattro*/
4830 0, /*tp_as_buffer*/
4831 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4832 0, /*tp_doc*/
4833 0, /*tp_traverse*/
4834 0, /*tp_clear*/
4835 0, /*tp_richcompare*/
4836 0, /*tp_weaklistoffset*/
4837 0, /*tp_iter*/
4838 0, /*tp_iternext*/
4839 encoding_map_methods, /*tp_methods*/
4840 0, /*tp_members*/
4841 0, /*tp_getset*/
4842 0, /*tp_base*/
4843 0, /*tp_dict*/
4844 0, /*tp_descr_get*/
4845 0, /*tp_descr_set*/
4846 0, /*tp_dictoffset*/
4847 0, /*tp_init*/
4848 0, /*tp_alloc*/
4849 0, /*tp_new*/
4850 0, /*tp_free*/
4851 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004852};
4853
4854PyObject*
4855PyUnicode_BuildEncodingMap(PyObject* string)
4856{
4857 Py_UNICODE *decode;
4858 PyObject *result;
4859 struct encoding_map *mresult;
4860 int i;
4861 int need_dict = 0;
4862 unsigned char level1[32];
4863 unsigned char level2[512];
4864 unsigned char *mlevel1, *mlevel2, *mlevel3;
4865 int count2 = 0, count3 = 0;
4866
4867 if (!PyUnicode_Check(string) || PyUnicode_GetSize(string) != 256) {
4868 PyErr_BadArgument();
4869 return NULL;
4870 }
4871 decode = PyUnicode_AS_UNICODE(string);
4872 memset(level1, 0xFF, sizeof level1);
4873 memset(level2, 0xFF, sizeof level2);
4874
4875 /* If there isn't a one-to-one mapping of NULL to \0,
4876 or if there are non-BMP characters, we need to use
4877 a mapping dictionary. */
4878 if (decode[0] != 0)
4879 need_dict = 1;
4880 for (i = 1; i < 256; i++) {
4881 int l1, l2;
4882 if (decode[i] == 0
Benjamin Peterson29060642009-01-31 22:14:21 +00004883#ifdef Py_UNICODE_WIDE
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004884 || decode[i] > 0xFFFF
Benjamin Peterson29060642009-01-31 22:14:21 +00004885#endif
4886 ) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004887 need_dict = 1;
4888 break;
4889 }
4890 if (decode[i] == 0xFFFE)
4891 /* unmapped character */
4892 continue;
4893 l1 = decode[i] >> 11;
4894 l2 = decode[i] >> 7;
4895 if (level1[l1] == 0xFF)
4896 level1[l1] = count2++;
4897 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00004898 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004899 }
4900
4901 if (count2 >= 0xFF || count3 >= 0xFF)
4902 need_dict = 1;
4903
4904 if (need_dict) {
4905 PyObject *result = PyDict_New();
4906 PyObject *key, *value;
4907 if (!result)
4908 return NULL;
4909 for (i = 0; i < 256; i++) {
4910 key = value = NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00004911 key = PyLong_FromLong(decode[i]);
4912 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004913 if (!key || !value)
4914 goto failed1;
4915 if (PyDict_SetItem(result, key, value) == -1)
4916 goto failed1;
4917 Py_DECREF(key);
4918 Py_DECREF(value);
4919 }
4920 return result;
4921 failed1:
4922 Py_XDECREF(key);
4923 Py_XDECREF(value);
4924 Py_DECREF(result);
4925 return NULL;
4926 }
4927
4928 /* Create a three-level trie */
4929 result = PyObject_MALLOC(sizeof(struct encoding_map) +
4930 16*count2 + 128*count3 - 1);
4931 if (!result)
4932 return PyErr_NoMemory();
4933 PyObject_Init(result, &EncodingMapType);
4934 mresult = (struct encoding_map*)result;
4935 mresult->count2 = count2;
4936 mresult->count3 = count3;
4937 mlevel1 = mresult->level1;
4938 mlevel2 = mresult->level23;
4939 mlevel3 = mresult->level23 + 16*count2;
4940 memcpy(mlevel1, level1, 32);
4941 memset(mlevel2, 0xFF, 16*count2);
4942 memset(mlevel3, 0, 128*count3);
4943 count3 = 0;
4944 for (i = 1; i < 256; i++) {
4945 int o1, o2, o3, i2, i3;
4946 if (decode[i] == 0xFFFE)
4947 /* unmapped character */
4948 continue;
4949 o1 = decode[i]>>11;
4950 o2 = (decode[i]>>7) & 0xF;
4951 i2 = 16*mlevel1[o1] + o2;
4952 if (mlevel2[i2] == 0xFF)
4953 mlevel2[i2] = count3++;
4954 o3 = decode[i] & 0x7F;
4955 i3 = 128*mlevel2[i2] + o3;
4956 mlevel3[i3] = i;
4957 }
4958 return result;
4959}
4960
4961static int
4962encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
4963{
4964 struct encoding_map *map = (struct encoding_map*)mapping;
4965 int l1 = c>>11;
4966 int l2 = (c>>7) & 0xF;
4967 int l3 = c & 0x7F;
4968 int i;
4969
4970#ifdef Py_UNICODE_WIDE
4971 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004972 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004973 }
4974#endif
4975 if (c == 0)
4976 return 0;
4977 /* level 1*/
4978 i = map->level1[l1];
4979 if (i == 0xFF) {
4980 return -1;
4981 }
4982 /* level 2*/
4983 i = map->level23[16*i+l2];
4984 if (i == 0xFF) {
4985 return -1;
4986 }
4987 /* level 3 */
4988 i = map->level23[16*map->count2 + 128*i + l3];
4989 if (i == 0) {
4990 return -1;
4991 }
4992 return i;
4993}
4994
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004995/* Lookup the character ch in the mapping. If the character
4996 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00004997 error occurred). */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004998static PyObject *charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004999{
Christian Heimes217cfd12007-12-02 14:31:20 +00005000 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005001 PyObject *x;
5002
5003 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005004 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005005 x = PyObject_GetItem(mapping, w);
5006 Py_DECREF(w);
5007 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005008 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5009 /* No mapping found means: mapping is undefined. */
5010 PyErr_Clear();
5011 x = Py_None;
5012 Py_INCREF(x);
5013 return x;
5014 } else
5015 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005016 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00005017 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00005018 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00005019 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005020 long value = PyLong_AS_LONG(x);
5021 if (value < 0 || value > 255) {
5022 PyErr_SetString(PyExc_TypeError,
5023 "character mapping must be in range(256)");
5024 Py_DECREF(x);
5025 return NULL;
5026 }
5027 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005028 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005029 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00005030 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005031 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005032 /* wrong return value */
5033 PyErr_Format(PyExc_TypeError,
5034 "character mapping must return integer, bytes or None, not %.400s",
5035 x->ob_type->tp_name);
5036 Py_DECREF(x);
5037 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005038 }
5039}
5040
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005041static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00005042charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005043{
Benjamin Peterson14339b62009-01-31 16:36:08 +00005044 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
5045 /* exponentially overallocate to minimize reallocations */
5046 if (requiredsize < 2*outsize)
5047 requiredsize = 2*outsize;
5048 if (_PyBytes_Resize(outobj, requiredsize))
5049 return -1;
5050 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005051}
5052
Benjamin Peterson14339b62009-01-31 16:36:08 +00005053typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00005054 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005055}charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005056/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00005057 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005058 space is available. Return a new reference to the object that
5059 was put in the output buffer, or Py_None, if the mapping was undefined
5060 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00005061 reallocation error occurred. The caller must decref the result */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005062static
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005063charmapencode_result charmapencode_output(Py_UNICODE c, PyObject *mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00005064 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005065{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005066 PyObject *rep;
5067 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00005068 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005069
Christian Heimes90aa7642007-12-19 02:45:37 +00005070 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005071 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00005072 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005073 if (res == -1)
5074 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00005075 if (outsize<requiredsize)
5076 if (charmapencode_resize(outobj, outpos, requiredsize))
5077 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00005078 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005079 outstart[(*outpos)++] = (char)res;
5080 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005081 }
5082
5083 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005084 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005085 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005086 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005087 Py_DECREF(rep);
5088 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005089 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005090 if (PyLong_Check(rep)) {
5091 Py_ssize_t requiredsize = *outpos+1;
5092 if (outsize<requiredsize)
5093 if (charmapencode_resize(outobj, outpos, requiredsize)) {
5094 Py_DECREF(rep);
5095 return enc_EXCEPTION;
5096 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005097 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005098 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005099 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005100 else {
5101 const char *repchars = PyBytes_AS_STRING(rep);
5102 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
5103 Py_ssize_t requiredsize = *outpos+repsize;
5104 if (outsize<requiredsize)
5105 if (charmapencode_resize(outobj, outpos, requiredsize)) {
5106 Py_DECREF(rep);
5107 return enc_EXCEPTION;
5108 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005109 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005110 memcpy(outstart + *outpos, repchars, repsize);
5111 *outpos += repsize;
5112 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005113 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005114 Py_DECREF(rep);
5115 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005116}
5117
5118/* handle an error in PyUnicode_EncodeCharmap
5119 Return 0 on success, -1 on error */
5120static
5121int charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00005122 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005123 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00005124 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00005125 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005126{
5127 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005128 Py_ssize_t repsize;
5129 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005130 Py_UNICODE *uni2;
5131 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005132 Py_ssize_t collstartpos = *inpos;
5133 Py_ssize_t collendpos = *inpos+1;
5134 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005135 char *encoding = "charmap";
5136 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005137 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005138
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005139 /* find all unencodable characters */
5140 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005141 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00005142 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005143 int res = encoding_map_lookup(p[collendpos], mapping);
5144 if (res != -1)
5145 break;
5146 ++collendpos;
5147 continue;
5148 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005149
Benjamin Peterson29060642009-01-31 22:14:21 +00005150 rep = charmapencode_lookup(p[collendpos], mapping);
5151 if (rep==NULL)
5152 return -1;
5153 else if (rep!=Py_None) {
5154 Py_DECREF(rep);
5155 break;
5156 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005157 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00005158 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005159 }
5160 /* cache callback name lookup
5161 * (if not done yet, i.e. it's the first error) */
5162 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005163 if ((errors==NULL) || (!strcmp(errors, "strict")))
5164 *known_errorHandler = 1;
5165 else if (!strcmp(errors, "replace"))
5166 *known_errorHandler = 2;
5167 else if (!strcmp(errors, "ignore"))
5168 *known_errorHandler = 3;
5169 else if (!strcmp(errors, "xmlcharrefreplace"))
5170 *known_errorHandler = 4;
5171 else
5172 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005173 }
5174 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005175 case 1: /* strict */
5176 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5177 return -1;
5178 case 2: /* replace */
5179 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005180 x = charmapencode_output('?', mapping, res, respos);
5181 if (x==enc_EXCEPTION) {
5182 return -1;
5183 }
5184 else if (x==enc_FAILED) {
5185 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5186 return -1;
5187 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005188 }
5189 /* fall through */
5190 case 3: /* ignore */
5191 *inpos = collendpos;
5192 break;
5193 case 4: /* xmlcharrefreplace */
5194 /* generate replacement (temporarily (mis)uses p) */
5195 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005196 char buffer[2+29+1+1];
5197 char *cp;
5198 sprintf(buffer, "&#%d;", (int)p[collpos]);
5199 for (cp = buffer; *cp; ++cp) {
5200 x = charmapencode_output(*cp, mapping, res, respos);
5201 if (x==enc_EXCEPTION)
5202 return -1;
5203 else if (x==enc_FAILED) {
5204 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5205 return -1;
5206 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005207 }
5208 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005209 *inpos = collendpos;
5210 break;
5211 default:
5212 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00005213 encoding, reason, p, size, exceptionObject,
5214 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005215 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005216 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005217 if (PyBytes_Check(repunicode)) {
5218 /* Directly copy bytes result to output. */
5219 Py_ssize_t outsize = PyBytes_Size(*res);
5220 Py_ssize_t requiredsize;
5221 repsize = PyBytes_Size(repunicode);
5222 requiredsize = *respos + repsize;
5223 if (requiredsize > outsize)
5224 /* Make room for all additional bytes. */
5225 if (charmapencode_resize(res, respos, requiredsize)) {
5226 Py_DECREF(repunicode);
5227 return -1;
5228 }
5229 memcpy(PyBytes_AsString(*res) + *respos,
5230 PyBytes_AsString(repunicode), repsize);
5231 *respos += repsize;
5232 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005233 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00005234 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005235 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005236 /* generate replacement */
5237 repsize = PyUnicode_GET_SIZE(repunicode);
5238 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005239 x = charmapencode_output(*uni2, mapping, res, respos);
5240 if (x==enc_EXCEPTION) {
5241 return -1;
5242 }
5243 else if (x==enc_FAILED) {
5244 Py_DECREF(repunicode);
5245 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5246 return -1;
5247 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005248 }
5249 *inpos = newpos;
5250 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005251 }
5252 return 0;
5253}
5254
Guido van Rossumd57fd912000-03-10 22:53:23 +00005255PyObject *PyUnicode_EncodeCharmap(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00005256 Py_ssize_t size,
5257 PyObject *mapping,
5258 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005259{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005260 /* output object */
5261 PyObject *res = NULL;
5262 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005263 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005264 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005265 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005266 PyObject *errorHandler = NULL;
5267 PyObject *exc = NULL;
5268 /* the following variable is used for caching string comparisons
5269 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
5270 * 3=ignore, 4=xmlcharrefreplace */
5271 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005272
5273 /* Default to Latin-1 */
5274 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005275 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005276
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005277 /* allocate enough for a simple encoding without
5278 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00005279 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005280 if (res == NULL)
5281 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00005282 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005283 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005284
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005285 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005286 /* try to encode it */
5287 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
5288 if (x==enc_EXCEPTION) /* error */
5289 goto onError;
5290 if (x==enc_FAILED) { /* unencodable character */
5291 if (charmap_encoding_error(p, size, &inpos, mapping,
5292 &exc,
5293 &known_errorHandler, &errorHandler, errors,
5294 &res, &respos)) {
5295 goto onError;
5296 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005297 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005298 else
5299 /* done with this character => adjust input position */
5300 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005301 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005302
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005303 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00005304 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005305 if (_PyBytes_Resize(&res, respos) < 0)
5306 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005307
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005308 Py_XDECREF(exc);
5309 Py_XDECREF(errorHandler);
5310 return res;
5311
Benjamin Peterson29060642009-01-31 22:14:21 +00005312 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005313 Py_XDECREF(res);
5314 Py_XDECREF(exc);
5315 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005316 return NULL;
5317}
5318
5319PyObject *PyUnicode_AsCharmapString(PyObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00005320 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005321{
5322 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005323 PyErr_BadArgument();
5324 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005325 }
5326 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005327 PyUnicode_GET_SIZE(unicode),
5328 mapping,
5329 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005330}
5331
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005332/* create or adjust a UnicodeTranslateError */
5333static void make_translate_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005334 const Py_UNICODE *unicode, Py_ssize_t size,
5335 Py_ssize_t startpos, Py_ssize_t endpos,
5336 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005337{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005338 if (*exceptionObject == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005339 *exceptionObject = PyUnicodeTranslateError_Create(
Benjamin Peterson29060642009-01-31 22:14:21 +00005340 unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005341 }
5342 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005343 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
5344 goto onError;
5345 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
5346 goto onError;
5347 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
5348 goto onError;
5349 return;
5350 onError:
5351 Py_DECREF(*exceptionObject);
5352 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005353 }
5354}
5355
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005356/* raises a UnicodeTranslateError */
5357static void raise_translate_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005358 const Py_UNICODE *unicode, Py_ssize_t size,
5359 Py_ssize_t startpos, Py_ssize_t endpos,
5360 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005361{
5362 make_translate_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005363 unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005364 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005365 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005366}
5367
5368/* error handling callback helper:
5369 build arguments, call the callback and check the arguments,
5370 put the result into newpos and return the replacement string, which
5371 has to be freed by the caller */
5372static PyObject *unicode_translate_call_errorhandler(const char *errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00005373 PyObject **errorHandler,
5374 const char *reason,
5375 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
5376 Py_ssize_t startpos, Py_ssize_t endpos,
5377 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005378{
Benjamin Peterson142957c2008-07-04 19:55:29 +00005379 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005380
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005381 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005382 PyObject *restuple;
5383 PyObject *resunicode;
5384
5385 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005386 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005387 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005388 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005389 }
5390
5391 make_translate_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005392 unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005393 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005394 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005395
5396 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00005397 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005398 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005399 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005400 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00005401 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00005402 Py_DECREF(restuple);
5403 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005404 }
5405 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00005406 &resunicode, &i_newpos)) {
5407 Py_DECREF(restuple);
5408 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005409 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00005410 if (i_newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005411 *newpos = size+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005412 else
5413 *newpos = i_newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005414 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005415 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
5416 Py_DECREF(restuple);
5417 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005418 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005419 Py_INCREF(resunicode);
5420 Py_DECREF(restuple);
5421 return resunicode;
5422}
5423
5424/* Lookup the character ch in the mapping and put the result in result,
5425 which must be decrefed by the caller.
5426 Return 0 on success, -1 on error */
5427static
5428int charmaptranslate_lookup(Py_UNICODE c, PyObject *mapping, PyObject **result)
5429{
Christian Heimes217cfd12007-12-02 14:31:20 +00005430 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005431 PyObject *x;
5432
5433 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005434 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005435 x = PyObject_GetItem(mapping, w);
5436 Py_DECREF(w);
5437 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005438 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5439 /* No mapping found means: use 1:1 mapping. */
5440 PyErr_Clear();
5441 *result = NULL;
5442 return 0;
5443 } else
5444 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005445 }
5446 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005447 *result = x;
5448 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005449 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005450 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005451 long value = PyLong_AS_LONG(x);
5452 long max = PyUnicode_GetMax();
5453 if (value < 0 || value > max) {
5454 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00005455 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00005456 Py_DECREF(x);
5457 return -1;
5458 }
5459 *result = x;
5460 return 0;
5461 }
5462 else if (PyUnicode_Check(x)) {
5463 *result = x;
5464 return 0;
5465 }
5466 else {
5467 /* wrong return value */
5468 PyErr_SetString(PyExc_TypeError,
5469 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00005470 Py_DECREF(x);
5471 return -1;
5472 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005473}
5474/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00005475 if not reallocate and adjust various state variables.
5476 Return 0 on success, -1 on error */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005477static
Walter Dörwald4894c302003-10-24 14:25:28 +00005478int charmaptranslate_makespace(PyObject **outobj, Py_UNICODE **outp,
Benjamin Peterson29060642009-01-31 22:14:21 +00005479 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005480{
Martin v. Löwis18e16552006-02-15 17:27:45 +00005481 Py_ssize_t oldsize = PyUnicode_GET_SIZE(*outobj);
Walter Dörwald4894c302003-10-24 14:25:28 +00005482 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005483 /* remember old output position */
5484 Py_ssize_t outpos = *outp-PyUnicode_AS_UNICODE(*outobj);
5485 /* exponentially overallocate to minimize reallocations */
5486 if (requiredsize < 2 * oldsize)
5487 requiredsize = 2 * oldsize;
5488 if (PyUnicode_Resize(outobj, requiredsize) < 0)
5489 return -1;
5490 *outp = PyUnicode_AS_UNICODE(*outobj) + outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005491 }
5492 return 0;
5493}
5494/* lookup the character, put the result in the output string and adjust
5495 various state variables. Return a new reference to the object that
5496 was put in the output buffer in *result, or Py_None, if the mapping was
5497 undefined (in which case no character was written).
5498 The called must decref result.
5499 Return 0 on success, -1 on error. */
5500static
Walter Dörwald4894c302003-10-24 14:25:28 +00005501int charmaptranslate_output(const Py_UNICODE *startinp, const Py_UNICODE *curinp,
Benjamin Peterson29060642009-01-31 22:14:21 +00005502 Py_ssize_t insize, PyObject *mapping, PyObject **outobj, Py_UNICODE **outp,
5503 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005504{
Walter Dörwald4894c302003-10-24 14:25:28 +00005505 if (charmaptranslate_lookup(*curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00005506 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005507 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005508 /* not found => default to 1:1 mapping */
5509 *(*outp)++ = *curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005510 }
5511 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00005512 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00005513 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005514 /* no overflow check, because we know that the space is enough */
5515 *(*outp)++ = (Py_UNICODE)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005516 }
5517 else if (PyUnicode_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005518 Py_ssize_t repsize = PyUnicode_GET_SIZE(*res);
5519 if (repsize==1) {
5520 /* no overflow check, because we know that the space is enough */
5521 *(*outp)++ = *PyUnicode_AS_UNICODE(*res);
5522 }
5523 else if (repsize!=0) {
5524 /* more than one character */
5525 Py_ssize_t requiredsize = (*outp-PyUnicode_AS_UNICODE(*outobj)) +
5526 (insize - (curinp-startinp)) +
5527 repsize - 1;
5528 if (charmaptranslate_makespace(outobj, outp, requiredsize))
5529 return -1;
5530 memcpy(*outp, PyUnicode_AS_UNICODE(*res), sizeof(Py_UNICODE)*repsize);
5531 *outp += repsize;
5532 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005533 }
5534 else
Benjamin Peterson29060642009-01-31 22:14:21 +00005535 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005536 return 0;
5537}
5538
5539PyObject *PyUnicode_TranslateCharmap(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00005540 Py_ssize_t size,
5541 PyObject *mapping,
5542 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005543{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005544 /* output object */
5545 PyObject *res = NULL;
5546 /* pointers to the beginning and end+1 of input */
5547 const Py_UNICODE *startp = p;
5548 const Py_UNICODE *endp = p + size;
5549 /* pointer into the output */
5550 Py_UNICODE *str;
5551 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005552 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005553 char *reason = "character maps to <undefined>";
5554 PyObject *errorHandler = NULL;
5555 PyObject *exc = NULL;
5556 /* the following variable is used for caching string comparisons
5557 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
5558 * 3=ignore, 4=xmlcharrefreplace */
5559 int known_errorHandler = -1;
5560
Guido van Rossumd57fd912000-03-10 22:53:23 +00005561 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005562 PyErr_BadArgument();
5563 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005564 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005565
5566 /* allocate enough for a simple 1:1 translation without
5567 replacements, if we need more, we'll resize */
5568 res = PyUnicode_FromUnicode(NULL, size);
5569 if (res == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005570 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005571 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005572 return res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005573 str = PyUnicode_AS_UNICODE(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005574
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005575 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005576 /* try to encode it */
5577 PyObject *x = NULL;
5578 if (charmaptranslate_output(startp, p, size, mapping, &res, &str, &x)) {
5579 Py_XDECREF(x);
5580 goto onError;
5581 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005582 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00005583 if (x!=Py_None) /* it worked => adjust input pointer */
5584 ++p;
5585 else { /* untranslatable character */
5586 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
5587 Py_ssize_t repsize;
5588 Py_ssize_t newpos;
5589 Py_UNICODE *uni2;
5590 /* startpos for collecting untranslatable chars */
5591 const Py_UNICODE *collstart = p;
5592 const Py_UNICODE *collend = p+1;
5593 const Py_UNICODE *coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005594
Benjamin Peterson29060642009-01-31 22:14:21 +00005595 /* find all untranslatable characters */
5596 while (collend < endp) {
5597 if (charmaptranslate_lookup(*collend, mapping, &x))
5598 goto onError;
5599 Py_XDECREF(x);
5600 if (x!=Py_None)
5601 break;
5602 ++collend;
5603 }
5604 /* cache callback name lookup
5605 * (if not done yet, i.e. it's the first error) */
5606 if (known_errorHandler==-1) {
5607 if ((errors==NULL) || (!strcmp(errors, "strict")))
5608 known_errorHandler = 1;
5609 else if (!strcmp(errors, "replace"))
5610 known_errorHandler = 2;
5611 else if (!strcmp(errors, "ignore"))
5612 known_errorHandler = 3;
5613 else if (!strcmp(errors, "xmlcharrefreplace"))
5614 known_errorHandler = 4;
5615 else
5616 known_errorHandler = 0;
5617 }
5618 switch (known_errorHandler) {
5619 case 1: /* strict */
5620 raise_translate_exception(&exc, startp, size, collstart-startp, collend-startp, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005621 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005622 case 2: /* replace */
5623 /* No need to check for space, this is a 1:1 replacement */
5624 for (coll = collstart; coll<collend; ++coll)
5625 *str++ = '?';
5626 /* fall through */
5627 case 3: /* ignore */
5628 p = collend;
5629 break;
5630 case 4: /* xmlcharrefreplace */
5631 /* generate replacement (temporarily (mis)uses p) */
5632 for (p = collstart; p < collend; ++p) {
5633 char buffer[2+29+1+1];
5634 char *cp;
5635 sprintf(buffer, "&#%d;", (int)*p);
5636 if (charmaptranslate_makespace(&res, &str,
5637 (str-PyUnicode_AS_UNICODE(res))+strlen(buffer)+(endp-collend)))
5638 goto onError;
5639 for (cp = buffer; *cp; ++cp)
5640 *str++ = *cp;
5641 }
5642 p = collend;
5643 break;
5644 default:
5645 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
5646 reason, startp, size, &exc,
5647 collstart-startp, collend-startp, &newpos);
5648 if (repunicode == NULL)
5649 goto onError;
5650 /* generate replacement */
5651 repsize = PyUnicode_GET_SIZE(repunicode);
5652 if (charmaptranslate_makespace(&res, &str,
5653 (str-PyUnicode_AS_UNICODE(res))+repsize+(endp-collend))) {
5654 Py_DECREF(repunicode);
5655 goto onError;
5656 }
5657 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2)
5658 *str++ = *uni2;
5659 p = startp + newpos;
5660 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005661 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005662 }
5663 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005664 /* Resize if we allocated to much */
5665 respos = str-PyUnicode_AS_UNICODE(res);
Walter Dörwald4894c302003-10-24 14:25:28 +00005666 if (respos<PyUnicode_GET_SIZE(res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005667 if (PyUnicode_Resize(&res, respos) < 0)
5668 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005669 }
5670 Py_XDECREF(exc);
5671 Py_XDECREF(errorHandler);
5672 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005673
Benjamin Peterson29060642009-01-31 22:14:21 +00005674 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005675 Py_XDECREF(res);
5676 Py_XDECREF(exc);
5677 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005678 return NULL;
5679}
5680
5681PyObject *PyUnicode_Translate(PyObject *str,
Benjamin Peterson29060642009-01-31 22:14:21 +00005682 PyObject *mapping,
5683 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005684{
5685 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00005686
Guido van Rossumd57fd912000-03-10 22:53:23 +00005687 str = PyUnicode_FromObject(str);
5688 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005689 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005690 result = PyUnicode_TranslateCharmap(PyUnicode_AS_UNICODE(str),
Benjamin Peterson29060642009-01-31 22:14:21 +00005691 PyUnicode_GET_SIZE(str),
5692 mapping,
5693 errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005694 Py_DECREF(str);
5695 return result;
Tim Petersced69f82003-09-16 20:30:58 +00005696
Benjamin Peterson29060642009-01-31 22:14:21 +00005697 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005698 Py_XDECREF(str);
5699 return NULL;
5700}
Tim Petersced69f82003-09-16 20:30:58 +00005701
Guido van Rossum9e896b32000-04-05 20:11:21 +00005702/* --- Decimal Encoder ---------------------------------------------------- */
5703
5704int PyUnicode_EncodeDecimal(Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005705 Py_ssize_t length,
5706 char *output,
5707 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00005708{
5709 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005710 PyObject *errorHandler = NULL;
5711 PyObject *exc = NULL;
5712 const char *encoding = "decimal";
5713 const char *reason = "invalid decimal Unicode string";
5714 /* the following variable is used for caching string comparisons
5715 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
5716 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00005717
5718 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005719 PyErr_BadArgument();
5720 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00005721 }
5722
5723 p = s;
5724 end = s + length;
5725 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005726 register Py_UNICODE ch = *p;
5727 int decimal;
5728 PyObject *repunicode;
5729 Py_ssize_t repsize;
5730 Py_ssize_t newpos;
5731 Py_UNICODE *uni2;
5732 Py_UNICODE *collstart;
5733 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00005734
Benjamin Peterson29060642009-01-31 22:14:21 +00005735 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005736 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00005737 ++p;
5738 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005739 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005740 decimal = Py_UNICODE_TODECIMAL(ch);
5741 if (decimal >= 0) {
5742 *output++ = '0' + decimal;
5743 ++p;
5744 continue;
5745 }
5746 if (0 < ch && ch < 256) {
5747 *output++ = (char)ch;
5748 ++p;
5749 continue;
5750 }
5751 /* All other characters are considered unencodable */
5752 collstart = p;
5753 collend = p+1;
5754 while (collend < end) {
5755 if ((0 < *collend && *collend < 256) ||
5756 !Py_UNICODE_ISSPACE(*collend) ||
5757 Py_UNICODE_TODECIMAL(*collend))
5758 break;
5759 }
5760 /* cache callback name lookup
5761 * (if not done yet, i.e. it's the first error) */
5762 if (known_errorHandler==-1) {
5763 if ((errors==NULL) || (!strcmp(errors, "strict")))
5764 known_errorHandler = 1;
5765 else if (!strcmp(errors, "replace"))
5766 known_errorHandler = 2;
5767 else if (!strcmp(errors, "ignore"))
5768 known_errorHandler = 3;
5769 else if (!strcmp(errors, "xmlcharrefreplace"))
5770 known_errorHandler = 4;
5771 else
5772 known_errorHandler = 0;
5773 }
5774 switch (known_errorHandler) {
5775 case 1: /* strict */
5776 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
5777 goto onError;
5778 case 2: /* replace */
5779 for (p = collstart; p < collend; ++p)
5780 *output++ = '?';
5781 /* fall through */
5782 case 3: /* ignore */
5783 p = collend;
5784 break;
5785 case 4: /* xmlcharrefreplace */
5786 /* generate replacement (temporarily (mis)uses p) */
5787 for (p = collstart; p < collend; ++p)
5788 output += sprintf(output, "&#%d;", (int)*p);
5789 p = collend;
5790 break;
5791 default:
5792 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
5793 encoding, reason, s, length, &exc,
5794 collstart-s, collend-s, &newpos);
5795 if (repunicode == NULL)
5796 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005797 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00005798 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005799 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
5800 Py_DECREF(repunicode);
5801 goto onError;
5802 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005803 /* generate replacement */
5804 repsize = PyUnicode_GET_SIZE(repunicode);
5805 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
5806 Py_UNICODE ch = *uni2;
5807 if (Py_UNICODE_ISSPACE(ch))
5808 *output++ = ' ';
5809 else {
5810 decimal = Py_UNICODE_TODECIMAL(ch);
5811 if (decimal >= 0)
5812 *output++ = '0' + decimal;
5813 else if (0 < ch && ch < 256)
5814 *output++ = (char)ch;
5815 else {
5816 Py_DECREF(repunicode);
5817 raise_encode_exception(&exc, encoding,
5818 s, length, collstart-s, collend-s, reason);
5819 goto onError;
5820 }
5821 }
5822 }
5823 p = s + newpos;
5824 Py_DECREF(repunicode);
5825 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00005826 }
5827 /* 0-terminate the output string */
5828 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005829 Py_XDECREF(exc);
5830 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00005831 return 0;
5832
Benjamin Peterson29060642009-01-31 22:14:21 +00005833 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005834 Py_XDECREF(exc);
5835 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00005836 return -1;
5837}
5838
Guido van Rossumd57fd912000-03-10 22:53:23 +00005839/* --- Helpers ------------------------------------------------------------ */
5840
Eric Smith8c663262007-08-25 02:26:07 +00005841#include "stringlib/unicodedefs.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00005842#include "stringlib/fastsearch.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00005843#include "stringlib/count.h"
Christian Heimes9cd17752007-11-18 19:35:23 +00005844/* Include _ParseTupleFinds from find.h */
5845#define FROM_UNICODE
Thomas Wouters477c8d52006-05-27 19:21:47 +00005846#include "stringlib/find.h"
5847#include "stringlib/partition.h"
5848
Eric Smith5807c412008-05-11 21:00:57 +00005849#define _Py_InsertThousandsGrouping _PyUnicode_InsertThousandsGrouping
Eric Smitha3b1ac82009-04-03 14:45:06 +00005850#define _Py_InsertThousandsGroupingLocale _PyUnicode_InsertThousandsGroupingLocale
Eric Smith5807c412008-05-11 21:00:57 +00005851#include "stringlib/localeutil.h"
5852
Thomas Wouters477c8d52006-05-27 19:21:47 +00005853/* helper macro to fixup start/end slice values */
5854#define FIX_START_END(obj) \
5855 if (start < 0) \
5856 start += (obj)->length; \
5857 if (start < 0) \
5858 start = 0; \
5859 if (end > (obj)->length) \
5860 end = (obj)->length; \
5861 if (end < 0) \
5862 end += (obj)->length; \
5863 if (end < 0) \
5864 end = 0;
5865
Martin v. Löwis18e16552006-02-15 17:27:45 +00005866Py_ssize_t PyUnicode_Count(PyObject *str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00005867 PyObject *substr,
5868 Py_ssize_t start,
5869 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005870{
Martin v. Löwis18e16552006-02-15 17:27:45 +00005871 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00005872 PyUnicodeObject* str_obj;
5873 PyUnicodeObject* sub_obj;
Tim Petersced69f82003-09-16 20:30:58 +00005874
Thomas Wouters477c8d52006-05-27 19:21:47 +00005875 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
5876 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00005877 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00005878 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
5879 if (!sub_obj) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005880 Py_DECREF(str_obj);
5881 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005882 }
Tim Petersced69f82003-09-16 20:30:58 +00005883
Thomas Wouters477c8d52006-05-27 19:21:47 +00005884 FIX_START_END(str_obj);
Tim Petersced69f82003-09-16 20:30:58 +00005885
Thomas Wouters477c8d52006-05-27 19:21:47 +00005886 result = stringlib_count(
5887 str_obj->str + start, end - start, sub_obj->str, sub_obj->length
5888 );
5889
5890 Py_DECREF(sub_obj);
5891 Py_DECREF(str_obj);
5892
Guido van Rossumd57fd912000-03-10 22:53:23 +00005893 return result;
5894}
5895
Martin v. Löwis18e16552006-02-15 17:27:45 +00005896Py_ssize_t PyUnicode_Find(PyObject *str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00005897 PyObject *sub,
5898 Py_ssize_t start,
5899 Py_ssize_t end,
5900 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005901{
Martin v. Löwis18e16552006-02-15 17:27:45 +00005902 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00005903
Guido van Rossumd57fd912000-03-10 22:53:23 +00005904 str = PyUnicode_FromObject(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00005905 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00005906 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00005907 sub = PyUnicode_FromObject(sub);
5908 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005909 Py_DECREF(str);
5910 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005911 }
Tim Petersced69f82003-09-16 20:30:58 +00005912
Thomas Wouters477c8d52006-05-27 19:21:47 +00005913 if (direction > 0)
5914 result = stringlib_find_slice(
5915 PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
5916 PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
5917 start, end
5918 );
5919 else
5920 result = stringlib_rfind_slice(
5921 PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
5922 PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
5923 start, end
5924 );
5925
Guido van Rossumd57fd912000-03-10 22:53:23 +00005926 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00005927 Py_DECREF(sub);
5928
Guido van Rossumd57fd912000-03-10 22:53:23 +00005929 return result;
5930}
5931
Tim Petersced69f82003-09-16 20:30:58 +00005932static
Guido van Rossumd57fd912000-03-10 22:53:23 +00005933int tailmatch(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00005934 PyUnicodeObject *substring,
5935 Py_ssize_t start,
5936 Py_ssize_t end,
5937 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005938{
Guido van Rossumd57fd912000-03-10 22:53:23 +00005939 if (substring->length == 0)
5940 return 1;
5941
Thomas Wouters477c8d52006-05-27 19:21:47 +00005942 FIX_START_END(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005943
5944 end -= substring->length;
5945 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00005946 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005947
5948 if (direction > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005949 if (Py_UNICODE_MATCH(self, end, substring))
5950 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005951 } else {
5952 if (Py_UNICODE_MATCH(self, start, substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00005953 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005954 }
5955
5956 return 0;
5957}
5958
Martin v. Löwis18e16552006-02-15 17:27:45 +00005959Py_ssize_t PyUnicode_Tailmatch(PyObject *str,
Benjamin Peterson29060642009-01-31 22:14:21 +00005960 PyObject *substr,
5961 Py_ssize_t start,
5962 Py_ssize_t end,
5963 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005964{
Martin v. Löwis18e16552006-02-15 17:27:45 +00005965 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00005966
Guido van Rossumd57fd912000-03-10 22:53:23 +00005967 str = PyUnicode_FromObject(str);
5968 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005969 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005970 substr = PyUnicode_FromObject(substr);
5971 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005972 Py_DECREF(str);
5973 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005974 }
Tim Petersced69f82003-09-16 20:30:58 +00005975
Guido van Rossumd57fd912000-03-10 22:53:23 +00005976 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00005977 (PyUnicodeObject *)substr,
5978 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005979 Py_DECREF(str);
5980 Py_DECREF(substr);
5981 return result;
5982}
5983
Guido van Rossumd57fd912000-03-10 22:53:23 +00005984/* Apply fixfct filter to the Unicode object self and return a
5985 reference to the modified object */
5986
Tim Petersced69f82003-09-16 20:30:58 +00005987static
Guido van Rossumd57fd912000-03-10 22:53:23 +00005988PyObject *fixup(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00005989 int (*fixfct)(PyUnicodeObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00005990{
5991
5992 PyUnicodeObject *u;
5993
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00005994 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005995 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005996 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00005997
5998 Py_UNICODE_COPY(u->str, self->str, self->length);
5999
Tim Peters7a29bd52001-09-12 03:03:31 +00006000 if (!fixfct(u) && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006001 /* fixfct should return TRUE if it modified the buffer. If
6002 FALSE, return a reference to the original buffer instead
6003 (to save space, not time) */
6004 Py_INCREF(self);
6005 Py_DECREF(u);
6006 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006007 }
6008 return (PyObject*) u;
6009}
6010
Tim Petersced69f82003-09-16 20:30:58 +00006011static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006012int fixupper(PyUnicodeObject *self)
6013{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006014 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006015 Py_UNICODE *s = self->str;
6016 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006017
Guido van Rossumd57fd912000-03-10 22:53:23 +00006018 while (len-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006019 register Py_UNICODE ch;
Tim Petersced69f82003-09-16 20:30:58 +00006020
Benjamin Peterson29060642009-01-31 22:14:21 +00006021 ch = Py_UNICODE_TOUPPER(*s);
6022 if (ch != *s) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006023 status = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006024 *s = ch;
6025 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006026 s++;
6027 }
6028
6029 return status;
6030}
6031
Tim Petersced69f82003-09-16 20:30:58 +00006032static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006033int fixlower(PyUnicodeObject *self)
6034{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006035 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006036 Py_UNICODE *s = self->str;
6037 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006038
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039 while (len-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006040 register Py_UNICODE ch;
Tim Petersced69f82003-09-16 20:30:58 +00006041
Benjamin Peterson29060642009-01-31 22:14:21 +00006042 ch = Py_UNICODE_TOLOWER(*s);
6043 if (ch != *s) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006044 status = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006045 *s = ch;
6046 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006047 s++;
6048 }
6049
6050 return status;
6051}
6052
Tim Petersced69f82003-09-16 20:30:58 +00006053static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006054int fixswapcase(PyUnicodeObject *self)
6055{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006056 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006057 Py_UNICODE *s = self->str;
6058 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006059
Guido van Rossumd57fd912000-03-10 22:53:23 +00006060 while (len-- > 0) {
6061 if (Py_UNICODE_ISUPPER(*s)) {
6062 *s = Py_UNICODE_TOLOWER(*s);
6063 status = 1;
6064 } else if (Py_UNICODE_ISLOWER(*s)) {
6065 *s = Py_UNICODE_TOUPPER(*s);
6066 status = 1;
6067 }
6068 s++;
6069 }
6070
6071 return status;
6072}
6073
Tim Petersced69f82003-09-16 20:30:58 +00006074static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006075int fixcapitalize(PyUnicodeObject *self)
6076{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006077 Py_ssize_t len = self->length;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006078 Py_UNICODE *s = self->str;
6079 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006080
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006081 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006082 return 0;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006083 if (Py_UNICODE_ISLOWER(*s)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006084 *s = Py_UNICODE_TOUPPER(*s);
6085 status = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006086 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006087 s++;
6088 while (--len > 0) {
6089 if (Py_UNICODE_ISUPPER(*s)) {
6090 *s = Py_UNICODE_TOLOWER(*s);
6091 status = 1;
6092 }
6093 s++;
6094 }
6095 return status;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006096}
6097
6098static
6099int fixtitle(PyUnicodeObject *self)
6100{
6101 register Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
6102 register Py_UNICODE *e;
6103 int previous_is_cased;
6104
6105 /* Shortcut for single character strings */
6106 if (PyUnicode_GET_SIZE(self) == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006107 Py_UNICODE ch = Py_UNICODE_TOTITLE(*p);
6108 if (*p != ch) {
6109 *p = ch;
6110 return 1;
6111 }
6112 else
6113 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006114 }
Tim Petersced69f82003-09-16 20:30:58 +00006115
Guido van Rossumd57fd912000-03-10 22:53:23 +00006116 e = p + PyUnicode_GET_SIZE(self);
6117 previous_is_cased = 0;
6118 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006119 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00006120
Benjamin Peterson29060642009-01-31 22:14:21 +00006121 if (previous_is_cased)
6122 *p = Py_UNICODE_TOLOWER(ch);
6123 else
6124 *p = Py_UNICODE_TOTITLE(ch);
Tim Petersced69f82003-09-16 20:30:58 +00006125
Benjamin Peterson29060642009-01-31 22:14:21 +00006126 if (Py_UNICODE_ISLOWER(ch) ||
6127 Py_UNICODE_ISUPPER(ch) ||
6128 Py_UNICODE_ISTITLE(ch))
6129 previous_is_cased = 1;
6130 else
6131 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006132 }
6133 return 1;
6134}
6135
Tim Peters8ce9f162004-08-27 01:49:32 +00006136PyObject *
6137PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006138{
Skip Montanaro6543b452004-09-16 03:28:13 +00006139 const Py_UNICODE blank = ' ';
6140 const Py_UNICODE *sep = &blank;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006141 Py_ssize_t seplen = 1;
Tim Peters05eba1f2004-08-27 21:32:02 +00006142 PyUnicodeObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00006143 Py_UNICODE *res_p; /* pointer to free byte in res's string area */
6144 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006145 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
6146 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00006147 PyObject *item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006148 Py_ssize_t sz, i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006149
Tim Peters05eba1f2004-08-27 21:32:02 +00006150 fseq = PySequence_Fast(seq, "");
6151 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006152 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00006153 }
6154
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006155 /* NOTE: the following code can't call back into Python code,
6156 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00006157 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006158
Tim Peters05eba1f2004-08-27 21:32:02 +00006159 seqlen = PySequence_Fast_GET_SIZE(fseq);
6160 /* If empty sequence, return u"". */
6161 if (seqlen == 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006162 res = _PyUnicode_New(0); /* empty sequence; return u"" */
6163 goto Done;
Tim Peters05eba1f2004-08-27 21:32:02 +00006164 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006165 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00006166 /* If singleton sequence with an exact Unicode, return that. */
6167 if (seqlen == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006168 item = items[0];
6169 if (PyUnicode_CheckExact(item)) {
6170 Py_INCREF(item);
6171 res = (PyUnicodeObject *)item;
6172 goto Done;
6173 }
Tim Peters8ce9f162004-08-27 01:49:32 +00006174 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006175 else {
6176 /* Set up sep and seplen */
6177 if (separator == NULL) {
6178 sep = &blank;
6179 seplen = 1;
Tim Peters05eba1f2004-08-27 21:32:02 +00006180 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006181 else {
6182 if (!PyUnicode_Check(separator)) {
6183 PyErr_Format(PyExc_TypeError,
6184 "separator: expected str instance,"
6185 " %.80s found",
6186 Py_TYPE(separator)->tp_name);
6187 goto onError;
6188 }
6189 sep = PyUnicode_AS_UNICODE(separator);
6190 seplen = PyUnicode_GET_SIZE(separator);
Tim Peters05eba1f2004-08-27 21:32:02 +00006191 }
6192 }
6193
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006194 /* There are at least two things to join, or else we have a subclass
6195 * of str in the sequence.
6196 * Do a pre-pass to figure out the total amount of space we'll
6197 * need (sz), and see whether all argument are strings.
6198 */
6199 sz = 0;
6200 for (i = 0; i < seqlen; i++) {
6201 const Py_ssize_t old_sz = sz;
6202 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00006203 if (!PyUnicode_Check(item)) {
6204 PyErr_Format(PyExc_TypeError,
6205 "sequence item %zd: expected str instance,"
6206 " %.80s found",
6207 i, Py_TYPE(item)->tp_name);
6208 goto onError;
6209 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006210 sz += PyUnicode_GET_SIZE(item);
6211 if (i != 0)
6212 sz += seplen;
6213 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
6214 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00006215 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006216 goto onError;
6217 }
6218 }
Tim Petersced69f82003-09-16 20:30:58 +00006219
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006220 res = _PyUnicode_New(sz);
6221 if (res == NULL)
6222 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00006223
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006224 /* Catenate everything. */
6225 res_p = PyUnicode_AS_UNICODE(res);
6226 for (i = 0; i < seqlen; ++i) {
6227 Py_ssize_t itemlen;
6228 item = items[i];
6229 itemlen = PyUnicode_GET_SIZE(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00006230 /* Copy item, and maybe the separator. */
6231 if (i) {
6232 Py_UNICODE_COPY(res_p, sep, seplen);
6233 res_p += seplen;
6234 }
6235 Py_UNICODE_COPY(res_p, PyUnicode_AS_UNICODE(item), itemlen);
6236 res_p += itemlen;
Tim Peters05eba1f2004-08-27 21:32:02 +00006237 }
Tim Peters8ce9f162004-08-27 01:49:32 +00006238
Benjamin Peterson29060642009-01-31 22:14:21 +00006239 Done:
Tim Peters05eba1f2004-08-27 21:32:02 +00006240 Py_DECREF(fseq);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006241 return (PyObject *)res;
6242
Benjamin Peterson29060642009-01-31 22:14:21 +00006243 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00006244 Py_DECREF(fseq);
Tim Peters8ce9f162004-08-27 01:49:32 +00006245 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006246 return NULL;
6247}
6248
Tim Petersced69f82003-09-16 20:30:58 +00006249static
6250PyUnicodeObject *pad(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006251 Py_ssize_t left,
6252 Py_ssize_t right,
6253 Py_UNICODE fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006254{
6255 PyUnicodeObject *u;
6256
6257 if (left < 0)
6258 left = 0;
6259 if (right < 0)
6260 right = 0;
6261
Tim Peters7a29bd52001-09-12 03:03:31 +00006262 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006263 Py_INCREF(self);
6264 return self;
6265 }
6266
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006267 if (left > PY_SSIZE_T_MAX - self->length ||
6268 right > PY_SSIZE_T_MAX - (left + self->length)) {
6269 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
6270 return NULL;
6271 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006272 u = _PyUnicode_New(left + self->length + right);
6273 if (u) {
6274 if (left)
6275 Py_UNICODE_FILL(u->str, fill, left);
6276 Py_UNICODE_COPY(u->str + left, self->str, self->length);
6277 if (right)
6278 Py_UNICODE_FILL(u->str + left + self->length, fill, right);
6279 }
6280
6281 return u;
6282}
6283
Benjamin Peterson29060642009-01-31 22:14:21 +00006284#define SPLIT_APPEND(data, left, right) \
6285 str = PyUnicode_FromUnicode((data) + (left), (right) - (left)); \
6286 if (!str) \
6287 goto onError; \
6288 if (PyList_Append(list, str)) { \
6289 Py_DECREF(str); \
6290 goto onError; \
6291 } \
6292 else \
6293 Py_DECREF(str);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006294
6295static
6296PyObject *split_whitespace(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006297 PyObject *list,
6298 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006299{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006300 register Py_ssize_t i;
6301 register Py_ssize_t j;
6302 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006303 PyObject *str;
Christian Heimes190d79e2008-01-30 11:58:22 +00006304 register const Py_UNICODE *buf = self->str;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006305
6306 for (i = j = 0; i < len; ) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006307 /* find a token */
Benjamin Peterson14339b62009-01-31 16:36:08 +00006308 while (i < len && Py_UNICODE_ISSPACE(buf[i]))
Benjamin Peterson29060642009-01-31 22:14:21 +00006309 i++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006310 j = i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006311 while (i < len && !Py_UNICODE_ISSPACE(buf[i]))
6312 i++;
6313 if (j < i) {
6314 if (maxcount-- <= 0)
6315 break;
6316 SPLIT_APPEND(buf, j, i);
6317 while (i < len && Py_UNICODE_ISSPACE(buf[i]))
6318 i++;
6319 j = i;
6320 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006321 }
6322 if (j < len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006323 SPLIT_APPEND(buf, j, len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006324 }
6325 return list;
6326
Benjamin Peterson29060642009-01-31 22:14:21 +00006327 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006328 Py_DECREF(list);
6329 return NULL;
6330}
6331
6332PyObject *PyUnicode_Splitlines(PyObject *string,
Benjamin Peterson29060642009-01-31 22:14:21 +00006333 int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006334{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006335 register Py_ssize_t i;
6336 register Py_ssize_t j;
6337 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006338 PyObject *list;
6339 PyObject *str;
6340 Py_UNICODE *data;
6341
6342 string = PyUnicode_FromObject(string);
6343 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006344 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006345 data = PyUnicode_AS_UNICODE(string);
6346 len = PyUnicode_GET_SIZE(string);
6347
Guido van Rossumd57fd912000-03-10 22:53:23 +00006348 list = PyList_New(0);
6349 if (!list)
6350 goto onError;
6351
6352 for (i = j = 0; i < len; ) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006353 Py_ssize_t eol;
Tim Petersced69f82003-09-16 20:30:58 +00006354
Benjamin Peterson29060642009-01-31 22:14:21 +00006355 /* Find a line and append it */
6356 while (i < len && !BLOOM_LINEBREAK(data[i]))
6357 i++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006358
Benjamin Peterson29060642009-01-31 22:14:21 +00006359 /* Skip the line break reading CRLF as one line break */
Benjamin Peterson14339b62009-01-31 16:36:08 +00006360 eol = i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006361 if (i < len) {
6362 if (data[i] == '\r' && i + 1 < len &&
6363 data[i+1] == '\n')
6364 i += 2;
6365 else
6366 i++;
6367 if (keepends)
6368 eol = i;
6369 }
6370 SPLIT_APPEND(data, j, eol);
6371 j = i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006372 }
6373 if (j < len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006374 SPLIT_APPEND(data, j, len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006375 }
6376
6377 Py_DECREF(string);
6378 return list;
6379
Benjamin Peterson29060642009-01-31 22:14:21 +00006380 onError:
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00006381 Py_XDECREF(list);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006382 Py_DECREF(string);
6383 return NULL;
6384}
6385
Tim Petersced69f82003-09-16 20:30:58 +00006386static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006387PyObject *split_char(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006388 PyObject *list,
6389 Py_UNICODE ch,
6390 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006391{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006392 register Py_ssize_t i;
6393 register Py_ssize_t j;
6394 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006395 PyObject *str;
Christian Heimes190d79e2008-01-30 11:58:22 +00006396 register const Py_UNICODE *buf = self->str;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006397
6398 for (i = j = 0; i < len; ) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006399 if (buf[i] == ch) {
6400 if (maxcount-- <= 0)
6401 break;
6402 SPLIT_APPEND(buf, j, i);
6403 i = j = i + 1;
6404 } else
6405 i++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006406 }
6407 if (j <= len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006408 SPLIT_APPEND(buf, j, len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006409 }
6410 return list;
6411
Benjamin Peterson29060642009-01-31 22:14:21 +00006412 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006413 Py_DECREF(list);
6414 return NULL;
6415}
6416
Tim Petersced69f82003-09-16 20:30:58 +00006417static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006418PyObject *split_substring(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006419 PyObject *list,
6420 PyUnicodeObject *substring,
6421 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006422{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006423 register Py_ssize_t i;
6424 register Py_ssize_t j;
6425 Py_ssize_t len = self->length;
6426 Py_ssize_t sublen = substring->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006427 PyObject *str;
6428
Guido van Rossumcda4f9a2000-12-19 02:23:19 +00006429 for (i = j = 0; i <= len - sublen; ) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006430 if (Py_UNICODE_MATCH(self, i, substring)) {
6431 if (maxcount-- <= 0)
6432 break;
6433 SPLIT_APPEND(self->str, j, i);
6434 i = j = i + sublen;
6435 } else
6436 i++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006437 }
6438 if (j <= len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006439 SPLIT_APPEND(self->str, j, len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006440 }
6441 return list;
6442
Benjamin Peterson29060642009-01-31 22:14:21 +00006443 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006444 Py_DECREF(list);
6445 return NULL;
6446}
6447
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006448static
6449PyObject *rsplit_whitespace(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006450 PyObject *list,
6451 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006452{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006453 register Py_ssize_t i;
6454 register Py_ssize_t j;
6455 Py_ssize_t len = self->length;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006456 PyObject *str;
Christian Heimes190d79e2008-01-30 11:58:22 +00006457 register const Py_UNICODE *buf = self->str;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006458
6459 for (i = j = len - 1; i >= 0; ) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006460 /* find a token */
Benjamin Peterson14339b62009-01-31 16:36:08 +00006461 while (i >= 0 && Py_UNICODE_ISSPACE(buf[i]))
Benjamin Peterson29060642009-01-31 22:14:21 +00006462 i--;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006463 j = i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006464 while (i >= 0 && !Py_UNICODE_ISSPACE(buf[i]))
6465 i--;
6466 if (j > i) {
6467 if (maxcount-- <= 0)
6468 break;
6469 SPLIT_APPEND(buf, i + 1, j + 1);
6470 while (i >= 0 && Py_UNICODE_ISSPACE(buf[i]))
6471 i--;
6472 j = i;
6473 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006474 }
6475 if (j >= 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006476 SPLIT_APPEND(buf, 0, j + 1);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006477 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00006478 if (PyList_Reverse(list) < 0)
6479 goto onError;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006480 return list;
6481
Benjamin Peterson29060642009-01-31 22:14:21 +00006482 onError:
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006483 Py_DECREF(list);
6484 return NULL;
6485}
6486
Benjamin Peterson14339b62009-01-31 16:36:08 +00006487static
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006488PyObject *rsplit_char(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006489 PyObject *list,
6490 Py_UNICODE ch,
6491 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006492{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006493 register Py_ssize_t i;
6494 register Py_ssize_t j;
6495 Py_ssize_t len = self->length;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006496 PyObject *str;
Christian Heimes190d79e2008-01-30 11:58:22 +00006497 register const Py_UNICODE *buf = self->str;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006498
6499 for (i = j = len - 1; i >= 0; ) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006500 if (buf[i] == ch) {
6501 if (maxcount-- <= 0)
6502 break;
6503 SPLIT_APPEND(buf, i + 1, j + 1);
6504 j = i = i - 1;
6505 } else
6506 i--;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006507 }
Hye-Shik Chang7fc4cf52003-12-23 09:10:16 +00006508 if (j >= -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006509 SPLIT_APPEND(buf, 0, j + 1);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006510 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00006511 if (PyList_Reverse(list) < 0)
6512 goto onError;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006513 return list;
6514
Benjamin Peterson29060642009-01-31 22:14:21 +00006515 onError:
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006516 Py_DECREF(list);
6517 return NULL;
6518}
6519
Benjamin Peterson14339b62009-01-31 16:36:08 +00006520static
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006521PyObject *rsplit_substring(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006522 PyObject *list,
6523 PyUnicodeObject *substring,
6524 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006525{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006526 register Py_ssize_t i;
6527 register Py_ssize_t j;
6528 Py_ssize_t len = self->length;
6529 Py_ssize_t sublen = substring->length;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006530 PyObject *str;
6531
6532 for (i = len - sublen, j = len; i >= 0; ) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006533 if (Py_UNICODE_MATCH(self, i, substring)) {
6534 if (maxcount-- <= 0)
6535 break;
6536 SPLIT_APPEND(self->str, i + sublen, j);
6537 j = i;
6538 i -= sublen;
6539 } else
6540 i--;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006541 }
6542 if (j >= 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006543 SPLIT_APPEND(self->str, 0, j);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006544 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00006545 if (PyList_Reverse(list) < 0)
6546 goto onError;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006547 return list;
6548
Benjamin Peterson29060642009-01-31 22:14:21 +00006549 onError:
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006550 Py_DECREF(list);
6551 return NULL;
6552}
6553
Guido van Rossumd57fd912000-03-10 22:53:23 +00006554#undef SPLIT_APPEND
6555
6556static
6557PyObject *split(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006558 PyUnicodeObject *substring,
6559 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006560{
6561 PyObject *list;
6562
6563 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006564 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006565
6566 list = PyList_New(0);
6567 if (!list)
6568 return NULL;
6569
6570 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006571 return split_whitespace(self,list,maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006572
6573 else if (substring->length == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00006574 return split_char(self,list,substring->str[0],maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006575
6576 else if (substring->length == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006577 Py_DECREF(list);
6578 PyErr_SetString(PyExc_ValueError, "empty separator");
6579 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006580 }
6581 else
Benjamin Peterson29060642009-01-31 22:14:21 +00006582 return split_substring(self,list,substring,maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006583}
6584
Tim Petersced69f82003-09-16 20:30:58 +00006585static
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006586PyObject *rsplit(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006587 PyUnicodeObject *substring,
6588 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006589{
6590 PyObject *list;
6591
6592 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006593 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006594
6595 list = PyList_New(0);
6596 if (!list)
6597 return NULL;
6598
6599 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006600 return rsplit_whitespace(self,list,maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006601
6602 else if (substring->length == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00006603 return rsplit_char(self,list,substring->str[0],maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006604
6605 else if (substring->length == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006606 Py_DECREF(list);
6607 PyErr_SetString(PyExc_ValueError, "empty separator");
6608 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006609 }
6610 else
Benjamin Peterson29060642009-01-31 22:14:21 +00006611 return rsplit_substring(self,list,substring,maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006612}
6613
6614static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006615PyObject *replace(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006616 PyUnicodeObject *str1,
6617 PyUnicodeObject *str2,
6618 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006619{
6620 PyUnicodeObject *u;
6621
6622 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006623 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006624
Thomas Wouters477c8d52006-05-27 19:21:47 +00006625 if (str1->length == str2->length) {
6626 /* same length */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006627 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006628 if (str1->length == 1) {
6629 /* replace characters */
6630 Py_UNICODE u1, u2;
6631 if (!findchar(self->str, self->length, str1->str[0]))
6632 goto nothing;
6633 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
6634 if (!u)
6635 return NULL;
6636 Py_UNICODE_COPY(u->str, self->str, self->length);
6637 u1 = str1->str[0];
6638 u2 = str2->str[0];
6639 for (i = 0; i < u->length; i++)
6640 if (u->str[i] == u1) {
6641 if (--maxcount < 0)
6642 break;
6643 u->str[i] = u2;
6644 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006645 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006646 i = fastsearch(
6647 self->str, self->length, str1->str, str1->length, FAST_SEARCH
Guido van Rossumd57fd912000-03-10 22:53:23 +00006648 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00006649 if (i < 0)
6650 goto nothing;
6651 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
6652 if (!u)
6653 return NULL;
6654 Py_UNICODE_COPY(u->str, self->str, self->length);
6655 while (i <= self->length - str1->length)
6656 if (Py_UNICODE_MATCH(self, i, str1)) {
6657 if (--maxcount < 0)
6658 break;
6659 Py_UNICODE_COPY(u->str+i, str2->str, str2->length);
6660 i += str1->length;
6661 } else
6662 i++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006663 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006664 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006665
6666 Py_ssize_t n, i, j, e;
6667 Py_ssize_t product, new_size, delta;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006668 Py_UNICODE *p;
6669
6670 /* replace strings */
Thomas Wouters477c8d52006-05-27 19:21:47 +00006671 n = stringlib_count(self->str, self->length, str1->str, str1->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006672 if (n > maxcount)
6673 n = maxcount;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006674 if (n == 0)
6675 goto nothing;
6676 /* new_size = self->length + n * (str2->length - str1->length)); */
6677 delta = (str2->length - str1->length);
6678 if (delta == 0) {
6679 new_size = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006680 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006681 product = n * (str2->length - str1->length);
6682 if ((product / (str2->length - str1->length)) != n) {
6683 PyErr_SetString(PyExc_OverflowError,
6684 "replace string is too long");
6685 return NULL;
6686 }
6687 new_size = self->length + product;
6688 if (new_size < 0) {
6689 PyErr_SetString(PyExc_OverflowError,
6690 "replace string is too long");
6691 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006692 }
6693 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00006694 u = _PyUnicode_New(new_size);
6695 if (!u)
6696 return NULL;
6697 i = 0;
6698 p = u->str;
6699 e = self->length - str1->length;
6700 if (str1->length > 0) {
6701 while (n-- > 0) {
6702 /* look for next match */
6703 j = i;
6704 while (j <= e) {
6705 if (Py_UNICODE_MATCH(self, j, str1))
6706 break;
6707 j++;
6708 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006709 if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006710 if (j > e)
6711 break;
6712 /* copy unchanged part [i:j] */
6713 Py_UNICODE_COPY(p, self->str+i, j-i);
6714 p += j - i;
6715 }
6716 /* copy substitution string */
6717 if (str2->length > 0) {
6718 Py_UNICODE_COPY(p, str2->str, str2->length);
6719 p += str2->length;
6720 }
6721 i = j + str1->length;
6722 }
6723 if (i < self->length)
6724 /* copy tail [i:] */
6725 Py_UNICODE_COPY(p, self->str+i, self->length-i);
6726 } else {
6727 /* interleave */
6728 while (n > 0) {
6729 Py_UNICODE_COPY(p, str2->str, str2->length);
6730 p += str2->length;
6731 if (--n <= 0)
6732 break;
6733 *p++ = self->str[i++];
6734 }
6735 Py_UNICODE_COPY(p, self->str+i, self->length-i);
6736 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006737 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006738 return (PyObject *) u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006739
Benjamin Peterson29060642009-01-31 22:14:21 +00006740 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00006741 /* nothing to replace; return original string (when possible) */
6742 if (PyUnicode_CheckExact(self)) {
6743 Py_INCREF(self);
6744 return (PyObject *) self;
6745 }
6746 return PyUnicode_FromUnicode(self->str, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006747}
6748
6749/* --- Unicode Object Methods --------------------------------------------- */
6750
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006751PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00006752 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00006753\n\
6754Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006755characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00006756
6757static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00006758unicode_title(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006759{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006760 return fixup(self, fixtitle);
6761}
6762
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006763PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00006764 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00006765\n\
6766Return a capitalized version of S, i.e. make the first character\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006767have upper case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00006768
6769static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00006770unicode_capitalize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006771{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006772 return fixup(self, fixcapitalize);
6773}
6774
6775#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006776PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00006777 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00006778\n\
6779Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006780normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00006781
6782static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00006783unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006784{
6785 PyObject *list;
6786 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006787 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006788
Guido van Rossumd57fd912000-03-10 22:53:23 +00006789 /* Split into words */
6790 list = split(self, NULL, -1);
6791 if (!list)
6792 return NULL;
6793
6794 /* Capitalize each word */
6795 for (i = 0; i < PyList_GET_SIZE(list); i++) {
6796 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00006797 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006798 if (item == NULL)
6799 goto onError;
6800 Py_DECREF(PyList_GET_ITEM(list, i));
6801 PyList_SET_ITEM(list, i, item);
6802 }
6803
6804 /* Join the words to form a new string */
6805 item = PyUnicode_Join(NULL, list);
6806
Benjamin Peterson29060642009-01-31 22:14:21 +00006807 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006808 Py_DECREF(list);
6809 return (PyObject *)item;
6810}
6811#endif
6812
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006813/* Argument converter. Coerces to a single unicode character */
6814
6815static int
6816convert_uc(PyObject *obj, void *addr)
6817{
Benjamin Peterson14339b62009-01-31 16:36:08 +00006818 Py_UNICODE *fillcharloc = (Py_UNICODE *)addr;
6819 PyObject *uniobj;
6820 Py_UNICODE *unistr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006821
Benjamin Peterson14339b62009-01-31 16:36:08 +00006822 uniobj = PyUnicode_FromObject(obj);
6823 if (uniobj == NULL) {
6824 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00006825 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +00006826 return 0;
6827 }
6828 if (PyUnicode_GET_SIZE(uniobj) != 1) {
6829 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00006830 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +00006831 Py_DECREF(uniobj);
6832 return 0;
6833 }
6834 unistr = PyUnicode_AS_UNICODE(uniobj);
6835 *fillcharloc = unistr[0];
6836 Py_DECREF(uniobj);
6837 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006838}
6839
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006840PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00006841 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00006842\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00006843Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006844done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +00006845
6846static PyObject *
6847unicode_center(PyUnicodeObject *self, PyObject *args)
6848{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006849 Py_ssize_t marg, left;
6850 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006851 Py_UNICODE fillchar = ' ';
Guido van Rossumd57fd912000-03-10 22:53:23 +00006852
Thomas Woutersde017742006-02-16 19:34:37 +00006853 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00006854 return NULL;
6855
Tim Peters7a29bd52001-09-12 03:03:31 +00006856 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006857 Py_INCREF(self);
6858 return (PyObject*) self;
6859 }
6860
6861 marg = width - self->length;
6862 left = marg / 2 + (marg & width & 1);
6863
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006864 return (PyObject*) pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006865}
6866
Marc-André Lemburge5034372000-08-08 08:04:29 +00006867#if 0
6868
6869/* This code should go into some future Unicode collation support
6870 module. The basic comparison should compare ordinals on a naive
Georg Brandlc6c31782009-06-08 13:41:29 +00006871 basis (this is what Java does and thus Jython too). */
Marc-André Lemburge5034372000-08-08 08:04:29 +00006872
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006873/* speedy UTF-16 code point order comparison */
6874/* gleaned from: */
6875/* http://www-4.ibm.com/software/developer/library/utf16.html?dwzone=unicode */
6876
Marc-André Lemburge12896e2000-07-07 17:51:08 +00006877static short utf16Fixup[32] =
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006878{
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006879 0, 0, 0, 0, 0, 0, 0, 0,
Tim Petersced69f82003-09-16 20:30:58 +00006880 0, 0, 0, 0, 0, 0, 0, 0,
6881 0, 0, 0, 0, 0, 0, 0, 0,
Marc-André Lemburge12896e2000-07-07 17:51:08 +00006882 0, 0, 0, 0x2000, -0x800, -0x800, -0x800, -0x800
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006883};
6884
Guido van Rossumd57fd912000-03-10 22:53:23 +00006885static int
6886unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
6887{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006888 Py_ssize_t len1, len2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006889
Guido van Rossumd57fd912000-03-10 22:53:23 +00006890 Py_UNICODE *s1 = str1->str;
6891 Py_UNICODE *s2 = str2->str;
6892
6893 len1 = str1->length;
6894 len2 = str2->length;
Tim Petersced69f82003-09-16 20:30:58 +00006895
Guido van Rossumd57fd912000-03-10 22:53:23 +00006896 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00006897 Py_UNICODE c1, c2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006898
6899 c1 = *s1++;
6900 c2 = *s2++;
Fredrik Lundh45714e92001-06-26 16:39:36 +00006901
Benjamin Peterson29060642009-01-31 22:14:21 +00006902 if (c1 > (1<<11) * 26)
6903 c1 += utf16Fixup[c1>>11];
6904 if (c2 > (1<<11) * 26)
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006905 c2 += utf16Fixup[c2>>11];
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006906 /* now c1 and c2 are in UTF-32-compatible order */
Fredrik Lundh45714e92001-06-26 16:39:36 +00006907
6908 if (c1 != c2)
6909 return (c1 < c2) ? -1 : 1;
Tim Petersced69f82003-09-16 20:30:58 +00006910
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006911 len1--; len2--;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006912 }
6913
6914 return (len1 < len2) ? -1 : (len1 != len2);
6915}
6916
Marc-André Lemburge5034372000-08-08 08:04:29 +00006917#else
6918
6919static int
6920unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
6921{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006922 register Py_ssize_t len1, len2;
Marc-André Lemburge5034372000-08-08 08:04:29 +00006923
6924 Py_UNICODE *s1 = str1->str;
6925 Py_UNICODE *s2 = str2->str;
6926
6927 len1 = str1->length;
6928 len2 = str2->length;
Tim Petersced69f82003-09-16 20:30:58 +00006929
Marc-André Lemburge5034372000-08-08 08:04:29 +00006930 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00006931 Py_UNICODE c1, c2;
Marc-André Lemburge5034372000-08-08 08:04:29 +00006932
Fredrik Lundh45714e92001-06-26 16:39:36 +00006933 c1 = *s1++;
6934 c2 = *s2++;
6935
6936 if (c1 != c2)
6937 return (c1 < c2) ? -1 : 1;
6938
Marc-André Lemburge5034372000-08-08 08:04:29 +00006939 len1--; len2--;
6940 }
6941
6942 return (len1 < len2) ? -1 : (len1 != len2);
6943}
6944
6945#endif
6946
Guido van Rossumd57fd912000-03-10 22:53:23 +00006947int PyUnicode_Compare(PyObject *left,
Benjamin Peterson29060642009-01-31 22:14:21 +00006948 PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006949{
Guido van Rossum09dc34f2007-05-04 04:17:33 +00006950 if (PyUnicode_Check(left) && PyUnicode_Check(right))
6951 return unicode_compare((PyUnicodeObject *)left,
6952 (PyUnicodeObject *)right);
Guido van Rossum09dc34f2007-05-04 04:17:33 +00006953 PyErr_Format(PyExc_TypeError,
6954 "Can't compare %.100s and %.100s",
6955 left->ob_type->tp_name,
6956 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006957 return -1;
6958}
6959
Martin v. Löwis5b222132007-06-10 09:51:05 +00006960int
6961PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
6962{
6963 int i;
6964 Py_UNICODE *id;
6965 assert(PyUnicode_Check(uni));
6966 id = PyUnicode_AS_UNICODE(uni);
6967 /* Compare Unicode string and source character set string */
6968 for (i = 0; id[i] && str[i]; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00006969 if (id[i] != str[i])
6970 return ((int)id[i] < (int)str[i]) ? -1 : 1;
Benjamin Petersonbb81c8c2010-01-09 21:54:39 +00006971 /* This check keeps Python strings that end in '\0' from comparing equal
6972 to C strings identical up to that point. */
6973 if (PyUnicode_GET_SIZE(uni) != i)
6974 /* We'll say the Python string is longer. */
6975 return 1;
Martin v. Löwis5b222132007-06-10 09:51:05 +00006976 if (id[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00006977 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00006978 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00006979 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00006980 return 0;
6981}
6982
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00006983
Benjamin Peterson29060642009-01-31 22:14:21 +00006984#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +00006985 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00006986
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00006987PyObject *PyUnicode_RichCompare(PyObject *left,
6988 PyObject *right,
6989 int op)
6990{
6991 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006992
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00006993 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
6994 PyObject *v;
6995 if (((PyUnicodeObject *) left)->length !=
6996 ((PyUnicodeObject *) right)->length) {
6997 if (op == Py_EQ) {
6998 Py_INCREF(Py_False);
6999 return Py_False;
7000 }
7001 if (op == Py_NE) {
7002 Py_INCREF(Py_True);
7003 return Py_True;
7004 }
7005 }
7006 if (left == right)
7007 result = 0;
7008 else
7009 result = unicode_compare((PyUnicodeObject *)left,
7010 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007011
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007012 /* Convert the return value to a Boolean */
7013 switch (op) {
7014 case Py_EQ:
7015 v = TEST_COND(result == 0);
7016 break;
7017 case Py_NE:
7018 v = TEST_COND(result != 0);
7019 break;
7020 case Py_LE:
7021 v = TEST_COND(result <= 0);
7022 break;
7023 case Py_GE:
7024 v = TEST_COND(result >= 0);
7025 break;
7026 case Py_LT:
7027 v = TEST_COND(result == -1);
7028 break;
7029 case Py_GT:
7030 v = TEST_COND(result == 1);
7031 break;
7032 default:
7033 PyErr_BadArgument();
7034 return NULL;
7035 }
7036 Py_INCREF(v);
7037 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007038 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007039
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00007040 Py_INCREF(Py_NotImplemented);
7041 return Py_NotImplemented;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007042}
7043
Guido van Rossum403d68b2000-03-13 15:55:09 +00007044int PyUnicode_Contains(PyObject *container,
Benjamin Peterson29060642009-01-31 22:14:21 +00007045 PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +00007046{
Thomas Wouters477c8d52006-05-27 19:21:47 +00007047 PyObject *str, *sub;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007048 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007049
7050 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +00007051 sub = PyUnicode_FromObject(element);
7052 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007053 PyErr_Format(PyExc_TypeError,
7054 "'in <string>' requires string as left operand, not %s",
7055 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007056 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007057 }
7058
Thomas Wouters477c8d52006-05-27 19:21:47 +00007059 str = PyUnicode_FromObject(container);
7060 if (!str) {
7061 Py_DECREF(sub);
7062 return -1;
7063 }
7064
7065 result = stringlib_contains_obj(str, sub);
7066
7067 Py_DECREF(str);
7068 Py_DECREF(sub);
7069
Guido van Rossum403d68b2000-03-13 15:55:09 +00007070 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007071}
7072
Guido van Rossumd57fd912000-03-10 22:53:23 +00007073/* Concat to string or Unicode object giving a new Unicode object. */
7074
7075PyObject *PyUnicode_Concat(PyObject *left,
Benjamin Peterson29060642009-01-31 22:14:21 +00007076 PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007077{
7078 PyUnicodeObject *u = NULL, *v = NULL, *w;
7079
7080 /* Coerce the two arguments */
7081 u = (PyUnicodeObject *)PyUnicode_FromObject(left);
7082 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007083 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007084 v = (PyUnicodeObject *)PyUnicode_FromObject(right);
7085 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007086 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007087
7088 /* Shortcuts */
7089 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007090 Py_DECREF(v);
7091 return (PyObject *)u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007092 }
7093 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007094 Py_DECREF(u);
7095 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007096 }
7097
7098 /* Concat the two Unicode strings */
7099 w = _PyUnicode_New(u->length + v->length);
7100 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007101 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007102 Py_UNICODE_COPY(w->str, u->str, u->length);
7103 Py_UNICODE_COPY(w->str + u->length, v->str, v->length);
7104
7105 Py_DECREF(u);
7106 Py_DECREF(v);
7107 return (PyObject *)w;
7108
Benjamin Peterson29060642009-01-31 22:14:21 +00007109 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007110 Py_XDECREF(u);
7111 Py_XDECREF(v);
7112 return NULL;
7113}
7114
Walter Dörwald1ab83302007-05-18 17:15:44 +00007115void
7116PyUnicode_Append(PyObject **pleft, PyObject *right)
7117{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007118 PyObject *new;
7119 if (*pleft == NULL)
7120 return;
7121 if (right == NULL || !PyUnicode_Check(*pleft)) {
7122 Py_DECREF(*pleft);
7123 *pleft = NULL;
7124 return;
7125 }
7126 new = PyUnicode_Concat(*pleft, right);
7127 Py_DECREF(*pleft);
7128 *pleft = new;
Walter Dörwald1ab83302007-05-18 17:15:44 +00007129}
7130
7131void
7132PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
7133{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007134 PyUnicode_Append(pleft, right);
7135 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +00007136}
7137
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007138PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007139 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007140\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00007141Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007142string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007143interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007144
7145static PyObject *
7146unicode_count(PyUnicodeObject *self, PyObject *args)
7147{
7148 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007149 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007150 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007151 PyObject *result;
7152
Guido van Rossumb8872e62000-05-09 14:14:27 +00007153 if (!PyArg_ParseTuple(args, "O|O&O&:count", &substring,
Benjamin Peterson29060642009-01-31 22:14:21 +00007154 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007155 return NULL;
7156
7157 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Thomas Wouters477c8d52006-05-27 19:21:47 +00007158 (PyObject *)substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007159 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007160 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007161
Thomas Wouters477c8d52006-05-27 19:21:47 +00007162 FIX_START_END(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007163
Christian Heimes217cfd12007-12-02 14:31:20 +00007164 result = PyLong_FromSsize_t(
Thomas Wouters477c8d52006-05-27 19:21:47 +00007165 stringlib_count(self->str + start, end - start,
7166 substring->str, substring->length)
7167 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007168
7169 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007170
Guido van Rossumd57fd912000-03-10 22:53:23 +00007171 return result;
7172}
7173
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007174PyDoc_STRVAR(encode__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007175 "S.encode([encoding[, errors]]) -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007176\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00007177Encode S using the codec registered for encoding. encoding defaults\n\
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007178to the default encoding. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +00007179handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007180a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
7181'xmlcharrefreplace' as well as any other name registered with\n\
7182codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007183
7184static PyObject *
7185unicode_encode(PyUnicodeObject *self, PyObject *args)
7186{
7187 char *encoding = NULL;
7188 char *errors = NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007189 PyObject *v;
Guido van Rossum35d94282007-08-27 18:20:11 +00007190
Guido van Rossumd57fd912000-03-10 22:53:23 +00007191 if (!PyArg_ParseTuple(args, "|ss:encode", &encoding, &errors))
7192 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00007193 v = PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00007194 if (v == NULL)
7195 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00007196 if (!PyBytes_Check(v)) {
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007197 PyErr_Format(PyExc_TypeError,
Guido van Rossumf15a29f2007-05-04 00:41:39 +00007198 "encoder did not return a bytes object "
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007199 "(type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00007200 Py_TYPE(v)->tp_name);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007201 Py_DECREF(v);
7202 return NULL;
7203 }
7204 return v;
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00007205
Benjamin Peterson29060642009-01-31 22:14:21 +00007206 onError:
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00007207 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007208}
7209
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007210PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007211 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007212\n\
7213Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007214If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007215
7216static PyObject*
7217unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
7218{
7219 Py_UNICODE *e;
7220 Py_UNICODE *p;
7221 Py_UNICODE *q;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007222 Py_UNICODE *qe;
7223 Py_ssize_t i, j, incr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007224 PyUnicodeObject *u;
7225 int tabsize = 8;
7226
7227 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00007228 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007229
Thomas Wouters7e474022000-07-16 12:04:32 +00007230 /* First pass: determine size of output string */
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007231 i = 0; /* chars up to and including most recent \n or \r */
7232 j = 0; /* chars since most recent \n or \r (use in tab calculations) */
7233 e = self->str + self->length; /* end of input */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007234 for (p = self->str; p < e; p++)
7235 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007236 if (tabsize > 0) {
7237 incr = tabsize - (j % tabsize); /* cannot overflow */
7238 if (j > PY_SSIZE_T_MAX - incr)
7239 goto overflow1;
7240 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007241 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007242 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007243 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007244 if (j > PY_SSIZE_T_MAX - 1)
7245 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007246 j++;
7247 if (*p == '\n' || *p == '\r') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007248 if (i > PY_SSIZE_T_MAX - j)
7249 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007250 i += j;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007251 j = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007252 }
7253 }
7254
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007255 if (i > PY_SSIZE_T_MAX - j)
Benjamin Peterson29060642009-01-31 22:14:21 +00007256 goto overflow1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007257
Guido van Rossumd57fd912000-03-10 22:53:23 +00007258 /* Second pass: create output string and fill it */
7259 u = _PyUnicode_New(i + j);
7260 if (!u)
7261 return NULL;
7262
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007263 j = 0; /* same as in first pass */
7264 q = u->str; /* next output char */
7265 qe = u->str + u->length; /* end of output */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007266
7267 for (p = self->str; p < e; p++)
7268 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007269 if (tabsize > 0) {
7270 i = tabsize - (j % tabsize);
7271 j += i;
7272 while (i--) {
7273 if (q >= qe)
7274 goto overflow2;
7275 *q++ = ' ';
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007276 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007277 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007278 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007279 else {
7280 if (q >= qe)
7281 goto overflow2;
7282 *q++ = *p;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007283 j++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007284 if (*p == '\n' || *p == '\r')
7285 j = 0;
7286 }
7287
7288 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007289
7290 overflow2:
7291 Py_DECREF(u);
7292 overflow1:
7293 PyErr_SetString(PyExc_OverflowError, "new string is too long");
7294 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007295}
7296
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007297PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007298 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007299\n\
7300Return the lowest index in S where substring sub is found,\n\
Guido van Rossum806c2462007-08-06 23:33:07 +00007301such that sub is contained within s[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007302arguments start and end are interpreted as in slice notation.\n\
7303\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007304Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007305
7306static PyObject *
7307unicode_find(PyUnicodeObject *self, PyObject *args)
7308{
Thomas Wouters477c8d52006-05-27 19:21:47 +00007309 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00007310 Py_ssize_t start;
7311 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007312 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007313
Christian Heimes9cd17752007-11-18 19:35:23 +00007314 if (!_ParseTupleFinds(args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007315 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007316
Thomas Wouters477c8d52006-05-27 19:21:47 +00007317 result = stringlib_find_slice(
7318 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
7319 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
7320 start, end
7321 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007322
7323 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007324
Christian Heimes217cfd12007-12-02 14:31:20 +00007325 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007326}
7327
7328static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00007329unicode_getitem(PyUnicodeObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007330{
7331 if (index < 0 || index >= self->length) {
7332 PyErr_SetString(PyExc_IndexError, "string index out of range");
7333 return NULL;
7334 }
7335
7336 return (PyObject*) PyUnicode_FromUnicode(&self->str[index], 1);
7337}
7338
Guido van Rossumc2504932007-09-18 19:42:40 +00007339/* Believe it or not, this produces the same value for ASCII strings
7340 as string_hash(). */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007341static long
Neil Schemenauerf8c37d12007-09-07 20:49:04 +00007342unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007343{
Guido van Rossumc2504932007-09-18 19:42:40 +00007344 Py_ssize_t len;
7345 Py_UNICODE *p;
7346 long x;
7347
7348 if (self->hash != -1)
7349 return self->hash;
Christian Heimes90aa7642007-12-19 02:45:37 +00007350 len = Py_SIZE(self);
Guido van Rossumc2504932007-09-18 19:42:40 +00007351 p = self->str;
7352 x = *p << 7;
7353 while (--len >= 0)
7354 x = (1000003*x) ^ *p++;
Christian Heimes90aa7642007-12-19 02:45:37 +00007355 x ^= Py_SIZE(self);
Guido van Rossumc2504932007-09-18 19:42:40 +00007356 if (x == -1)
7357 x = -2;
7358 self->hash = x;
7359 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007360}
7361
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007362PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007363 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007364\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007365Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007366
7367static PyObject *
7368unicode_index(PyUnicodeObject *self, PyObject *args)
7369{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007370 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007371 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00007372 Py_ssize_t start;
7373 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007374
Christian Heimes9cd17752007-11-18 19:35:23 +00007375 if (!_ParseTupleFinds(args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007376 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007377
Thomas Wouters477c8d52006-05-27 19:21:47 +00007378 result = stringlib_find_slice(
7379 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
7380 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
7381 start, end
7382 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007383
7384 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007385
Guido van Rossumd57fd912000-03-10 22:53:23 +00007386 if (result < 0) {
7387 PyErr_SetString(PyExc_ValueError, "substring not found");
7388 return NULL;
7389 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00007390
Christian Heimes217cfd12007-12-02 14:31:20 +00007391 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007392}
7393
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007394PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007395 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007396\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007397Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007398at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007399
7400static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007401unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007402{
7403 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7404 register const Py_UNICODE *e;
7405 int cased;
7406
Guido van Rossumd57fd912000-03-10 22:53:23 +00007407 /* Shortcut for single character strings */
7408 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007409 return PyBool_FromLong(Py_UNICODE_ISLOWER(*p));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007410
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007411 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007412 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007413 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007414
Guido van Rossumd57fd912000-03-10 22:53:23 +00007415 e = p + PyUnicode_GET_SIZE(self);
7416 cased = 0;
7417 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007418 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007419
Benjamin Peterson29060642009-01-31 22:14:21 +00007420 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
7421 return PyBool_FromLong(0);
7422 else if (!cased && Py_UNICODE_ISLOWER(ch))
7423 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007424 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007425 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007426}
7427
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007428PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007429 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007430\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007431Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007432at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007433
7434static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007435unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007436{
7437 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7438 register const Py_UNICODE *e;
7439 int cased;
7440
Guido van Rossumd57fd912000-03-10 22:53:23 +00007441 /* Shortcut for single character strings */
7442 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007443 return PyBool_FromLong(Py_UNICODE_ISUPPER(*p) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007444
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007445 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007446 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007447 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007448
Guido van Rossumd57fd912000-03-10 22:53:23 +00007449 e = p + PyUnicode_GET_SIZE(self);
7450 cased = 0;
7451 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007452 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007453
Benjamin Peterson29060642009-01-31 22:14:21 +00007454 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
7455 return PyBool_FromLong(0);
7456 else if (!cased && Py_UNICODE_ISUPPER(ch))
7457 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007458 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007459 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007460}
7461
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007462PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007463 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007464\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007465Return True if S is a titlecased string and there is at least one\n\
7466character in S, i.e. upper- and titlecase characters may only\n\
7467follow uncased characters and lowercase characters only cased ones.\n\
7468Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007469
7470static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007471unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007472{
7473 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7474 register const Py_UNICODE *e;
7475 int cased, previous_is_cased;
7476
Guido van Rossumd57fd912000-03-10 22:53:23 +00007477 /* Shortcut for single character strings */
7478 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007479 return PyBool_FromLong((Py_UNICODE_ISTITLE(*p) != 0) ||
7480 (Py_UNICODE_ISUPPER(*p) != 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007481
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007482 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007483 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007484 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007485
Guido van Rossumd57fd912000-03-10 22:53:23 +00007486 e = p + PyUnicode_GET_SIZE(self);
7487 cased = 0;
7488 previous_is_cased = 0;
7489 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007490 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007491
Benjamin Peterson29060642009-01-31 22:14:21 +00007492 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
7493 if (previous_is_cased)
7494 return PyBool_FromLong(0);
7495 previous_is_cased = 1;
7496 cased = 1;
7497 }
7498 else if (Py_UNICODE_ISLOWER(ch)) {
7499 if (!previous_is_cased)
7500 return PyBool_FromLong(0);
7501 previous_is_cased = 1;
7502 cased = 1;
7503 }
7504 else
7505 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007506 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007507 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007508}
7509
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007510PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007511 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007512\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007513Return True if all characters in S are whitespace\n\
7514and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007515
7516static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007517unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007518{
7519 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7520 register const Py_UNICODE *e;
7521
Guido van Rossumd57fd912000-03-10 22:53:23 +00007522 /* Shortcut for single character strings */
7523 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007524 Py_UNICODE_ISSPACE(*p))
7525 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007526
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007527 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007528 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007529 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007530
Guido van Rossumd57fd912000-03-10 22:53:23 +00007531 e = p + PyUnicode_GET_SIZE(self);
7532 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007533 if (!Py_UNICODE_ISSPACE(*p))
7534 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007535 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007536 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007537}
7538
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007539PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007540 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007541\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007542Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007543and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007544
7545static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007546unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007547{
7548 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7549 register const Py_UNICODE *e;
7550
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007551 /* Shortcut for single character strings */
7552 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007553 Py_UNICODE_ISALPHA(*p))
7554 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007555
7556 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007557 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007558 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007559
7560 e = p + PyUnicode_GET_SIZE(self);
7561 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007562 if (!Py_UNICODE_ISALPHA(*p))
7563 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007564 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007565 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007566}
7567
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007568PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007569 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007570\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007571Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007572and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007573
7574static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007575unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007576{
7577 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7578 register const Py_UNICODE *e;
7579
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007580 /* Shortcut for single character strings */
7581 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007582 Py_UNICODE_ISALNUM(*p))
7583 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007584
7585 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007586 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007587 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007588
7589 e = p + PyUnicode_GET_SIZE(self);
7590 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007591 if (!Py_UNICODE_ISALNUM(*p))
7592 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007593 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007594 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007595}
7596
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007597PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007598 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007599\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007600Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007601False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007602
7603static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007604unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007605{
7606 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7607 register const Py_UNICODE *e;
7608
Guido van Rossumd57fd912000-03-10 22:53:23 +00007609 /* Shortcut for single character strings */
7610 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007611 Py_UNICODE_ISDECIMAL(*p))
7612 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007613
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007614 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007615 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007616 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007617
Guido van Rossumd57fd912000-03-10 22:53:23 +00007618 e = p + PyUnicode_GET_SIZE(self);
7619 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007620 if (!Py_UNICODE_ISDECIMAL(*p))
7621 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007622 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007623 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007624}
7625
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007626PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007627 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007628\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007629Return True if all characters in S are digits\n\
7630and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007631
7632static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007633unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007634{
7635 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7636 register const Py_UNICODE *e;
7637
Guido van Rossumd57fd912000-03-10 22:53:23 +00007638 /* Shortcut for single character strings */
7639 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007640 Py_UNICODE_ISDIGIT(*p))
7641 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007642
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007643 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007644 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007645 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007646
Guido van Rossumd57fd912000-03-10 22:53:23 +00007647 e = p + PyUnicode_GET_SIZE(self);
7648 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007649 if (!Py_UNICODE_ISDIGIT(*p))
7650 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007651 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007652 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007653}
7654
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007655PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007656 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007657\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007658Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007659False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007660
7661static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007662unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007663{
7664 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7665 register const Py_UNICODE *e;
7666
Guido van Rossumd57fd912000-03-10 22:53:23 +00007667 /* Shortcut for single character strings */
7668 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007669 Py_UNICODE_ISNUMERIC(*p))
7670 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007671
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007672 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007673 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007674 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007675
Guido van Rossumd57fd912000-03-10 22:53:23 +00007676 e = p + PyUnicode_GET_SIZE(self);
7677 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007678 if (!Py_UNICODE_ISNUMERIC(*p))
7679 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007680 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007681 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007682}
7683
Martin v. Löwis47383402007-08-15 07:32:56 +00007684int
7685PyUnicode_IsIdentifier(PyObject *self)
7686{
7687 register const Py_UNICODE *p = PyUnicode_AS_UNICODE((PyUnicodeObject*)self);
7688 register const Py_UNICODE *e;
7689
7690 /* Special case for empty strings */
7691 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007692 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +00007693
7694 /* PEP 3131 says that the first character must be in
7695 XID_Start and subsequent characters in XID_Continue,
7696 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +00007697 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +00007698 letters, digits, underscore). However, given the current
7699 definition of XID_Start and XID_Continue, it is sufficient
7700 to check just for these, except that _ must be allowed
7701 as starting an identifier. */
7702 if (!_PyUnicode_IsXidStart(*p) && *p != 0x5F /* LOW LINE */)
7703 return 0;
7704
7705 e = p + PyUnicode_GET_SIZE(self);
7706 for (p++; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007707 if (!_PyUnicode_IsXidContinue(*p))
7708 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +00007709 }
7710 return 1;
7711}
7712
7713PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007714 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +00007715\n\
7716Return True if S is a valid identifier according\n\
7717to the language definition.");
7718
7719static PyObject*
7720unicode_isidentifier(PyObject *self)
7721{
7722 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
7723}
7724
Georg Brandl559e5d72008-06-11 18:37:52 +00007725PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007726 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +00007727\n\
7728Return True if all characters in S are considered\n\
7729printable in repr() or S is empty, False otherwise.");
7730
7731static PyObject*
7732unicode_isprintable(PyObject *self)
7733{
7734 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7735 register const Py_UNICODE *e;
7736
7737 /* Shortcut for single character strings */
7738 if (PyUnicode_GET_SIZE(self) == 1 && Py_UNICODE_ISPRINTABLE(*p)) {
7739 Py_RETURN_TRUE;
7740 }
7741
7742 e = p + PyUnicode_GET_SIZE(self);
7743 for (; p < e; p++) {
7744 if (!Py_UNICODE_ISPRINTABLE(*p)) {
7745 Py_RETURN_FALSE;
7746 }
7747 }
7748 Py_RETURN_TRUE;
7749}
7750
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007751PyDoc_STRVAR(join__doc__,
Georg Brandl628e6f92009-10-27 20:24:45 +00007752 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007753\n\
7754Return a string which is the concatenation of the strings in the\n\
Georg Brandl628e6f92009-10-27 20:24:45 +00007755iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007756
7757static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007758unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007759{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007760 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007761}
7762
Martin v. Löwis18e16552006-02-15 17:27:45 +00007763static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +00007764unicode_length(PyUnicodeObject *self)
7765{
7766 return self->length;
7767}
7768
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007769PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007770 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007771\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00007772Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007773done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007774
7775static PyObject *
7776unicode_ljust(PyUnicodeObject *self, PyObject *args)
7777{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007778 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007779 Py_UNICODE fillchar = ' ';
7780
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007781 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007782 return NULL;
7783
Tim Peters7a29bd52001-09-12 03:03:31 +00007784 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00007785 Py_INCREF(self);
7786 return (PyObject*) self;
7787 }
7788
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007789 return (PyObject*) pad(self, 0, width - self->length, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007790}
7791
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007792PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007793 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007794\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007795Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007796
7797static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007798unicode_lower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007799{
Guido van Rossumd57fd912000-03-10 22:53:23 +00007800 return fixup(self, fixlower);
7801}
7802
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007803#define LEFTSTRIP 0
7804#define RIGHTSTRIP 1
7805#define BOTHSTRIP 2
7806
7807/* Arrays indexed by above */
7808static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
7809
7810#define STRIPNAME(i) (stripformat[i]+3)
7811
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007812/* externally visible for str.strip(unicode) */
7813PyObject *
7814_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
7815{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007816 Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
7817 Py_ssize_t len = PyUnicode_GET_SIZE(self);
7818 Py_UNICODE *sep = PyUnicode_AS_UNICODE(sepobj);
7819 Py_ssize_t seplen = PyUnicode_GET_SIZE(sepobj);
7820 Py_ssize_t i, j;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007821
Benjamin Peterson29060642009-01-31 22:14:21 +00007822 BLOOM_MASK sepmask = make_bloom_mask(sep, seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007823
Benjamin Peterson14339b62009-01-31 16:36:08 +00007824 i = 0;
7825 if (striptype != RIGHTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007826 while (i < len && BLOOM_MEMBER(sepmask, s[i], sep, seplen)) {
7827 i++;
7828 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007829 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007830
Benjamin Peterson14339b62009-01-31 16:36:08 +00007831 j = len;
7832 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007833 do {
7834 j--;
7835 } while (j >= i && BLOOM_MEMBER(sepmask, s[j], sep, seplen));
7836 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007837 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007838
Benjamin Peterson14339b62009-01-31 16:36:08 +00007839 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007840 Py_INCREF(self);
7841 return (PyObject*)self;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007842 }
7843 else
Benjamin Peterson29060642009-01-31 22:14:21 +00007844 return PyUnicode_FromUnicode(s+i, j-i);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007845}
7846
Guido van Rossumd57fd912000-03-10 22:53:23 +00007847
7848static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007849do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007850{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007851 Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
7852 Py_ssize_t len = PyUnicode_GET_SIZE(self), i, j;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007853
Benjamin Peterson14339b62009-01-31 16:36:08 +00007854 i = 0;
7855 if (striptype != RIGHTSTRIP) {
7856 while (i < len && Py_UNICODE_ISSPACE(s[i])) {
7857 i++;
7858 }
7859 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007860
Benjamin Peterson14339b62009-01-31 16:36:08 +00007861 j = len;
7862 if (striptype != LEFTSTRIP) {
7863 do {
7864 j--;
7865 } while (j >= i && Py_UNICODE_ISSPACE(s[j]));
7866 j++;
7867 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007868
Benjamin Peterson14339b62009-01-31 16:36:08 +00007869 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
7870 Py_INCREF(self);
7871 return (PyObject*)self;
7872 }
7873 else
7874 return PyUnicode_FromUnicode(s+i, j-i);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007875}
7876
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007877
7878static PyObject *
7879do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
7880{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007881 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007882
Benjamin Peterson14339b62009-01-31 16:36:08 +00007883 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
7884 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007885
Benjamin Peterson14339b62009-01-31 16:36:08 +00007886 if (sep != NULL && sep != Py_None) {
7887 if (PyUnicode_Check(sep))
7888 return _PyUnicode_XStrip(self, striptype, sep);
7889 else {
7890 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00007891 "%s arg must be None or str",
7892 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +00007893 return NULL;
7894 }
7895 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007896
Benjamin Peterson14339b62009-01-31 16:36:08 +00007897 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007898}
7899
7900
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007901PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007902 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007903\n\
7904Return a copy of the string S with leading and trailing\n\
7905whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007906If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007907
7908static PyObject *
7909unicode_strip(PyUnicodeObject *self, PyObject *args)
7910{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007911 if (PyTuple_GET_SIZE(args) == 0)
7912 return do_strip(self, BOTHSTRIP); /* Common case */
7913 else
7914 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007915}
7916
7917
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007918PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007919 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007920\n\
7921Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007922If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007923
7924static PyObject *
7925unicode_lstrip(PyUnicodeObject *self, PyObject *args)
7926{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007927 if (PyTuple_GET_SIZE(args) == 0)
7928 return do_strip(self, LEFTSTRIP); /* Common case */
7929 else
7930 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007931}
7932
7933
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007934PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007935 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007936\n\
7937Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007938If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007939
7940static PyObject *
7941unicode_rstrip(PyUnicodeObject *self, PyObject *args)
7942{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007943 if (PyTuple_GET_SIZE(args) == 0)
7944 return do_strip(self, RIGHTSTRIP); /* Common case */
7945 else
7946 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007947}
7948
7949
Guido van Rossumd57fd912000-03-10 22:53:23 +00007950static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +00007951unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007952{
7953 PyUnicodeObject *u;
7954 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007955 Py_ssize_t nchars;
Tim Peters8f422462000-09-09 06:13:41 +00007956 size_t nbytes;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007957
Georg Brandl222de0f2009-04-12 12:01:50 +00007958 if (len < 1) {
7959 Py_INCREF(unicode_empty);
7960 return (PyObject *)unicode_empty;
7961 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007962
Tim Peters7a29bd52001-09-12 03:03:31 +00007963 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00007964 /* no repeat, return original string */
7965 Py_INCREF(str);
7966 return (PyObject*) str;
7967 }
Tim Peters8f422462000-09-09 06:13:41 +00007968
7969 /* ensure # of chars needed doesn't overflow int and # of bytes
7970 * needed doesn't overflow size_t
7971 */
7972 nchars = len * str->length;
Georg Brandl222de0f2009-04-12 12:01:50 +00007973 if (nchars / len != str->length) {
Tim Peters8f422462000-09-09 06:13:41 +00007974 PyErr_SetString(PyExc_OverflowError,
7975 "repeated string is too long");
7976 return NULL;
7977 }
7978 nbytes = (nchars + 1) * sizeof(Py_UNICODE);
7979 if (nbytes / sizeof(Py_UNICODE) != (size_t)(nchars + 1)) {
7980 PyErr_SetString(PyExc_OverflowError,
7981 "repeated string is too long");
7982 return NULL;
7983 }
7984 u = _PyUnicode_New(nchars);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007985 if (!u)
7986 return NULL;
7987
7988 p = u->str;
7989
Georg Brandl222de0f2009-04-12 12:01:50 +00007990 if (str->length == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00007991 Py_UNICODE_FILL(p, str->str[0], len);
7992 } else {
Georg Brandl222de0f2009-04-12 12:01:50 +00007993 Py_ssize_t done = str->length; /* number of characters copied this far */
7994 Py_UNICODE_COPY(p, str->str, str->length);
Benjamin Peterson29060642009-01-31 22:14:21 +00007995 while (done < nchars) {
Christian Heimescc47b052008-03-25 14:56:36 +00007996 Py_ssize_t n = (done <= nchars-done) ? done : nchars-done;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007997 Py_UNICODE_COPY(p+done, p, n);
7998 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00007999 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008000 }
8001
8002 return (PyObject*) u;
8003}
8004
8005PyObject *PyUnicode_Replace(PyObject *obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00008006 PyObject *subobj,
8007 PyObject *replobj,
8008 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008009{
8010 PyObject *self;
8011 PyObject *str1;
8012 PyObject *str2;
8013 PyObject *result;
8014
8015 self = PyUnicode_FromObject(obj);
8016 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008017 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008018 str1 = PyUnicode_FromObject(subobj);
8019 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008020 Py_DECREF(self);
8021 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008022 }
8023 str2 = PyUnicode_FromObject(replobj);
8024 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008025 Py_DECREF(self);
8026 Py_DECREF(str1);
8027 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008028 }
Tim Petersced69f82003-09-16 20:30:58 +00008029 result = replace((PyUnicodeObject *)self,
Benjamin Peterson29060642009-01-31 22:14:21 +00008030 (PyUnicodeObject *)str1,
8031 (PyUnicodeObject *)str2,
8032 maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008033 Py_DECREF(self);
8034 Py_DECREF(str1);
8035 Py_DECREF(str2);
8036 return result;
8037}
8038
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008039PyDoc_STRVAR(replace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008040 "S.replace (old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008041\n\
8042Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +00008043old replaced by new. If the optional argument count is\n\
8044given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008045
8046static PyObject*
8047unicode_replace(PyUnicodeObject *self, PyObject *args)
8048{
8049 PyUnicodeObject *str1;
8050 PyUnicodeObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008051 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008052 PyObject *result;
8053
Martin v. Löwis18e16552006-02-15 17:27:45 +00008054 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008055 return NULL;
8056 str1 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str1);
8057 if (str1 == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008058 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008059 str2 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str2);
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +00008060 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008061 Py_DECREF(str1);
8062 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +00008063 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008064
8065 result = replace(self, str1, str2, maxcount);
8066
8067 Py_DECREF(str1);
8068 Py_DECREF(str2);
8069 return result;
8070}
8071
8072static
8073PyObject *unicode_repr(PyObject *unicode)
8074{
Walter Dörwald79e913e2007-05-12 11:08:06 +00008075 PyObject *repr;
Walter Dörwald1ab83302007-05-18 17:15:44 +00008076 Py_UNICODE *p;
Walter Dörwald79e913e2007-05-12 11:08:06 +00008077 Py_UNICODE *s = PyUnicode_AS_UNICODE(unicode);
8078 Py_ssize_t size = PyUnicode_GET_SIZE(unicode);
8079
8080 /* XXX(nnorwitz): rather than over-allocating, it would be
8081 better to choose a different scheme. Perhaps scan the
8082 first N-chars of the string and allocate based on that size.
8083 */
8084 /* Initial allocation is based on the longest-possible unichr
8085 escape.
8086
8087 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
8088 unichr, so in this case it's the longest unichr escape. In
8089 narrow (UTF-16) builds this is five chars per source unichr
8090 since there are two unichrs in the surrogate pair, so in narrow
8091 (UTF-16) builds it's not the longest unichr escape.
8092
8093 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
8094 so in the narrow (UTF-16) build case it's the longest unichr
8095 escape.
8096 */
8097
Walter Dörwald1ab83302007-05-18 17:15:44 +00008098 repr = PyUnicode_FromUnicode(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00008099 2 /* quotes */
Walter Dörwald79e913e2007-05-12 11:08:06 +00008100#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00008101 + 10*size
Walter Dörwald79e913e2007-05-12 11:08:06 +00008102#else
Benjamin Peterson29060642009-01-31 22:14:21 +00008103 + 6*size
Walter Dörwald79e913e2007-05-12 11:08:06 +00008104#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00008105 + 1);
Walter Dörwald79e913e2007-05-12 11:08:06 +00008106 if (repr == NULL)
8107 return NULL;
8108
Walter Dörwald1ab83302007-05-18 17:15:44 +00008109 p = PyUnicode_AS_UNICODE(repr);
Walter Dörwald79e913e2007-05-12 11:08:06 +00008110
8111 /* Add quote */
8112 *p++ = (findchar(s, size, '\'') &&
8113 !findchar(s, size, '"')) ? '"' : '\'';
8114 while (size-- > 0) {
8115 Py_UNICODE ch = *s++;
8116
8117 /* Escape quotes and backslashes */
Walter Dörwald1ab83302007-05-18 17:15:44 +00008118 if ((ch == PyUnicode_AS_UNICODE(repr)[0]) || (ch == '\\')) {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008119 *p++ = '\\';
Walter Dörwald1ab83302007-05-18 17:15:44 +00008120 *p++ = ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00008121 continue;
8122 }
8123
Benjamin Peterson29060642009-01-31 22:14:21 +00008124 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +00008125 if (ch == '\t') {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008126 *p++ = '\\';
8127 *p++ = 't';
8128 }
8129 else if (ch == '\n') {
8130 *p++ = '\\';
8131 *p++ = 'n';
8132 }
8133 else if (ch == '\r') {
8134 *p++ = '\\';
8135 *p++ = 'r';
8136 }
8137
8138 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +00008139 else if (ch < ' ' || ch == 0x7F) {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008140 *p++ = '\\';
8141 *p++ = 'x';
8142 *p++ = hexdigits[(ch >> 4) & 0x000F];
8143 *p++ = hexdigits[ch & 0x000F];
8144 }
8145
Georg Brandl559e5d72008-06-11 18:37:52 +00008146 /* Copy ASCII characters as-is */
8147 else if (ch < 0x7F) {
8148 *p++ = ch;
8149 }
8150
Benjamin Peterson29060642009-01-31 22:14:21 +00008151 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +00008152 else {
8153 Py_UCS4 ucs = ch;
8154
8155#ifndef Py_UNICODE_WIDE
8156 Py_UNICODE ch2 = 0;
8157 /* Get code point from surrogate pair */
8158 if (size > 0) {
8159 ch2 = *s;
8160 if (ch >= 0xD800 && ch < 0xDC00 && ch2 >= 0xDC00
Benjamin Peterson29060642009-01-31 22:14:21 +00008161 && ch2 <= 0xDFFF) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008162 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF))
Benjamin Peterson29060642009-01-31 22:14:21 +00008163 + 0x00010000;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008164 s++;
Georg Brandl559e5d72008-06-11 18:37:52 +00008165 size--;
8166 }
8167 }
8168#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00008169 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +00008170 (categories Z* and C* except ASCII space)
8171 */
8172 if (!Py_UNICODE_ISPRINTABLE(ucs)) {
8173 /* Map 8-bit characters to '\xhh' */
8174 if (ucs <= 0xff) {
8175 *p++ = '\\';
8176 *p++ = 'x';
8177 *p++ = hexdigits[(ch >> 4) & 0x000F];
8178 *p++ = hexdigits[ch & 0x000F];
8179 }
8180 /* Map 21-bit characters to '\U00xxxxxx' */
8181 else if (ucs >= 0x10000) {
8182 *p++ = '\\';
8183 *p++ = 'U';
8184 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
8185 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
8186 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
8187 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
8188 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
8189 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
8190 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
8191 *p++ = hexdigits[ucs & 0x0000000F];
8192 }
8193 /* Map 16-bit characters to '\uxxxx' */
8194 else {
8195 *p++ = '\\';
8196 *p++ = 'u';
8197 *p++ = hexdigits[(ucs >> 12) & 0x000F];
8198 *p++ = hexdigits[(ucs >> 8) & 0x000F];
8199 *p++ = hexdigits[(ucs >> 4) & 0x000F];
8200 *p++ = hexdigits[ucs & 0x000F];
8201 }
8202 }
8203 /* Copy characters as-is */
8204 else {
8205 *p++ = ch;
8206#ifndef Py_UNICODE_WIDE
8207 if (ucs >= 0x10000)
8208 *p++ = ch2;
8209#endif
8210 }
8211 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00008212 }
8213 /* Add quote */
Walter Dörwald1ab83302007-05-18 17:15:44 +00008214 *p++ = PyUnicode_AS_UNICODE(repr)[0];
Walter Dörwald79e913e2007-05-12 11:08:06 +00008215
8216 *p = '\0';
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00008217 PyUnicode_Resize(&repr, p - PyUnicode_AS_UNICODE(repr));
Walter Dörwald79e913e2007-05-12 11:08:06 +00008218 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008219}
8220
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008221PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008222 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008223\n\
8224Return the highest index in S where substring sub is found,\n\
Guido van Rossum806c2462007-08-06 23:33:07 +00008225such that sub is contained within s[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008226arguments start and end are interpreted as in slice notation.\n\
8227\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008228Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008229
8230static PyObject *
8231unicode_rfind(PyUnicodeObject *self, PyObject *args)
8232{
Thomas Wouters477c8d52006-05-27 19:21:47 +00008233 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00008234 Py_ssize_t start;
8235 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008236 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008237
Christian Heimes9cd17752007-11-18 19:35:23 +00008238 if (!_ParseTupleFinds(args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008239 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008240
Thomas Wouters477c8d52006-05-27 19:21:47 +00008241 result = stringlib_rfind_slice(
8242 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
8243 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
8244 start, end
8245 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008246
8247 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008248
Christian Heimes217cfd12007-12-02 14:31:20 +00008249 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008250}
8251
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008252PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008253 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008254\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008255Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008256
8257static PyObject *
8258unicode_rindex(PyUnicodeObject *self, PyObject *args)
8259{
Thomas Wouters477c8d52006-05-27 19:21:47 +00008260 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00008261 Py_ssize_t start;
8262 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008263 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008264
Christian Heimes9cd17752007-11-18 19:35:23 +00008265 if (!_ParseTupleFinds(args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008266 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008267
Thomas Wouters477c8d52006-05-27 19:21:47 +00008268 result = stringlib_rfind_slice(
8269 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
8270 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
8271 start, end
8272 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008273
8274 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008275
Guido van Rossumd57fd912000-03-10 22:53:23 +00008276 if (result < 0) {
8277 PyErr_SetString(PyExc_ValueError, "substring not found");
8278 return NULL;
8279 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008280 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008281}
8282
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008283PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008284 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008285\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008286Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008287done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008288
8289static PyObject *
8290unicode_rjust(PyUnicodeObject *self, PyObject *args)
8291{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008292 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008293 Py_UNICODE fillchar = ' ';
8294
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008295 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008296 return NULL;
8297
Tim Peters7a29bd52001-09-12 03:03:31 +00008298 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008299 Py_INCREF(self);
8300 return (PyObject*) self;
8301 }
8302
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008303 return (PyObject*) pad(self, width - self->length, 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008304}
8305
Guido van Rossumd57fd912000-03-10 22:53:23 +00008306PyObject *PyUnicode_Split(PyObject *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00008307 PyObject *sep,
8308 Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008309{
8310 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008311
Guido van Rossumd57fd912000-03-10 22:53:23 +00008312 s = PyUnicode_FromObject(s);
8313 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008314 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00008315 if (sep != NULL) {
8316 sep = PyUnicode_FromObject(sep);
8317 if (sep == NULL) {
8318 Py_DECREF(s);
8319 return NULL;
8320 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008321 }
8322
8323 result = split((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
8324
8325 Py_DECREF(s);
8326 Py_XDECREF(sep);
8327 return result;
8328}
8329
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008330PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008331 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008332\n\
8333Return a list of the words in S, using sep as the\n\
8334delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00008335splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00008336whitespace string is a separator and empty strings are\n\
8337removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008338
8339static PyObject*
8340unicode_split(PyUnicodeObject *self, PyObject *args)
8341{
8342 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008343 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008344
Martin v. Löwis18e16552006-02-15 17:27:45 +00008345 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008346 return NULL;
8347
8348 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008349 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008350 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00008351 return split(self, (PyUnicodeObject *)substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008352 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008353 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008354}
8355
Thomas Wouters477c8d52006-05-27 19:21:47 +00008356PyObject *
8357PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
8358{
8359 PyObject* str_obj;
8360 PyObject* sep_obj;
8361 PyObject* out;
8362
8363 str_obj = PyUnicode_FromObject(str_in);
8364 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008365 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008366 sep_obj = PyUnicode_FromObject(sep_in);
8367 if (!sep_obj) {
8368 Py_DECREF(str_obj);
8369 return NULL;
8370 }
8371
8372 out = stringlib_partition(
8373 str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
8374 sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
8375 );
8376
8377 Py_DECREF(sep_obj);
8378 Py_DECREF(str_obj);
8379
8380 return out;
8381}
8382
8383
8384PyObject *
8385PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
8386{
8387 PyObject* str_obj;
8388 PyObject* sep_obj;
8389 PyObject* out;
8390
8391 str_obj = PyUnicode_FromObject(str_in);
8392 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008393 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008394 sep_obj = PyUnicode_FromObject(sep_in);
8395 if (!sep_obj) {
8396 Py_DECREF(str_obj);
8397 return NULL;
8398 }
8399
8400 out = stringlib_rpartition(
8401 str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
8402 sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
8403 );
8404
8405 Py_DECREF(sep_obj);
8406 Py_DECREF(str_obj);
8407
8408 return out;
8409}
8410
8411PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008412 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008413\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00008414Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008415the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008416found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00008417
8418static PyObject*
8419unicode_partition(PyUnicodeObject *self, PyObject *separator)
8420{
8421 return PyUnicode_Partition((PyObject *)self, separator);
8422}
8423
8424PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti4c81fbb2010-01-25 12:02:24 +00008425 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008426\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00008427Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008428the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008429separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00008430
8431static PyObject*
8432unicode_rpartition(PyUnicodeObject *self, PyObject *separator)
8433{
8434 return PyUnicode_RPartition((PyObject *)self, separator);
8435}
8436
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008437PyObject *PyUnicode_RSplit(PyObject *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00008438 PyObject *sep,
8439 Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008440{
8441 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008442
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008443 s = PyUnicode_FromObject(s);
8444 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008445 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00008446 if (sep != NULL) {
8447 sep = PyUnicode_FromObject(sep);
8448 if (sep == NULL) {
8449 Py_DECREF(s);
8450 return NULL;
8451 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008452 }
8453
8454 result = rsplit((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
8455
8456 Py_DECREF(s);
8457 Py_XDECREF(sep);
8458 return result;
8459}
8460
8461PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008462 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008463\n\
8464Return a list of the words in S, using sep as the\n\
8465delimiter string, starting at the end of the string and\n\
8466working to the front. If maxsplit is given, at most maxsplit\n\
8467splits are done. If sep is not specified, any whitespace string\n\
8468is a separator.");
8469
8470static PyObject*
8471unicode_rsplit(PyUnicodeObject *self, PyObject *args)
8472{
8473 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008474 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008475
Martin v. Löwis18e16552006-02-15 17:27:45 +00008476 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008477 return NULL;
8478
8479 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008480 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008481 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00008482 return rsplit(self, (PyUnicodeObject *)substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008483 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008484 return PyUnicode_RSplit((PyObject *)self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008485}
8486
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008487PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008488 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008489\n\
8490Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +00008491Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008492is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008493
8494static PyObject*
8495unicode_splitlines(PyUnicodeObject *self, PyObject *args)
8496{
Guido van Rossum86662912000-04-11 15:38:46 +00008497 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008498
Guido van Rossum86662912000-04-11 15:38:46 +00008499 if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008500 return NULL;
8501
Guido van Rossum86662912000-04-11 15:38:46 +00008502 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008503}
8504
8505static
Guido van Rossumf15a29f2007-05-04 00:41:39 +00008506PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008507{
Walter Dörwald346737f2007-05-31 10:44:43 +00008508 if (PyUnicode_CheckExact(self)) {
8509 Py_INCREF(self);
8510 return self;
8511 } else
8512 /* Subtype -- return genuine unicode string with the same value. */
8513 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(self),
8514 PyUnicode_GET_SIZE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +00008515}
8516
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008517PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008518 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008519\n\
8520Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008521and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008522
8523static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008524unicode_swapcase(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008525{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008526 return fixup(self, fixswapcase);
8527}
8528
Georg Brandlceee0772007-11-27 23:48:05 +00008529PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008530 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +00008531\n\
8532Return a translation table usable for str.translate().\n\
8533If there is only one argument, it must be a dictionary mapping Unicode\n\
8534ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008535Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +00008536If there are two arguments, they must be strings of equal length, and\n\
8537in the resulting dictionary, each character in x will be mapped to the\n\
8538character at the same position in y. If there is a third argument, it\n\
8539must be a string, whose characters will be mapped to None in the result.");
8540
8541static PyObject*
8542unicode_maketrans(PyUnicodeObject *null, PyObject *args)
8543{
8544 PyObject *x, *y = NULL, *z = NULL;
8545 PyObject *new = NULL, *key, *value;
8546 Py_ssize_t i = 0;
8547 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008548
Georg Brandlceee0772007-11-27 23:48:05 +00008549 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
8550 return NULL;
8551 new = PyDict_New();
8552 if (!new)
8553 return NULL;
8554 if (y != NULL) {
8555 /* x must be a string too, of equal length */
8556 Py_ssize_t ylen = PyUnicode_GET_SIZE(y);
8557 if (!PyUnicode_Check(x)) {
8558 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
8559 "be a string if there is a second argument");
8560 goto err;
8561 }
8562 if (PyUnicode_GET_SIZE(x) != ylen) {
8563 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
8564 "arguments must have equal length");
8565 goto err;
8566 }
8567 /* create entries for translating chars in x to those in y */
8568 for (i = 0; i < PyUnicode_GET_SIZE(x); i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +00008569 key = PyLong_FromLong(PyUnicode_AS_UNICODE(x)[i]);
8570 value = PyLong_FromLong(PyUnicode_AS_UNICODE(y)[i]);
Georg Brandlceee0772007-11-27 23:48:05 +00008571 if (!key || !value)
8572 goto err;
8573 res = PyDict_SetItem(new, key, value);
8574 Py_DECREF(key);
8575 Py_DECREF(value);
8576 if (res < 0)
8577 goto err;
8578 }
8579 /* create entries for deleting chars in z */
8580 if (z != NULL) {
8581 for (i = 0; i < PyUnicode_GET_SIZE(z); i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +00008582 key = PyLong_FromLong(PyUnicode_AS_UNICODE(z)[i]);
Georg Brandlceee0772007-11-27 23:48:05 +00008583 if (!key)
8584 goto err;
8585 res = PyDict_SetItem(new, key, Py_None);
8586 Py_DECREF(key);
8587 if (res < 0)
8588 goto err;
8589 }
8590 }
8591 } else {
8592 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +00008593 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +00008594 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
8595 "to maketrans it must be a dict");
8596 goto err;
8597 }
8598 /* copy entries into the new dict, converting string keys to int keys */
8599 while (PyDict_Next(x, &i, &key, &value)) {
8600 if (PyUnicode_Check(key)) {
8601 /* convert string keys to integer keys */
8602 PyObject *newkey;
8603 if (PyUnicode_GET_SIZE(key) != 1) {
8604 PyErr_SetString(PyExc_ValueError, "string keys in translate "
8605 "table must be of length 1");
8606 goto err;
8607 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008608 newkey = PyLong_FromLong(PyUnicode_AS_UNICODE(key)[0]);
Georg Brandlceee0772007-11-27 23:48:05 +00008609 if (!newkey)
8610 goto err;
8611 res = PyDict_SetItem(new, newkey, value);
8612 Py_DECREF(newkey);
8613 if (res < 0)
8614 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +00008615 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +00008616 /* just keep integer keys */
8617 if (PyDict_SetItem(new, key, value) < 0)
8618 goto err;
8619 } else {
8620 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
8621 "be strings or integers");
8622 goto err;
8623 }
8624 }
8625 }
8626 return new;
8627 err:
8628 Py_DECREF(new);
8629 return NULL;
8630}
8631
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008632PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008633 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008634\n\
8635Return a copy of the string S, where all characters have been mapped\n\
8636through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008637Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +00008638Unmapped characters are left untouched. Characters mapped to None\n\
8639are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008640
8641static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008642unicode_translate(PyUnicodeObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008643{
Georg Brandlceee0772007-11-27 23:48:05 +00008644 return PyUnicode_TranslateCharmap(self->str, self->length, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008645}
8646
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008647PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008648 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008649\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008650Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008651
8652static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008653unicode_upper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008654{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008655 return fixup(self, fixupper);
8656}
8657
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008658PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008659 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008660\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +00008661Pad a numeric string S with zeros on the left, to fill a field\n\
8662of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008663
8664static PyObject *
8665unicode_zfill(PyUnicodeObject *self, PyObject *args)
8666{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008667 Py_ssize_t fill;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008668 PyUnicodeObject *u;
8669
Martin v. Löwis18e16552006-02-15 17:27:45 +00008670 Py_ssize_t width;
8671 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008672 return NULL;
8673
8674 if (self->length >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +00008675 if (PyUnicode_CheckExact(self)) {
8676 Py_INCREF(self);
8677 return (PyObject*) self;
8678 }
8679 else
8680 return PyUnicode_FromUnicode(
8681 PyUnicode_AS_UNICODE(self),
8682 PyUnicode_GET_SIZE(self)
Benjamin Peterson29060642009-01-31 22:14:21 +00008683 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008684 }
8685
8686 fill = width - self->length;
8687
8688 u = pad(self, fill, 0, '0');
8689
Walter Dörwald068325e2002-04-15 13:36:47 +00008690 if (u == NULL)
8691 return NULL;
8692
Guido van Rossumd57fd912000-03-10 22:53:23 +00008693 if (u->str[fill] == '+' || u->str[fill] == '-') {
8694 /* move sign to beginning of string */
8695 u->str[0] = u->str[fill];
8696 u->str[fill] = '0';
8697 }
8698
8699 return (PyObject*) u;
8700}
Guido van Rossumd57fd912000-03-10 22:53:23 +00008701
8702#if 0
8703static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008704unicode_freelistsize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008705{
Christian Heimes2202f872008-02-06 14:31:34 +00008706 return PyLong_FromLong(numfree);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008707}
8708#endif
8709
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008710PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008711 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008712\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00008713Return True if S starts with the specified prefix, False otherwise.\n\
8714With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008715With optional end, stop comparing S at that position.\n\
8716prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008717
8718static PyObject *
8719unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00008720 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008721{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008722 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008723 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008724 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008725 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008726 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008727
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008728 if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
Benjamin Peterson29060642009-01-31 22:14:21 +00008729 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
8730 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008731 if (PyTuple_Check(subobj)) {
8732 Py_ssize_t i;
8733 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
8734 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +00008735 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008736 if (substring == NULL)
8737 return NULL;
8738 result = tailmatch(self, substring, start, end, -1);
8739 Py_DECREF(substring);
8740 if (result) {
8741 Py_RETURN_TRUE;
8742 }
8743 }
8744 /* nothing matched */
8745 Py_RETURN_FALSE;
8746 }
8747 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008748 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008749 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008750 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008751 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008752 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008753}
8754
8755
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008756PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008757 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008758\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00008759Return True if S ends with the specified suffix, False otherwise.\n\
8760With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008761With optional end, stop comparing S at that position.\n\
8762suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008763
8764static PyObject *
8765unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00008766 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008767{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008768 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008769 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008770 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008771 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008772 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008773
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008774 if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
Benjamin Peterson29060642009-01-31 22:14:21 +00008775 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
8776 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008777 if (PyTuple_Check(subobj)) {
8778 Py_ssize_t i;
8779 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
8780 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +00008781 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008782 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008783 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008784 result = tailmatch(self, substring, start, end, +1);
8785 Py_DECREF(substring);
8786 if (result) {
8787 Py_RETURN_TRUE;
8788 }
8789 }
8790 Py_RETURN_FALSE;
8791 }
8792 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008793 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008794 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008795
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008796 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008797 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008798 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008799}
8800
Eric Smith8c663262007-08-25 02:26:07 +00008801#include "stringlib/string_format.h"
8802
8803PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008804 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +00008805\n\
8806");
8807
Eric Smith4a7d76d2008-05-30 18:10:19 +00008808static PyObject *
8809unicode__format__(PyObject* self, PyObject* args)
8810{
8811 PyObject *format_spec;
8812
8813 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
8814 return NULL;
8815
8816 return _PyUnicode_FormatAdvanced(self,
8817 PyUnicode_AS_UNICODE(format_spec),
8818 PyUnicode_GET_SIZE(format_spec));
8819}
8820
Eric Smith8c663262007-08-25 02:26:07 +00008821PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008822 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +00008823\n\
8824");
8825
8826static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +00008827unicode__sizeof__(PyUnicodeObject *v)
8828{
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00008829 return PyLong_FromSsize_t(sizeof(PyUnicodeObject) +
8830 sizeof(Py_UNICODE) * (v->length + 1));
Georg Brandlc28e1fa2008-06-10 19:20:26 +00008831}
8832
8833PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008834 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00008835
8836static PyObject *
Guido van Rossum5d9113d2003-01-29 17:58:45 +00008837unicode_getnewargs(PyUnicodeObject *v)
8838{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008839 return Py_BuildValue("(u#)", v->str, v->length);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00008840}
8841
8842
Guido van Rossumd57fd912000-03-10 22:53:23 +00008843static PyMethodDef unicode_methods[] = {
8844
8845 /* Order is according to common usage: often used methods should
8846 appear first, since lookup is done sequentially. */
8847
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008848 {"encode", (PyCFunction) unicode_encode, METH_VARARGS, encode__doc__},
8849 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
8850 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008851 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008852 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
8853 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
8854 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
8855 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
8856 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
8857 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
8858 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00008859 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008860 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
8861 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
8862 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008863 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008864 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
8865 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
8866 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008867 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00008868 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008869 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008870 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008871 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
8872 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
8873 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
8874 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
8875 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
8876 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
8877 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
8878 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
8879 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
8880 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
8881 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
8882 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
8883 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
8884 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +00008885 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +00008886 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008887 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +00008888 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +00008889 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Eric Smithf6db4092007-08-27 23:52:26 +00008890 {"_formatter_field_name_split", (PyCFunction) formatter_field_name_split, METH_NOARGS},
8891 {"_formatter_parser", (PyCFunction) formatter_parser, METH_NOARGS},
Georg Brandlceee0772007-11-27 23:48:05 +00008892 {"maketrans", (PyCFunction) unicode_maketrans,
8893 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +00008894 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +00008895#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008896 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +00008897#endif
8898
8899#if 0
8900 /* This one is just used for debugging the implementation. */
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008901 {"freelistsize", (PyCFunction) unicode_freelistsize, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +00008902#endif
8903
Benjamin Peterson14339b62009-01-31 16:36:08 +00008904 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +00008905 {NULL, NULL}
8906};
8907
Neil Schemenauerce30bc92002-11-18 16:10:18 +00008908static PyObject *
8909unicode_mod(PyObject *v, PyObject *w)
8910{
Benjamin Peterson29060642009-01-31 22:14:21 +00008911 if (!PyUnicode_Check(v)) {
8912 Py_INCREF(Py_NotImplemented);
8913 return Py_NotImplemented;
8914 }
8915 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +00008916}
8917
8918static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008919 0, /*nb_add*/
8920 0, /*nb_subtract*/
8921 0, /*nb_multiply*/
8922 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +00008923};
8924
Guido van Rossumd57fd912000-03-10 22:53:23 +00008925static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008926 (lenfunc) unicode_length, /* sq_length */
8927 PyUnicode_Concat, /* sq_concat */
8928 (ssizeargfunc) unicode_repeat, /* sq_repeat */
8929 (ssizeargfunc) unicode_getitem, /* sq_item */
8930 0, /* sq_slice */
8931 0, /* sq_ass_item */
8932 0, /* sq_ass_slice */
8933 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +00008934};
8935
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008936static PyObject*
8937unicode_subscript(PyUnicodeObject* self, PyObject* item)
8938{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00008939 if (PyIndex_Check(item)) {
8940 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008941 if (i == -1 && PyErr_Occurred())
8942 return NULL;
8943 if (i < 0)
Martin v. Löwisdea59e52006-01-05 10:00:36 +00008944 i += PyUnicode_GET_SIZE(self);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008945 return unicode_getitem(self, i);
8946 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00008947 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008948 Py_UNICODE* source_buf;
8949 Py_UNICODE* result_buf;
8950 PyObject* result;
8951
Martin v. Löwisdea59e52006-01-05 10:00:36 +00008952 if (PySlice_GetIndicesEx((PySliceObject*)item, PyUnicode_GET_SIZE(self),
Benjamin Peterson29060642009-01-31 22:14:21 +00008953 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008954 return NULL;
8955 }
8956
8957 if (slicelength <= 0) {
8958 return PyUnicode_FromUnicode(NULL, 0);
Thomas Woutersed03b412007-08-28 21:37:11 +00008959 } else if (start == 0 && step == 1 && slicelength == self->length &&
8960 PyUnicode_CheckExact(self)) {
8961 Py_INCREF(self);
8962 return (PyObject *)self;
8963 } else if (step == 1) {
8964 return PyUnicode_FromUnicode(self->str + start, slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008965 } else {
8966 source_buf = PyUnicode_AS_UNICODE((PyObject*)self);
Christian Heimesb186d002008-03-18 15:15:01 +00008967 result_buf = (Py_UNICODE *)PyObject_MALLOC(slicelength*
8968 sizeof(Py_UNICODE));
Benjamin Peterson14339b62009-01-31 16:36:08 +00008969
Benjamin Peterson29060642009-01-31 22:14:21 +00008970 if (result_buf == NULL)
8971 return PyErr_NoMemory();
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008972
8973 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
8974 result_buf[i] = source_buf[cur];
8975 }
Tim Petersced69f82003-09-16 20:30:58 +00008976
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008977 result = PyUnicode_FromUnicode(result_buf, slicelength);
Christian Heimesb186d002008-03-18 15:15:01 +00008978 PyObject_FREE(result_buf);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008979 return result;
8980 }
8981 } else {
8982 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
8983 return NULL;
8984 }
8985}
8986
8987static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008988 (lenfunc)unicode_length, /* mp_length */
8989 (binaryfunc)unicode_subscript, /* mp_subscript */
8990 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008991};
8992
Guido van Rossumd57fd912000-03-10 22:53:23 +00008993
Guido van Rossumd57fd912000-03-10 22:53:23 +00008994/* Helpers for PyUnicode_Format() */
8995
8996static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00008997getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008998{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008999 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009000 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009001 (*p_argidx)++;
9002 if (arglen < 0)
9003 return args;
9004 else
9005 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009006 }
9007 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009008 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009009 return NULL;
9010}
9011
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009012/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009013
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009014static PyObject *
9015formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009016{
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009017 char *p;
9018 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009019 double x;
Tim Petersced69f82003-09-16 20:30:58 +00009020
Guido van Rossumd57fd912000-03-10 22:53:23 +00009021 x = PyFloat_AsDouble(v);
9022 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009023 return NULL;
9024
Guido van Rossumd57fd912000-03-10 22:53:23 +00009025 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009026 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +00009027
Eric Smith0923d1d2009-04-16 20:16:10 +00009028 p = PyOS_double_to_string(x, type, prec,
9029 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009030 if (p == NULL)
9031 return NULL;
9032 result = PyUnicode_FromStringAndSize(p, strlen(p));
Eric Smith0923d1d2009-04-16 20:16:10 +00009033 PyMem_Free(p);
9034 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009035}
9036
Tim Peters38fd5b62000-09-21 05:43:11 +00009037static PyObject*
9038formatlong(PyObject *val, int flags, int prec, int type)
9039{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009040 char *buf;
9041 int len;
9042 PyObject *str; /* temporary string object. */
9043 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +00009044
Benjamin Peterson14339b62009-01-31 16:36:08 +00009045 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
9046 if (!str)
9047 return NULL;
9048 result = PyUnicode_FromStringAndSize(buf, len);
9049 Py_DECREF(str);
9050 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +00009051}
9052
Guido van Rossumd57fd912000-03-10 22:53:23 +00009053static int
9054formatchar(Py_UNICODE *buf,
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009055 size_t buflen,
9056 PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009057{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00009058 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009059 if (PyUnicode_Check(v)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009060 if (PyUnicode_GET_SIZE(v) == 1) {
9061 buf[0] = PyUnicode_AS_UNICODE(v)[0];
9062 buf[1] = '\0';
9063 return 1;
9064 }
9065#ifndef Py_UNICODE_WIDE
9066 if (PyUnicode_GET_SIZE(v) == 2) {
9067 /* Decode a valid surrogate pair */
9068 int c0 = PyUnicode_AS_UNICODE(v)[0];
9069 int c1 = PyUnicode_AS_UNICODE(v)[1];
9070 if (0xD800 <= c0 && c0 <= 0xDBFF &&
9071 0xDC00 <= c1 && c1 <= 0xDFFF) {
9072 buf[0] = c0;
9073 buf[1] = c1;
9074 buf[2] = '\0';
9075 return 2;
9076 }
9077 }
9078#endif
9079 goto onError;
9080 }
9081 else {
9082 /* Integer input truncated to a character */
9083 long x;
9084 x = PyLong_AsLong(v);
9085 if (x == -1 && PyErr_Occurred())
9086 goto onError;
9087
9088 if (x < 0 || x > 0x10ffff) {
9089 PyErr_SetString(PyExc_OverflowError,
9090 "%c arg not in range(0x110000)");
9091 return -1;
9092 }
9093
9094#ifndef Py_UNICODE_WIDE
9095 if (x > 0xffff) {
9096 x -= 0x10000;
9097 buf[0] = (Py_UNICODE)(0xD800 | (x >> 10));
9098 buf[1] = (Py_UNICODE)(0xDC00 | (x & 0x3FF));
9099 return 2;
9100 }
9101#endif
9102 buf[0] = (Py_UNICODE) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009103 buf[1] = '\0';
9104 return 1;
9105 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00009106
Benjamin Peterson29060642009-01-31 22:14:21 +00009107 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009108 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009109 "%c requires int or char");
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009110 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009111}
9112
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009113/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009114 FORMATBUFLEN is the length of the buffer in which chars are formatted.
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009115*/
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009116#define FORMATBUFLEN (size_t)10
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009117
Guido van Rossumd57fd912000-03-10 22:53:23 +00009118PyObject *PyUnicode_Format(PyObject *format,
Benjamin Peterson29060642009-01-31 22:14:21 +00009119 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009120{
9121 Py_UNICODE *fmt, *res;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009122 Py_ssize_t fmtcnt, rescnt, reslen, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009123 int args_owned = 0;
9124 PyUnicodeObject *result = NULL;
9125 PyObject *dict = NULL;
9126 PyObject *uformat;
Tim Petersced69f82003-09-16 20:30:58 +00009127
Guido van Rossumd57fd912000-03-10 22:53:23 +00009128 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009129 PyErr_BadInternalCall();
9130 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009131 }
9132 uformat = PyUnicode_FromObject(format);
Fred Drakee4315f52000-05-09 19:53:39 +00009133 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009134 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009135 fmt = PyUnicode_AS_UNICODE(uformat);
9136 fmtcnt = PyUnicode_GET_SIZE(uformat);
9137
9138 reslen = rescnt = fmtcnt + 100;
9139 result = _PyUnicode_New(reslen);
9140 if (result == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009141 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009142 res = PyUnicode_AS_UNICODE(result);
9143
9144 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009145 arglen = PyTuple_Size(args);
9146 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009147 }
9148 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009149 arglen = -1;
9150 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009151 }
Christian Heimes90aa7642007-12-19 02:45:37 +00009152 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +00009153 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +00009154 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009155
9156 while (--fmtcnt >= 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009157 if (*fmt != '%') {
9158 if (--rescnt < 0) {
9159 rescnt = fmtcnt + 100;
9160 reslen += rescnt;
9161 if (_PyUnicode_Resize(&result, reslen) < 0)
9162 goto onError;
9163 res = PyUnicode_AS_UNICODE(result) + reslen - rescnt;
9164 --rescnt;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009165 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009166 *res++ = *fmt++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009167 }
9168 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009169 /* Got a format specifier */
9170 int flags = 0;
9171 Py_ssize_t width = -1;
9172 int prec = -1;
9173 Py_UNICODE c = '\0';
9174 Py_UNICODE fill;
9175 int isnumok;
9176 PyObject *v = NULL;
9177 PyObject *temp = NULL;
9178 Py_UNICODE *pbuf;
9179 Py_UNICODE sign;
9180 Py_ssize_t len;
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009181 Py_UNICODE formatbuf[FORMATBUFLEN]; /* For formatchar() */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009182
Benjamin Peterson29060642009-01-31 22:14:21 +00009183 fmt++;
9184 if (*fmt == '(') {
9185 Py_UNICODE *keystart;
9186 Py_ssize_t keylen;
9187 PyObject *key;
9188 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +00009189
Benjamin Peterson29060642009-01-31 22:14:21 +00009190 if (dict == NULL) {
9191 PyErr_SetString(PyExc_TypeError,
9192 "format requires a mapping");
9193 goto onError;
9194 }
9195 ++fmt;
9196 --fmtcnt;
9197 keystart = fmt;
9198 /* Skip over balanced parentheses */
9199 while (pcount > 0 && --fmtcnt >= 0) {
9200 if (*fmt == ')')
9201 --pcount;
9202 else if (*fmt == '(')
9203 ++pcount;
9204 fmt++;
9205 }
9206 keylen = fmt - keystart - 1;
9207 if (fmtcnt < 0 || pcount > 0) {
9208 PyErr_SetString(PyExc_ValueError,
9209 "incomplete format key");
9210 goto onError;
9211 }
9212#if 0
9213 /* keys are converted to strings using UTF-8 and
9214 then looked up since Python uses strings to hold
9215 variables names etc. in its namespaces and we
9216 wouldn't want to break common idioms. */
9217 key = PyUnicode_EncodeUTF8(keystart,
9218 keylen,
9219 NULL);
9220#else
9221 key = PyUnicode_FromUnicode(keystart, keylen);
9222#endif
9223 if (key == NULL)
9224 goto onError;
9225 if (args_owned) {
9226 Py_DECREF(args);
9227 args_owned = 0;
9228 }
9229 args = PyObject_GetItem(dict, key);
9230 Py_DECREF(key);
9231 if (args == NULL) {
9232 goto onError;
9233 }
9234 args_owned = 1;
9235 arglen = -1;
9236 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009237 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009238 while (--fmtcnt >= 0) {
9239 switch (c = *fmt++) {
9240 case '-': flags |= F_LJUST; continue;
9241 case '+': flags |= F_SIGN; continue;
9242 case ' ': flags |= F_BLANK; continue;
9243 case '#': flags |= F_ALT; continue;
9244 case '0': flags |= F_ZERO; continue;
9245 }
9246 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009247 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009248 if (c == '*') {
9249 v = getnextarg(args, arglen, &argidx);
9250 if (v == NULL)
9251 goto onError;
9252 if (!PyLong_Check(v)) {
9253 PyErr_SetString(PyExc_TypeError,
9254 "* wants int");
9255 goto onError;
9256 }
9257 width = PyLong_AsLong(v);
9258 if (width == -1 && PyErr_Occurred())
9259 goto onError;
9260 if (width < 0) {
9261 flags |= F_LJUST;
9262 width = -width;
9263 }
9264 if (--fmtcnt >= 0)
9265 c = *fmt++;
9266 }
9267 else if (c >= '0' && c <= '9') {
9268 width = c - '0';
9269 while (--fmtcnt >= 0) {
9270 c = *fmt++;
9271 if (c < '0' || c > '9')
9272 break;
9273 if ((width*10) / 10 != width) {
9274 PyErr_SetString(PyExc_ValueError,
9275 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009276 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00009277 }
9278 width = width*10 + (c - '0');
9279 }
9280 }
9281 if (c == '.') {
9282 prec = 0;
9283 if (--fmtcnt >= 0)
9284 c = *fmt++;
9285 if (c == '*') {
9286 v = getnextarg(args, arglen, &argidx);
9287 if (v == NULL)
9288 goto onError;
9289 if (!PyLong_Check(v)) {
9290 PyErr_SetString(PyExc_TypeError,
9291 "* wants int");
9292 goto onError;
9293 }
9294 prec = PyLong_AsLong(v);
9295 if (prec == -1 && PyErr_Occurred())
9296 goto onError;
9297 if (prec < 0)
9298 prec = 0;
9299 if (--fmtcnt >= 0)
9300 c = *fmt++;
9301 }
9302 else if (c >= '0' && c <= '9') {
9303 prec = c - '0';
9304 while (--fmtcnt >= 0) {
9305 c = Py_CHARMASK(*fmt++);
9306 if (c < '0' || c > '9')
9307 break;
9308 if ((prec*10) / 10 != prec) {
9309 PyErr_SetString(PyExc_ValueError,
9310 "prec too big");
9311 goto onError;
9312 }
9313 prec = prec*10 + (c - '0');
9314 }
9315 }
9316 } /* prec */
9317 if (fmtcnt >= 0) {
9318 if (c == 'h' || c == 'l' || c == 'L') {
9319 if (--fmtcnt >= 0)
9320 c = *fmt++;
9321 }
9322 }
9323 if (fmtcnt < 0) {
9324 PyErr_SetString(PyExc_ValueError,
9325 "incomplete format");
9326 goto onError;
9327 }
9328 if (c != '%') {
9329 v = getnextarg(args, arglen, &argidx);
9330 if (v == NULL)
9331 goto onError;
9332 }
9333 sign = 0;
9334 fill = ' ';
9335 switch (c) {
9336
9337 case '%':
9338 pbuf = formatbuf;
9339 /* presume that buffer length is at least 1 */
9340 pbuf[0] = '%';
9341 len = 1;
9342 break;
9343
9344 case 's':
9345 case 'r':
9346 case 'a':
Victor Stinnerabdb21a2010-03-22 12:53:14 +00009347 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +00009348 temp = v;
9349 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009350 }
9351 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009352 if (c == 's')
9353 temp = PyObject_Str(v);
9354 else if (c == 'r')
9355 temp = PyObject_Repr(v);
9356 else
9357 temp = PyObject_ASCII(v);
9358 if (temp == NULL)
9359 goto onError;
9360 if (PyUnicode_Check(temp))
9361 /* nothing to do */;
9362 else {
9363 Py_DECREF(temp);
9364 PyErr_SetString(PyExc_TypeError,
9365 "%s argument has non-string str()");
9366 goto onError;
9367 }
9368 }
9369 pbuf = PyUnicode_AS_UNICODE(temp);
9370 len = PyUnicode_GET_SIZE(temp);
9371 if (prec >= 0 && len > prec)
9372 len = prec;
9373 break;
9374
9375 case 'i':
9376 case 'd':
9377 case 'u':
9378 case 'o':
9379 case 'x':
9380 case 'X':
9381 if (c == 'i')
9382 c = 'd';
9383 isnumok = 0;
9384 if (PyNumber_Check(v)) {
9385 PyObject *iobj=NULL;
9386
9387 if (PyLong_Check(v)) {
9388 iobj = v;
9389 Py_INCREF(iobj);
9390 }
9391 else {
9392 iobj = PyNumber_Long(v);
9393 }
9394 if (iobj!=NULL) {
9395 if (PyLong_Check(iobj)) {
9396 isnumok = 1;
9397 temp = formatlong(iobj, flags, prec, c);
9398 Py_DECREF(iobj);
9399 if (!temp)
9400 goto onError;
9401 pbuf = PyUnicode_AS_UNICODE(temp);
9402 len = PyUnicode_GET_SIZE(temp);
9403 sign = 1;
9404 }
9405 else {
9406 Py_DECREF(iobj);
9407 }
9408 }
9409 }
9410 if (!isnumok) {
9411 PyErr_Format(PyExc_TypeError,
9412 "%%%c format: a number is required, "
9413 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
9414 goto onError;
9415 }
9416 if (flags & F_ZERO)
9417 fill = '0';
9418 break;
9419
9420 case 'e':
9421 case 'E':
9422 case 'f':
9423 case 'F':
9424 case 'g':
9425 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009426 temp = formatfloat(v, flags, prec, c);
9427 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +00009428 goto onError;
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009429 pbuf = PyUnicode_AS_UNICODE(temp);
9430 len = PyUnicode_GET_SIZE(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +00009431 sign = 1;
9432 if (flags & F_ZERO)
9433 fill = '0';
9434 break;
9435
9436 case 'c':
9437 pbuf = formatbuf;
9438 len = formatchar(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), v);
9439 if (len < 0)
9440 goto onError;
9441 break;
9442
9443 default:
9444 PyErr_Format(PyExc_ValueError,
9445 "unsupported format character '%c' (0x%x) "
9446 "at index %zd",
9447 (31<=c && c<=126) ? (char)c : '?',
9448 (int)c,
9449 (Py_ssize_t)(fmt - 1 -
9450 PyUnicode_AS_UNICODE(uformat)));
9451 goto onError;
9452 }
9453 if (sign) {
9454 if (*pbuf == '-' || *pbuf == '+') {
9455 sign = *pbuf++;
9456 len--;
9457 }
9458 else if (flags & F_SIGN)
9459 sign = '+';
9460 else if (flags & F_BLANK)
9461 sign = ' ';
9462 else
9463 sign = 0;
9464 }
9465 if (width < len)
9466 width = len;
9467 if (rescnt - (sign != 0) < width) {
9468 reslen -= rescnt;
9469 rescnt = width + fmtcnt + 100;
9470 reslen += rescnt;
9471 if (reslen < 0) {
9472 Py_XDECREF(temp);
9473 PyErr_NoMemory();
9474 goto onError;
9475 }
9476 if (_PyUnicode_Resize(&result, reslen) < 0) {
9477 Py_XDECREF(temp);
9478 goto onError;
9479 }
9480 res = PyUnicode_AS_UNICODE(result)
9481 + reslen - rescnt;
9482 }
9483 if (sign) {
9484 if (fill != ' ')
9485 *res++ = sign;
9486 rescnt--;
9487 if (width > len)
9488 width--;
9489 }
9490 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
9491 assert(pbuf[0] == '0');
9492 assert(pbuf[1] == c);
9493 if (fill != ' ') {
9494 *res++ = *pbuf++;
9495 *res++ = *pbuf++;
9496 }
9497 rescnt -= 2;
9498 width -= 2;
9499 if (width < 0)
9500 width = 0;
9501 len -= 2;
9502 }
9503 if (width > len && !(flags & F_LJUST)) {
9504 do {
9505 --rescnt;
9506 *res++ = fill;
9507 } while (--width > len);
9508 }
9509 if (fill == ' ') {
9510 if (sign)
9511 *res++ = sign;
9512 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
9513 assert(pbuf[0] == '0');
9514 assert(pbuf[1] == c);
9515 *res++ = *pbuf++;
9516 *res++ = *pbuf++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009517 }
9518 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009519 Py_UNICODE_COPY(res, pbuf, len);
9520 res += len;
9521 rescnt -= len;
9522 while (--width >= len) {
9523 --rescnt;
9524 *res++ = ' ';
9525 }
9526 if (dict && (argidx < arglen) && c != '%') {
9527 PyErr_SetString(PyExc_TypeError,
9528 "not all arguments converted during string formatting");
Thomas Woutersa96affe2006-03-12 00:29:36 +00009529 Py_XDECREF(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +00009530 goto onError;
9531 }
9532 Py_XDECREF(temp);
9533 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009534 } /* until end */
9535 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009536 PyErr_SetString(PyExc_TypeError,
9537 "not all arguments converted during string formatting");
9538 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009539 }
9540
Thomas Woutersa96affe2006-03-12 00:29:36 +00009541 if (_PyUnicode_Resize(&result, reslen - rescnt) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009542 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009543 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009544 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009545 }
9546 Py_DECREF(uformat);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009547 return (PyObject *)result;
9548
Benjamin Peterson29060642009-01-31 22:14:21 +00009549 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009550 Py_XDECREF(result);
9551 Py_DECREF(uformat);
9552 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009553 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009554 }
9555 return NULL;
9556}
9557
Jeremy Hylton938ace62002-07-17 16:30:39 +00009558static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +00009559unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
9560
Tim Peters6d6c1a32001-08-02 04:15:00 +00009561static PyObject *
9562unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9563{
Benjamin Peterson29060642009-01-31 22:14:21 +00009564 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009565 static char *kwlist[] = {"object", "encoding", "errors", 0};
9566 char *encoding = NULL;
9567 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00009568
Benjamin Peterson14339b62009-01-31 16:36:08 +00009569 if (type != &PyUnicode_Type)
9570 return unicode_subtype_new(type, args, kwds);
9571 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +00009572 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009573 return NULL;
9574 if (x == NULL)
9575 return (PyObject *)_PyUnicode_New(0);
9576 if (encoding == NULL && errors == NULL)
9577 return PyObject_Str(x);
9578 else
Benjamin Peterson29060642009-01-31 22:14:21 +00009579 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +00009580}
9581
Guido van Rossume023fe02001-08-30 03:12:59 +00009582static PyObject *
9583unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9584{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009585 PyUnicodeObject *tmp, *pnew;
9586 Py_ssize_t n;
Guido van Rossume023fe02001-08-30 03:12:59 +00009587
Benjamin Peterson14339b62009-01-31 16:36:08 +00009588 assert(PyType_IsSubtype(type, &PyUnicode_Type));
9589 tmp = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
9590 if (tmp == NULL)
9591 return NULL;
9592 assert(PyUnicode_Check(tmp));
9593 pnew = (PyUnicodeObject *) type->tp_alloc(type, n = tmp->length);
9594 if (pnew == NULL) {
9595 Py_DECREF(tmp);
9596 return NULL;
9597 }
9598 pnew->str = (Py_UNICODE*) PyObject_MALLOC(sizeof(Py_UNICODE) * (n+1));
9599 if (pnew->str == NULL) {
9600 _Py_ForgetReference((PyObject *)pnew);
9601 PyObject_Del(pnew);
9602 Py_DECREF(tmp);
9603 return PyErr_NoMemory();
9604 }
9605 Py_UNICODE_COPY(pnew->str, tmp->str, n+1);
9606 pnew->length = n;
9607 pnew->hash = tmp->hash;
9608 Py_DECREF(tmp);
9609 return (PyObject *)pnew;
Guido van Rossume023fe02001-08-30 03:12:59 +00009610}
9611
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009612PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +00009613 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00009614\n\
Collin Winterd474ce82007-08-07 19:42:11 +00009615Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +00009616encoding defaults to the current default string encoding.\n\
9617errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00009618
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009619static PyObject *unicode_iter(PyObject *seq);
9620
Guido van Rossumd57fd912000-03-10 22:53:23 +00009621PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00009622 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +00009623 "str", /* tp_name */
9624 sizeof(PyUnicodeObject), /* tp_size */
9625 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009626 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009627 (destructor)unicode_dealloc, /* tp_dealloc */
9628 0, /* tp_print */
9629 0, /* tp_getattr */
9630 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00009631 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009632 unicode_repr, /* tp_repr */
9633 &unicode_as_number, /* tp_as_number */
9634 &unicode_as_sequence, /* tp_as_sequence */
9635 &unicode_as_mapping, /* tp_as_mapping */
9636 (hashfunc) unicode_hash, /* tp_hash*/
9637 0, /* tp_call*/
9638 (reprfunc) unicode_str, /* tp_str */
9639 PyObject_GenericGetAttr, /* tp_getattro */
9640 0, /* tp_setattro */
9641 0, /* tp_as_buffer */
9642 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +00009643 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009644 unicode_doc, /* tp_doc */
9645 0, /* tp_traverse */
9646 0, /* tp_clear */
9647 PyUnicode_RichCompare, /* tp_richcompare */
9648 0, /* tp_weaklistoffset */
9649 unicode_iter, /* tp_iter */
9650 0, /* tp_iternext */
9651 unicode_methods, /* tp_methods */
9652 0, /* tp_members */
9653 0, /* tp_getset */
9654 &PyBaseObject_Type, /* tp_base */
9655 0, /* tp_dict */
9656 0, /* tp_descr_get */
9657 0, /* tp_descr_set */
9658 0, /* tp_dictoffset */
9659 0, /* tp_init */
9660 0, /* tp_alloc */
9661 unicode_new, /* tp_new */
9662 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009663};
9664
9665/* Initialize the Unicode implementation */
9666
Thomas Wouters78890102000-07-22 19:25:51 +00009667void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009668{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009669 int i;
9670
Thomas Wouters477c8d52006-05-27 19:21:47 +00009671 /* XXX - move this array to unicodectype.c ? */
9672 Py_UNICODE linebreak[] = {
9673 0x000A, /* LINE FEED */
9674 0x000D, /* CARRIAGE RETURN */
9675 0x001C, /* FILE SEPARATOR */
9676 0x001D, /* GROUP SEPARATOR */
9677 0x001E, /* RECORD SEPARATOR */
9678 0x0085, /* NEXT LINE */
9679 0x2028, /* LINE SEPARATOR */
9680 0x2029, /* PARAGRAPH SEPARATOR */
9681 };
9682
Fred Drakee4315f52000-05-09 19:53:39 +00009683 /* Init the implementation */
Christian Heimes2202f872008-02-06 14:31:34 +00009684 free_list = NULL;
9685 numfree = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009686 unicode_empty = _PyUnicode_New(0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009687 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00009688 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009689
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009690 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00009691 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +00009692 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009693 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +00009694
9695 /* initialize the linebreak bloom filter */
9696 bloom_linebreak = make_bloom_mask(
9697 linebreak, sizeof(linebreak) / sizeof(linebreak[0])
9698 );
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009699
9700 PyType_Ready(&EncodingMapType);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009701}
9702
9703/* Finalize the Unicode implementation */
9704
Christian Heimesa156e092008-02-16 07:38:31 +00009705int
9706PyUnicode_ClearFreeList(void)
9707{
9708 int freelist_size = numfree;
9709 PyUnicodeObject *u;
9710
9711 for (u = free_list; u != NULL;) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009712 PyUnicodeObject *v = u;
9713 u = *(PyUnicodeObject **)u;
9714 if (v->str)
9715 PyObject_DEL(v->str);
9716 Py_XDECREF(v->defenc);
9717 PyObject_Del(v);
9718 numfree--;
Christian Heimesa156e092008-02-16 07:38:31 +00009719 }
9720 free_list = NULL;
9721 assert(numfree == 0);
9722 return freelist_size;
9723}
9724
Guido van Rossumd57fd912000-03-10 22:53:23 +00009725void
Thomas Wouters78890102000-07-22 19:25:51 +00009726_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009727{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009728 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009729
Guido van Rossum4ae8ef82000-10-03 18:09:04 +00009730 Py_XDECREF(unicode_empty);
9731 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +00009732
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009733 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009734 if (unicode_latin1[i]) {
9735 Py_DECREF(unicode_latin1[i]);
9736 unicode_latin1[i] = NULL;
9737 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009738 }
Christian Heimesa156e092008-02-16 07:38:31 +00009739 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +00009740}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00009741
Walter Dörwald16807132007-05-25 13:52:07 +00009742void
9743PyUnicode_InternInPlace(PyObject **p)
9744{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009745 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
9746 PyObject *t;
9747 if (s == NULL || !PyUnicode_Check(s))
9748 Py_FatalError(
9749 "PyUnicode_InternInPlace: unicode strings only please!");
9750 /* If it's a subclass, we don't really know what putting
9751 it in the interned dict might do. */
9752 if (!PyUnicode_CheckExact(s))
9753 return;
9754 if (PyUnicode_CHECK_INTERNED(s))
9755 return;
9756 if (interned == NULL) {
9757 interned = PyDict_New();
9758 if (interned == NULL) {
9759 PyErr_Clear(); /* Don't leave an exception */
9760 return;
9761 }
9762 }
9763 /* It might be that the GetItem call fails even
9764 though the key is present in the dictionary,
9765 namely when this happens during a stack overflow. */
9766 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +00009767 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009768 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +00009769
Benjamin Peterson29060642009-01-31 22:14:21 +00009770 if (t) {
9771 Py_INCREF(t);
9772 Py_DECREF(*p);
9773 *p = t;
9774 return;
9775 }
Walter Dörwald16807132007-05-25 13:52:07 +00009776
Benjamin Peterson14339b62009-01-31 16:36:08 +00009777 PyThreadState_GET()->recursion_critical = 1;
9778 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
9779 PyErr_Clear();
9780 PyThreadState_GET()->recursion_critical = 0;
9781 return;
9782 }
9783 PyThreadState_GET()->recursion_critical = 0;
9784 /* The two references in interned are not counted by refcnt.
9785 The deallocator will take care of this */
9786 Py_REFCNT(s) -= 2;
9787 PyUnicode_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +00009788}
9789
9790void
9791PyUnicode_InternImmortal(PyObject **p)
9792{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009793 PyUnicode_InternInPlace(p);
9794 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
9795 PyUnicode_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
9796 Py_INCREF(*p);
9797 }
Walter Dörwald16807132007-05-25 13:52:07 +00009798}
9799
9800PyObject *
9801PyUnicode_InternFromString(const char *cp)
9802{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009803 PyObject *s = PyUnicode_FromString(cp);
9804 if (s == NULL)
9805 return NULL;
9806 PyUnicode_InternInPlace(&s);
9807 return s;
Walter Dörwald16807132007-05-25 13:52:07 +00009808}
9809
9810void _Py_ReleaseInternedUnicodeStrings(void)
9811{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009812 PyObject *keys;
9813 PyUnicodeObject *s;
9814 Py_ssize_t i, n;
9815 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +00009816
Benjamin Peterson14339b62009-01-31 16:36:08 +00009817 if (interned == NULL || !PyDict_Check(interned))
9818 return;
9819 keys = PyDict_Keys(interned);
9820 if (keys == NULL || !PyList_Check(keys)) {
9821 PyErr_Clear();
9822 return;
9823 }
Walter Dörwald16807132007-05-25 13:52:07 +00009824
Benjamin Peterson14339b62009-01-31 16:36:08 +00009825 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
9826 detector, interned unicode strings are not forcibly deallocated;
9827 rather, we give them their stolen references back, and then clear
9828 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +00009829
Benjamin Peterson14339b62009-01-31 16:36:08 +00009830 n = PyList_GET_SIZE(keys);
9831 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +00009832 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009833 for (i = 0; i < n; i++) {
9834 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
9835 switch (s->state) {
9836 case SSTATE_NOT_INTERNED:
9837 /* XXX Shouldn't happen */
9838 break;
9839 case SSTATE_INTERNED_IMMORTAL:
9840 Py_REFCNT(s) += 1;
9841 immortal_size += s->length;
9842 break;
9843 case SSTATE_INTERNED_MORTAL:
9844 Py_REFCNT(s) += 2;
9845 mortal_size += s->length;
9846 break;
9847 default:
9848 Py_FatalError("Inconsistent interned string state.");
9849 }
9850 s->state = SSTATE_NOT_INTERNED;
9851 }
9852 fprintf(stderr, "total size of all interned strings: "
9853 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
9854 "mortal/immortal\n", mortal_size, immortal_size);
9855 Py_DECREF(keys);
9856 PyDict_Clear(interned);
9857 Py_DECREF(interned);
9858 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +00009859}
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009860
9861
9862/********************* Unicode Iterator **************************/
9863
9864typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009865 PyObject_HEAD
9866 Py_ssize_t it_index;
9867 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009868} unicodeiterobject;
9869
9870static void
9871unicodeiter_dealloc(unicodeiterobject *it)
9872{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009873 _PyObject_GC_UNTRACK(it);
9874 Py_XDECREF(it->it_seq);
9875 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009876}
9877
9878static int
9879unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
9880{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009881 Py_VISIT(it->it_seq);
9882 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009883}
9884
9885static PyObject *
9886unicodeiter_next(unicodeiterobject *it)
9887{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009888 PyUnicodeObject *seq;
9889 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009890
Benjamin Peterson14339b62009-01-31 16:36:08 +00009891 assert(it != NULL);
9892 seq = it->it_seq;
9893 if (seq == NULL)
9894 return NULL;
9895 assert(PyUnicode_Check(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009896
Benjamin Peterson14339b62009-01-31 16:36:08 +00009897 if (it->it_index < PyUnicode_GET_SIZE(seq)) {
9898 item = PyUnicode_FromUnicode(
Benjamin Peterson29060642009-01-31 22:14:21 +00009899 PyUnicode_AS_UNICODE(seq)+it->it_index, 1);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009900 if (item != NULL)
9901 ++it->it_index;
9902 return item;
9903 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009904
Benjamin Peterson14339b62009-01-31 16:36:08 +00009905 Py_DECREF(seq);
9906 it->it_seq = NULL;
9907 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009908}
9909
9910static PyObject *
9911unicodeiter_len(unicodeiterobject *it)
9912{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009913 Py_ssize_t len = 0;
9914 if (it->it_seq)
9915 len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index;
9916 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009917}
9918
9919PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
9920
9921static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009922 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00009923 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +00009924 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009925};
9926
9927PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009928 PyVarObject_HEAD_INIT(&PyType_Type, 0)
9929 "str_iterator", /* tp_name */
9930 sizeof(unicodeiterobject), /* tp_basicsize */
9931 0, /* tp_itemsize */
9932 /* methods */
9933 (destructor)unicodeiter_dealloc, /* tp_dealloc */
9934 0, /* tp_print */
9935 0, /* tp_getattr */
9936 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00009937 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009938 0, /* tp_repr */
9939 0, /* tp_as_number */
9940 0, /* tp_as_sequence */
9941 0, /* tp_as_mapping */
9942 0, /* tp_hash */
9943 0, /* tp_call */
9944 0, /* tp_str */
9945 PyObject_GenericGetAttr, /* tp_getattro */
9946 0, /* tp_setattro */
9947 0, /* tp_as_buffer */
9948 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
9949 0, /* tp_doc */
9950 (traverseproc)unicodeiter_traverse, /* tp_traverse */
9951 0, /* tp_clear */
9952 0, /* tp_richcompare */
9953 0, /* tp_weaklistoffset */
9954 PyObject_SelfIter, /* tp_iter */
9955 (iternextfunc)unicodeiter_next, /* tp_iternext */
9956 unicodeiter_methods, /* tp_methods */
9957 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009958};
9959
9960static PyObject *
9961unicode_iter(PyObject *seq)
9962{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009963 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009964
Benjamin Peterson14339b62009-01-31 16:36:08 +00009965 if (!PyUnicode_Check(seq)) {
9966 PyErr_BadInternalCall();
9967 return NULL;
9968 }
9969 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
9970 if (it == NULL)
9971 return NULL;
9972 it->it_index = 0;
9973 Py_INCREF(seq);
9974 it->it_seq = (PyUnicodeObject *)seq;
9975 _PyObject_GC_TRACK(it);
9976 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009977}
9978
Martin v. Löwis5b222132007-06-10 09:51:05 +00009979size_t
9980Py_UNICODE_strlen(const Py_UNICODE *u)
9981{
9982 int res = 0;
9983 while(*u++)
9984 res++;
9985 return res;
9986}
9987
9988Py_UNICODE*
9989Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
9990{
9991 Py_UNICODE *u = s1;
9992 while ((*u++ = *s2++));
9993 return s1;
9994}
9995
9996Py_UNICODE*
9997Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
9998{
9999 Py_UNICODE *u = s1;
10000 while ((*u++ = *s2++))
10001 if (n-- == 0)
10002 break;
10003 return s1;
10004}
10005
10006int
10007Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
10008{
10009 while (*s1 && *s2 && *s1 == *s2)
10010 s1++, s2++;
10011 if (*s1 && *s2)
10012 return (*s1 < *s2) ? -1 : +1;
10013 if (*s1)
10014 return 1;
10015 if (*s2)
10016 return -1;
10017 return 0;
10018}
10019
10020Py_UNICODE*
10021Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
10022{
10023 const Py_UNICODE *p;
10024 for (p = s; *p; p++)
10025 if (*p == c)
10026 return (Py_UNICODE*)p;
10027 return NULL;
10028}
10029
10030
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010031#ifdef __cplusplus
10032}
10033#endif
10034
10035
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000010036/*
Benjamin Peterson29060642009-01-31 22:14:21 +000010037 Local variables:
10038 c-basic-offset: 4
10039 indent-tabs-mode: nil
10040 End:
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000010041*/